RawSql.php 12.6 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
 *  $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
19
 * <http://www.phpdoctrine.org>.
20
 */
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();
lsmith's avatar
lsmith committed
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
     */
lsmith's avatar
lsmith committed
69
    public function parseDqlQueryPart($queryPartName, $queryPart, $append = false)
lsmith's avatar
lsmith committed
70
    {
71
        if ($queryPartName == 'select') {
lsmith's avatar
lsmith committed
72 73 74 75 76 77 78 79 80 81 82 83
            $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;
        }
84
        
lsmith's avatar
lsmith committed
85
        return $this;
86
    }
lsmith's avatar
lsmith committed
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);
    }
lsmith's avatar
lsmith committed
96

97
    /**
98
     * Add select parts to fields.
99 100 101
     *
     * @param $queryPart sting The name of the querypart
     */
102
    private function _parseSelectFields($queryPart){
103 104
        preg_match_all('/{([^}{]*)}/U', $queryPart, $m);
        $this->fields = $m[1];
105
        $this->_sqlParts['select'] = array();
106
    }
lsmith's avatar
lsmith committed
107 108


zYne's avatar
zYne committed
109 110 111 112
    public function parseQuery($query)
    {
        return $this->parseDqlQuery($query);
    }
113
    /**
114 115 116 117 118
     * 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.
119
     *
120 121
     * @param string $query     query to be parsed
     * @return Doctrine_RawSql  this object
122
     */
123
    public function parseDqlQuery($query)
lsmith's avatar
lsmith committed
124
    {
125
        $this->_parseSelectFields($query);
126 127
        $this->clear();

128
        $tokens = $this->_tokenizer->sqlExplode($query, ' ');
129

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

171 172
        $this->_sqlParts = $parts;
        $this->_sqlParts['select'] = array();
lsmith's avatar
lsmith committed
173

doctrine's avatar
doctrine committed
174
        return $this;
175
    }
176

177
    /**
178 179
     * getSqlQuery
     * builds the sql query.
180
     *
zYne's avatar
zYne committed
181
     * @return string       the built sql query
182
     */
183
    public function getSqlQuery($params = array())
lsmith's avatar
lsmith committed
184
    {
185
        $select = array();
zYne's avatar
zYne committed
186

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

zYne's avatar
zYne committed
201
            $componentAlias = $this->getComponentAlias($e[0]);
lsmith's avatar
lsmith committed
202

lsmith's avatar
lsmith committed
203
            if ($e[1] == '*') {
204
                foreach ($this->_queryComponents[$componentAlias]['table']->getColumnNames() as $name) {
zYne's avatar
zYne committed
205
                    $field = $e[0] . '.' . $name;
zYne's avatar
zYne committed
206 207

                    $select[$componentAlias][$field] = $field . ' AS ' . $e[0] . '__' . $name;
208 209
                }
            } else {
zYne's avatar
zYne committed
210
                $field = $e[0] . '.' . $e[1];
zYne's avatar
zYne committed
211
                $select[$componentAlias][$field] = $field . ' AS ' . $e[0] . '__' . $e[1];
212 213
            }
        }
214

215 216
        // force-add all primary key fields

217 218
        foreach ($this->getTableAliasMap() as $tableAlias => $componentAlias) {
            $map = $this->_queryComponents[$componentAlias];
zYne's avatar
zYne committed
219

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

223
                if ( ! isset($this->_sqlParts['select'][$field])) {
zYne's avatar
zYne committed
224
                    $select[$componentAlias][$field] = $field . ' AS ' . $tableAlias . '__' . $key;
lsmith's avatar
lsmith committed
225
                }
226 227
            }
        }
lsmith's avatar
lsmith committed
228

zYne's avatar
zYne committed
229
        // first add the fields of the root component
230 231
        reset($this->_queryComponents);
        $componentAlias = key($this->_queryComponents);
232

zYne's avatar
zYne committed
233 234 235 236 237 238 239 240
        $q = 'SELECT ' . implode(', ', $select[$componentAlias]);
        unset($select[$componentAlias]);

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

242
        $string = $this->_createDiscriminatorConditionSql();
lsmith's avatar
lsmith committed
243
        if ( ! empty($string)) {
244
            $this->_sqlParts['where'][] = $string;
lsmith's avatar
lsmith committed
245
        }
246
        $copy = $this->_sqlParts;
247 248
        unset($copy['select']);

249 250 251 252 253 254 255
        $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']) : '';
256

lsmith's avatar
lsmith committed
257
        if ( ! empty($string)) {
258
            array_pop($this->_sqlParts['where']);
lsmith's avatar
lsmith committed
259
        }
260
        return $q;
261
    }
262

263 264
    /**
     * getFields
zYne's avatar
zYne committed
265
     * returns the fields associated with this parser
266
     *
zYne's avatar
zYne committed
267
     * @return array    all the fields associated with this parser
268
     */
lsmith's avatar
lsmith committed
269 270
    public function getFields()
    {
271 272
        return $this->fields;
    }
273

274 275 276 277 278
    /**
     * addComponent
     *
     * @param string $tableAlias
     * @param string $componentName
doctrine's avatar
doctrine committed
279
     * @return Doctrine_RawSql
280
     */
zYne's avatar
zYne committed
281
    public function addComponent($tableAlias, $path)
lsmith's avatar
lsmith committed
282
    {
zYne's avatar
zYne committed
283 284 285 286 287 288 289
        $tmp           = explode(' ', $path);
        $originalAlias = (count($tmp) > 1) ? end($tmp) : null;

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

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

pookey's avatar
pookey committed
291
        $table = null;
zYne's avatar
zYne committed
292 293 294

        $currPath = '';

295 296
        if (isset($this->_queryComponents[$e[0]])) {
            $table = $this->_queryComponents[$e[0]]['table'];
zYne's avatar
zYne committed
297

zYne's avatar
zYne committed
298
            $currPath = $parent = array_shift($e);
zYne's avatar
zYne committed
299 300
        }

lsmith's avatar
lsmith committed
301
        foreach ($e as $k => $component) {
zYne's avatar
zYne committed
302 303 304 305
            // get length of the previous path
            $length = strlen($currPath);

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

zYne's avatar
zYne committed
308 309 310 311 312
            $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
313
            } else {
zYne's avatar
zYne committed
314
                $componentAlias = $currPath;
lsmith's avatar
lsmith committed
315
            }
zYne's avatar
zYne committed
316 317
            if ( ! isset($table)) {
                $conn = Doctrine_Manager::getInstance()
zYne's avatar
zYne committed
318
                        ->getConnectionForComponent($component);
lsmith's avatar
lsmith committed
319

320
                $table = $conn->getClassMetadata($component);
321 322
                $this->_queryComponents[$componentAlias] = array(
                        'table' => $table, 'mapper' => $conn->getMapper($component));
zYne's avatar
zYne committed
323
            } else {
zYne's avatar
zYne committed
324
                $relation = $table->getRelation($component);
325

326 327
                $this->_queryComponents[$componentAlias] = array(
                        'table'    => $relation->getTable(),
328
                        'mapper'   => $this->_conn->getMapper($component),
329 330
                        'parent'   => $parent,
                        'relation' => $relation);
pookey's avatar
pookey committed
331
            }
332
            $this->addSqlTableAlias($tableAlias, $componentAlias);
333

zYne's avatar
zYne committed
334
            $parent = $currPath;
335
        }
lsmith's avatar
lsmith committed
336

doctrine's avatar
doctrine committed
337
        return $this;
338
    }
339
}