RawSql.php 12.4 KB
Newer Older
1
<?php
lsmith's avatar
lsmith committed
2
/*
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 *  $Id$
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.phpdoctrine.com>.
 */
21
Doctrine::autoload('Doctrine_Query_Abstract');
22 23 24
/**
 * Doctrine_RawSql
 *
25 26 27 28 29 30
 * Doctrine_RawSql is an implementation of Doctrine_Query_Abstract that skips the entire
 * DQL parsing procedure. The "DQL" that is passed to a RawSql query object for execution
 * is considered to be plain SQL and will be used "as is". The only query part that is special
 * in a RawSql query is the SELECT part, which has a special syntax that provides Doctrine
 * with the necessary information to properly hydrate the query results.
 *
31
 * @package     Doctrine
32
 * @subpackage  RawSql
33 34 35 36 37 38
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link        www.phpdoctrine.com
 * @since       1.0
 * @version     $Revision$
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 */
39
class Doctrine_RawSql extends Doctrine_Query_Abstract
lsmith's avatar
lsmith committed
40
{
41 42 43
    /**
     * @var array $fields
     */
zYne's avatar
zYne committed
44
    private $fields = array();
45 46 47 48 49 50 51 52
    
    /**
     * @deprecated
     */
    public function parseQueryPart($queryPartName, $queryPart, $append = false)
    {
        return $this->parseDqlQueryPart($queryPartName, $queryPart, $append);
    }
53

54
    /**
55 56 57 58 59 60
     * parseDqlQueryPart
     * parses given DQL query part. Overrides Doctrine_Query_Abstract::parseDqlQueryPart().
     * This implementation does no parsing at all, except of the SELECT portion of the query
     * which is special in RawSql queries. The entire remaining parts are used "as is", so
     * the user of the RawSql query is responsible for writing SQL that is portable between
     * different DBMS.
61
     *
62 63 64
     * @param string $queryPartName     the name of the query part
     * @param string $queryPart         query part to be parsed
     * @param boolean $append           whether or not to append the query part to its stack
65
     *                                  if false is given, this method will overwrite
66 67
     *                                  the given query part stack with $queryPart
     * @return Doctrine_Query           this object
68
     */
69
 	public function parseDqlQueryPart($queryPartName, $queryPart, $append = false)
lsmith's avatar
lsmith committed
70
    {
71
        if ($queryPartName == 'select') {
72 73 74 75 76 77 78 79 80 81 82 83 84
     	    $this->_parseSelectFields($queryPart);
     	    return $this;
     	}
     	if ( ! isset($this->parts[$queryPartName])) {
     	    $this->_sqlParts[$queryPartName] = array();
     	}
     	
     	if ( ! $append) {
     	    $this->_sqlParts[$queryPartName] = array($queryPart);
     	} else {
     	    $this->_sqlParts[$queryPartName][] = $queryPart;
     	}
     	return $this;
85
    }
86 87 88 89 90 91 92 93 94 95
    
    /**
     * Adds a DQL query part. Overrides Doctrine_Query_Abstract::_addDqlQueryPart().
     * This implementation for RawSql parses the new parts right away, generating the SQL.
     */
    protected function _addDqlQueryPart($queryPartName, $queryPart, $append = false)
    {
        return $this->parseQueryPart($queryPartName, $queryPart, $append);
    }
    
96
    /**
97
     * Add select parts to fields.
98 99 100
     *
     * @param $queryPart sting The name of the querypart
     */
101
    private function _parseSelectFields($queryPart){
102 103
        preg_match_all('/{([^}{]*)}/U', $queryPart, $m);
        $this->fields = $m[1];
104
        $this->_sqlParts['select'] = array();
105
    }
106
    
107
    /**
108 109 110 111 112
     * parseDqlQuery
     * parses an sql query and adds the parts to internal array.
     * Overrides Doctrine_Query_Abstract::parseDqlQuery().
     * This implementation simply tokenizes the provided query string and uses them
     * as SQL parts right away.
113
     *
114 115
     * @param string $query     query to be parsed
     * @return Doctrine_RawSql  this object
116
     */
117
    public function parseDqlQuery($query)
lsmith's avatar
lsmith committed
118
    {
119
        $this->_parseSelectFields($query);
120 121
        $this->clear();

122
        $tokens = $this->_tokenizer->sqlExplode($query, ' ');
123

124 125 126 127
        $parts = array();
        foreach ($tokens as $key => $part) {
            $partLowerCase = strtolower($part);
            switch ($partLowerCase) {
zYne's avatar
zYne committed
128 129 130 131 132 133
                case 'select':
                case 'from':
                case 'where':
                case 'limit':
                case 'offset':
                case 'having':
134 135 136
                    $type = $partLowerCase;
                    if ( ! isset($parts[$partLowerCase])) {
                        $parts[$partLowerCase] = array();
137 138
                    }
                    break;
zYne's avatar
zYne committed
139 140
                case 'order':
                case 'group':
141 142 143 144
                    $i = $key + 1;
                    if (isset($tokens[$i]) && strtolower($tokens[$i]) === 'by') {
                        $type = $partLowerCase . 'by';
                        $parts[$type] = array();
145
                    } else {
146 147
                        //not a keyword so we add it to the previous type
                        $parts[$type][] = $part;
148 149
                    }
                    break;
zYne's avatar
zYne committed
150
                case 'by':
151 152
                    continue;
                default:
153 154 155
                    //not a keyword so we add it to the previous type.
                    if ( ! isset($parts[$type][0])) {
                        $parts[$type][0] = $part;
156
                    } else {
157 158 159 160
                        // why does this add to index 0 and not append to the 
                        // array. If it had done that one could have used 
                        // parseQueryPart.
                        $parts[$type][0] .= ' '.$part;
161
                    }
162 163
            }
        }
164

165 166
        $this->_sqlParts = $parts;
        $this->_sqlParts['select'] = array();
lsmith's avatar
lsmith committed
167

doctrine's avatar
doctrine committed
168
        return $this;
169
    }
170

171
    /**
172 173
     * getSqlQuery
     * builds the sql query.
174
     *
zYne's avatar
zYne committed
175
     * @return string       the built sql query
176
     */
177 178
    public function getSqlQuery($params = array())
    {        
179
        $select = array();
zYne's avatar
zYne committed
180

lsmith's avatar
lsmith committed
181
        foreach ($this->fields as $field) {
zYne's avatar
zYne committed
182
            $e = explode('.', $field);
lsmith's avatar
lsmith committed
183
            if ( ! isset($e[1])) {
zYne's avatar
zYne committed
184
                throw new Doctrine_RawSql_Exception('All selected fields in Sql query must be in format tableAlias.fieldName');
lsmith's avatar
lsmith committed
185
            }
zYne's avatar
zYne committed
186
            // try to auto-add component
187
            if ( ! $this->hasSqlTableAlias($e[0])) {
188 189
                try {
                    $this->addComponent($e[0], ucwords($e[0]));
190
                } catch (Doctrine_Exception $exception) {
zYne's avatar
zYne committed
191
                    throw new Doctrine_RawSql_Exception('The associated component for table alias ' . $e[0] . ' couldn\'t be found.');
192 193 194
                }
            }

zYne's avatar
zYne committed
195 196
            $componentAlias = $this->getComponentAlias($e[0]);
            
lsmith's avatar
lsmith committed
197
            if ($e[1] == '*') {
198
                foreach ($this->_queryComponents[$componentAlias]['table']->getColumnNames() as $name) {
zYne's avatar
zYne committed
199
                    $field = $e[0] . '.' . $name;
zYne's avatar
zYne committed
200 201

                    $select[$componentAlias][$field] = $field . ' AS ' . $e[0] . '__' . $name;
202 203
                }
            } else {
zYne's avatar
zYne committed
204
                $field = $e[0] . '.' . $e[1];
zYne's avatar
zYne committed
205
                $select[$componentAlias][$field] = $field . ' AS ' . $e[0] . '__' . $e[1];
206 207
            }
        }
208

209 210
        // force-add all primary key fields

211 212
        foreach ($this->getTableAliasMap() as $tableAlias => $componentAlias) {
            $map = $this->_queryComponents[$componentAlias];
zYne's avatar
zYne committed
213

romanb's avatar
romanb committed
214
            foreach ((array) $map['table']->getIdentifierColumnNames() as $key) {
zYne's avatar
zYne committed
215 216
                $field = $tableAlias . '.' . $key;

217
                if ( ! isset($this->_sqlParts['select'][$field])) {
zYne's avatar
zYne committed
218
                    $select[$componentAlias][$field] = $field . ' AS ' . $tableAlias . '__' . $key;
lsmith's avatar
lsmith committed
219
                }
220 221
            }
        }
zYne's avatar
zYne committed
222 223
        
        // first add the fields of the root component
224 225
        reset($this->_queryComponents);
        $componentAlias = key($this->_queryComponents);
226

zYne's avatar
zYne committed
227 228 229 230 231 232 233 234
        $q = 'SELECT ' . implode(', ', $select[$componentAlias]);
        unset($select[$componentAlias]);

        foreach ($select as $component => $fields) {
            if ( ! empty($fields)) {
                $q .= ', ' . implode(', ', $fields);
            }
        }
235

236
        $string = $this->applyInheritance();
lsmith's avatar
lsmith committed
237
        if ( ! empty($string)) {
238
            $this->_sqlParts['where'][] = $string;
lsmith's avatar
lsmith committed
239
        }
240
        $copy = $this->_sqlParts;
241 242
        unset($copy['select']);

243 244 245 246 247 248 249
        $q .= ( ! empty($this->_sqlParts['from']))?    ' FROM '     . implode(' ', $this->_sqlParts['from']) : '';
        $q .= ( ! empty($this->_sqlParts['where']))?   ' WHERE '    . implode(' AND ', $this->_sqlParts['where']) : '';
        $q .= ( ! empty($this->_sqlParts['groupby']))? ' GROUP BY ' . implode(', ', $this->_sqlParts['groupby']) : '';
        $q .= ( ! empty($this->_sqlParts['having']))?  ' HAVING '   . implode(' AND ', $this->_sqlParts['having']) : '';
        $q .= ( ! empty($this->_sqlParts['orderby']))? ' ORDER BY ' . implode(', ', $this->_sqlParts['orderby']) : '';
        $q .= ( ! empty($this->_sqlParts['limit']))?   ' LIMIT ' . implode(' ', $this->_sqlParts['limit']) : '';
        $q .= ( ! empty($this->_sqlParts['offset']))?  ' OFFSET ' . implode(' ', $this->_sqlParts['offset']) : '';
250

lsmith's avatar
lsmith committed
251
        if ( ! empty($string)) {
252
            array_pop($this->_sqlParts['where']);
lsmith's avatar
lsmith committed
253
        }
254
        return $q;
255
    }
256

257 258
    /**
     * getFields
zYne's avatar
zYne committed
259
     * returns the fields associated with this parser
260
     *
zYne's avatar
zYne committed
261
     * @return array    all the fields associated with this parser
262
     */
lsmith's avatar
lsmith committed
263 264
    public function getFields()
    {
265 266
        return $this->fields;
    }
267

268 269 270 271 272
    /**
     * addComponent
     *
     * @param string $tableAlias
     * @param string $componentName
doctrine's avatar
doctrine committed
273
     * @return Doctrine_RawSql
274
     */
zYne's avatar
zYne committed
275
    public function addComponent($tableAlias, $path)
lsmith's avatar
lsmith committed
276
    {
zYne's avatar
zYne committed
277 278 279 280 281 282 283
        $tmp           = explode(' ', $path);
        $originalAlias = (count($tmp) > 1) ? end($tmp) : null;

        $e = explode('.', $tmp[0]);

        $fullPath = $tmp[0];
        $fullLength = strlen($fullPath);
284

pookey's avatar
pookey committed
285
        $table = null;
zYne's avatar
zYne committed
286 287 288

        $currPath = '';

289 290
        if (isset($this->_queryComponents[$e[0]])) {
            $table = $this->_queryComponents[$e[0]]['table'];
zYne's avatar
zYne committed
291

zYne's avatar
zYne committed
292
            $currPath = $parent = array_shift($e);
zYne's avatar
zYne committed
293 294
        }

lsmith's avatar
lsmith committed
295
        foreach ($e as $k => $component) {
zYne's avatar
zYne committed
296 297 298 299
            // get length of the previous path
            $length = strlen($currPath);

            // build the current component path
zYne's avatar
zYne committed
300
            $currPath = ($currPath) ? $currPath . '.' . $component : $component;
301

zYne's avatar
zYne committed
302 303 304 305 306
            $delimeter = substr($fullPath, $length, 1);

            // if an alias is not given use the current path as an alias identifier
            if (strlen($currPath) === $fullLength && isset($originalAlias)) {
                $componentAlias = $originalAlias;
lsmith's avatar
lsmith committed
307
            } else {
zYne's avatar
zYne committed
308
                $componentAlias = $currPath;
lsmith's avatar
lsmith committed
309
            }
zYne's avatar
zYne committed
310 311
            if ( ! isset($table)) {
                $conn = Doctrine_Manager::getInstance()
zYne's avatar
zYne committed
312
                        ->getConnectionForComponent($component);
zYne's avatar
zYne committed
313 314
                        
                $table = $conn->getTable($component);
315
                $this->_queryComponents[$componentAlias] = array('table' => $table);
zYne's avatar
zYne committed
316
            } else {
zYne's avatar
zYne committed
317
                $relation = $table->getRelation($component);
318

319
                $this->_queryComponents[$componentAlias] = array('table'    => $relation->getTable(),
zYne's avatar
zYne committed
320 321
                                                          'parent'   => $parent,
                                                          'relation' => $relation);
pookey's avatar
pookey committed
322
            }
323
            $this->addSqlTableAlias($tableAlias, $componentAlias);
324

zYne's avatar
zYne committed
325
            $parent = $currPath;
326
        }
lsmith's avatar
lsmith committed
327

doctrine's avatar
doctrine committed
328
        return $this;
329
    }
330
}