Subversion-Projekte lars-tiefland.php_share

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
1 lars 1
<?php
2
/*
3
 *  $Id: Query.php 7674 2010-06-08 22:59:01Z jwage $
4
 *
5
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
12
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
13
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
14
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
15
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
16
 *
17
 * This software consists of voluntary contributions made by many individuals
18
 * and is licensed under the LGPL. For more information, see
19
 * <http://www.doctrine-project.org>.
20
 */
21
 
22
/**
23
 * Doctrine_Query
24
 * A Doctrine_Query object represents a DQL query. It is used to query databases for
25
 * data in an object-oriented fashion. A DQL query understands relations and inheritance
26
 * and is dbms independant.
27
 *
28
 * @package     Doctrine
29
 * @subpackage  Query
30
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
31
 * @link        www.doctrine-project.org
32
 * @since       1.0
33
 * @version     $Revision: 7674 $
34
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
35
 * @todo        Proposal: This class does far too much. It should have only 1 task: Collecting
36
 *              the DQL query parts and the query parameters (the query state and caching options/methods
37
 *              can remain here, too).
38
 *              The actual SQL construction could be done by a separate object (Doctrine_Query_SqlBuilder?)
39
 *              whose task it is to convert DQL into SQL.
40
 *              Furthermore the SqlBuilder? can then use other objects (Doctrine_Query_Tokenizer?),
41
 *              (Doctrine_Query_Parser(s)?) to accomplish his work. Doctrine_Query does not need
42
 *              to know the tokenizer/parsers. There could be extending
43
 *              implementations of SqlBuilder? that cover the specific SQL dialects.
44
 *              This would release Doctrine_Connection and the Doctrine_Connection_xxx classes
45
 *              from this tedious task.
46
 *              This would also largely reduce the currently huge interface of Doctrine_Query(_Abstract)
47
 *              and better hide all these transformation internals from the public Query API.
48
 *
49
 * @internal    The lifecycle of a Query object is the following:
50
 *              After construction the query object is empty. Through using the fluent
51
 *              query interface the user fills the query object with DQL parts and query parameters.
52
 *              These get collected in {@link $_dqlParts} and {@link $_params}, respectively.
53
 *              When the query is executed the first time, or when {@link getSqlQuery()}
54
 *              is called the first time, the collected DQL parts get parsed and the resulting
55
 *              connection-driver specific SQL is generated. The generated SQL parts are
56
 *              stored in {@link $_sqlParts} and the final resulting SQL query is stored in
57
 *              {@link $_sql}.
58
 */
59
class Doctrine_Query extends Doctrine_Query_Abstract implements Countable
60
{
61
    /**
62
     * @var array  The DQL keywords.
63
     */
64
    protected static $_keywords  = array('ALL',
65
                                         'AND',
66
                                         'ANY',
67
                                         'AS',
68
                                         'ASC',
69
                                         'AVG',
70
                                         'BETWEEN',
71
                                         'BIT_LENGTH',
72
                                         'BY',
73
                                         'CHARACTER_LENGTH',
74
                                         'CHAR_LENGTH',
75
                                         'CURRENT_DATE',
76
                                         'CURRENT_TIME',
77
                                         'CURRENT_TIMESTAMP',
78
                                         'DELETE',
79
                                         'DESC',
80
                                         'DISTINCT',
81
                                         'EMPTY',
82
                                         'EXISTS',
83
                                         'FALSE',
84
                                         'FETCH',
85
                                         'FROM',
86
                                         'GROUP',
87
                                         'HAVING',
88
                                         'IN',
89
                                         'INDEXBY',
90
                                         'INNER',
91
                                         'IS',
92
                                         'JOIN',
93
                                         'LEFT',
94
                                         'LIKE',
95
                                         'LOWER',
96
                                         'MEMBER',
97
                                         'MOD',
98
                                         'NEW',
99
                                         'NOT',
100
                                         'NULL',
101
                                         'OBJECT',
102
                                         'OF',
103
                                         'OR',
104
                                         'ORDER',
105
                                         'OUTER',
106
                                         'POSITION',
107
                                         'SELECT',
108
                                         'SOME',
109
                                         'TRIM',
110
                                         'TRUE',
111
                                         'UNKNOWN',
112
                                         'UPDATE',
113
                                         'WHERE');
114
 
115
    /**
116
     * @var array
117
     */
118
    protected $_subqueryAliases = array();
119
 
120
    /**
121
     * @var array $_aggregateAliasMap       an array containing all aggregate aliases, keys as dql aliases
122
     *                                      and values as sql aliases
123
     */
124
    protected $_aggregateAliasMap      = array();
125
 
126
    /**
127
     * @var array
128
     */
129
    protected $_pendingAggregates = array();
130
 
131
    /**
132
     * @param boolean $needsSubquery
133
     */
134
    protected $_needsSubquery = false;
135
 
136
    /**
137
     * @param boolean $isSubquery           whether or not this query object is a subquery of another
138
     *                                      query object
139
     */
140
    protected $_isSubquery;
141
 
142
    /**
143
     * @var array $_neededTables            an array containing the needed table aliases
144
     */
145
    protected $_neededTables = array();
146
 
147
    /**
148
     * @var array $pendingSubqueries        SELECT part subqueries, these are called pending subqueries since
149
     *                                      they cannot be parsed directly (some queries might be correlated)
150
     */
151
    protected $_pendingSubqueries = array();
152
 
153
    /**
154
     * @var array $_pendingFields           an array of pending fields (fields waiting to be parsed)
155
     */
156
    protected $_pendingFields = array();
157
 
158
    /**
159
     * @var array $_parsers                 an array of parser objects, each DQL query part has its own parser
160
     */
161
    protected $_parsers = array();
162
 
163
    /**
164
     * @var array $_pendingJoinConditions    an array containing pending joins
165
     */
166
    protected $_pendingJoinConditions = array();
167
 
168
    /**
169
     * @var array
170
     */
171
    protected $_expressionMap = array();
172
 
173
    /**
174
     * @var string $_sql            cached SQL query
175
     */
176
    protected $_sql;
177
 
178
    /**
179
     * create
180
     * returns a new Doctrine_Query object
181
     *
182
     * @param Doctrine_Connection $conn  optional connection parameter
183
     * @param string $class              Query class to instantiate
184
     * @return Doctrine_Query
185
     */
186
    public static function create($conn = null, $class = null)
187
    {
188
        if ( ! $class) {
189
            $class = Doctrine_Manager::getInstance()
190
                ->getAttribute(Doctrine_Core::ATTR_QUERY_CLASS);
191
        }
192
        return new $class($conn);
193
    }
194
 
195
    /**
196
     * Clears all the sql parts.
197
     */
198
    protected function clear()
199
    {
200
        $this->_preQueried = false;
201
        $this->_pendingJoinConditions = array();
202
        $this->_state = self::STATE_DIRTY;
203
    }
204
 
205
    /**
206
     * Resets the query to the state just after it has been instantiated.
207
     */
208
    public function reset()
209
    {
210
        $this->_subqueryAliases = array();
211
        $this->_aggregateAliasMap = array();
212
        $this->_pendingAggregates = array();
213
        $this->_pendingSubqueries = array();
214
        $this->_pendingFields = array();
215
        $this->_neededTables = array();
216
        $this->_expressionMap = array();
217
        $this->_subqueryAliases = array();
218
        $this->_needsSubquery = false;
219
        $this->_isLimitSubqueryUsed = false;
220
    }
221
 
222
    /**
223
     * createSubquery
224
     * creates a subquery
225
     *
226
     * @return Doctrine_Hydrate
227
     */
228
    public function createSubquery()
229
    {
230
        $class = get_class($this);
231
        $obj   = new $class();
232
 
233
        // copy the aliases to the subquery
234
        $obj->copySubqueryInfo($this);
235
 
236
        // this prevents the 'id' being selected, re ticket #307
237
        $obj->isSubquery(true);
238
 
239
        return $obj;
240
    }
241
 
242
    /**
243
     * addPendingJoinCondition
244
     *
245
     * @param string $componentAlias    component alias
246
     * @param string $joinCondition     dql join condition
247
     * @return Doctrine_Query           this object
248
     */
249
    public function addPendingJoinCondition($componentAlias, $joinCondition)
250
    {
251
        if ( ! isset($this->_pendingJoinConditions[$componentAlias])) {
252
            $this->_pendingJoinConditions[$componentAlias] = array();
253
        }
254
 
255
        $this->_pendingJoinConditions[$componentAlias][] = $joinCondition;
256
    }
257
 
258
    /**
259
     * fetchArray
260
     * Convenience method to execute using array fetching as hydration mode.
261
     *
262
     * @param string $params
263
     * @return array
264
     */
265
    public function fetchArray($params = array())
266
    {
267
        return $this->execute($params, Doctrine_Core::HYDRATE_ARRAY);
268
    }
269
 
270
    /**
271
     * fetchOne
272
     * Convenience method to execute the query and return the first item
273
     * of the collection.
274
     *
275
     * @param string $params        Query parameters
276
     * @param int $hydrationMode    Hydration mode: see Doctrine_Core::HYDRATE_* constants
277
     * @return mixed                Array or Doctrine_Collection, depending on hydration mode. False if no result.
278
     */
279
    public function fetchOne($params = array(), $hydrationMode = null)
280
    {
281
        $collection = $this->execute($params, $hydrationMode);
282
 
283
        if (is_scalar($collection)) {
284
            return $collection;
285
        }
286
 
287
        if (count($collection) === 0) {
288
            return false;
289
        }
290
 
291
        if ($collection instanceof Doctrine_Collection) {
292
            return $collection->getFirst();
293
        } else if (is_array($collection)) {
294
            return array_shift($collection);
295
        }
296
 
297
        return false;
298
    }
299
 
300
    /**
301
     * isSubquery
302
     * if $bool parameter is set this method sets the value of
303
     * Doctrine_Query::$isSubquery. If this value is set to true
304
     * the query object will not load the primary key fields of the selected
305
     * components.
306
     *
307
     * If null is given as the first parameter this method retrieves the current
308
     * value of Doctrine_Query::$isSubquery.
309
     *
310
     * @param boolean $bool     whether or not this query acts as a subquery
311
     * @return Doctrine_Query|bool
312
     */
313
    public function isSubquery($bool = null)
314
    {
315
        if ($bool === null) {
316
            return $this->_isSubquery;
317
        }
318
 
319
        $this->_isSubquery = (bool) $bool;
320
        return $this;
321
    }
322
 
323
    /**
324
     * getSqlAggregateAlias
325
     *
326
     * @param string $dqlAlias      the dql alias of an aggregate value
327
     * @return string
328
     */
329
    public function getSqlAggregateAlias($dqlAlias)
330
    {
331
        if (isset($this->_aggregateAliasMap[$dqlAlias])) {
332
            // mark the expression as used
333
            $this->_expressionMap[$dqlAlias][1] = true;
334
 
335
            return $this->_aggregateAliasMap[$dqlAlias];
336
        } else if ( ! empty($this->_pendingAggregates)) {
337
            $this->processPendingAggregates();
338
 
339
            return $this->getSqlAggregateAlias($dqlAlias);
340
        } else if( ! ($this->_conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_EXPR)){
341
            return $dqlAlias;
342
        } else {
343
            throw new Doctrine_Query_Exception('Unknown aggregate alias: ' . $dqlAlias);
344
        }
345
    }
346
 
347
    /**
348
     * Check if a dql alias has a sql aggregate alias
349
     *
350
     * @param string $dqlAlias
351
     * @return boolean
352
     */
353
    public function hasSqlAggregateAlias($dqlAlias)
354
    {
355
        try {
356
            $this->getSqlAggregateAlias($dqlAlias);
357
            return true;
358
        } catch (Exception $e) {
359
            return false;
360
        }
361
    }
362
 
363
    /**
364
     * Adjust the processed param index for "foo.bar IN ?" support
365
     *
366
     */
367
    public function adjustProcessedParam($index)
368
    {
369
        // Retrieve all params
370
        $params = $this->getInternalParams();
371
 
372
        // Retrieve already processed values
373
        $first = array_slice($params, 0, $index);
374
        $last = array_slice($params, $index, count($params) - $index);
375
 
376
        // Include array as values splicing the params array
377
        array_splice($last, 0, 1, $last[0]);
378
 
379
        // Put all param values into a single index
380
        $this->_execParams = array_merge($first, $last);
381
    }
382
 
383
    /**
384
     * Retrieves a specific DQL query part.
385
     *
386
     * @see Doctrine_Query_Abstract::$_dqlParts
387
     * <code>
388
     * var_dump($q->getDqlPart('where'));
389
     * // array(2) { [0] => string(8) 'name = ?' [1] => string(8) 'date > ?' }
390
     * </code>
391
     * @param string $queryPart     the name of the query part; can be:
392
     *     array from, containing strings;
393
     *     array select, containg string;
394
     *     boolean forUpdate;
395
     *     array set;
396
     *     array join;
397
     *     array where;
398
     *     array groupby;
399
     *     array having;
400
     *     array orderby, containing strings such as 'id ASC';
401
     *     array limit, containing numerics;
402
     *     array offset, containing numerics;
403
     * @return array
404
     */
405
    public function getDqlPart($queryPart)
406
    {
407
        if ( ! isset($this->_dqlParts[$queryPart])) {
408
           throw new Doctrine_Query_Exception('Unknown query part ' . $queryPart);
409
        }
410
 
411
        return $this->_dqlParts[$queryPart];
412
    }
413
 
414
    /**
415
     * contains
416
     *
417
     * Method to check if a arbitrary piece of dql exists
418
     *
419
     * @param string $dql Arbitrary piece of dql to check for
420
     * @return boolean
421
     */
422
    public function contains($dql)
423
    {
424
      return stripos($this->getDql(), $dql) === false ? false : true;
425
    }
426
 
427
    /**
428
     * processPendingFields
429
     * the fields in SELECT clause cannot be parsed until the components
430
     * in FROM clause are parsed, hence this method is called everytime a
431
     * specific component is being parsed. For instance, the wildcard '*'
432
     * is expanded in the list of columns.
433
     *
434
     * @throws Doctrine_Query_Exception     if unknown component alias has been given
435
     * @param string $componentAlias        the alias of the component
436
     * @return string SQL code
437
     * @todo Description: What is a 'pending field' (and are there non-pending fields, too)?
438
     *       What is 'processed'? (Meaning: What information is gathered & stored away)
439
     */
440
    public function processPendingFields($componentAlias)
441
    {
442
        $tableAlias = $this->getSqlTableAlias($componentAlias);
443
        $table = $this->_queryComponents[$componentAlias]['table'];
444
 
445
        if ( ! isset($this->_pendingFields[$componentAlias])) {
446
            if ($this->_hydrator->getHydrationMode() != Doctrine_Core::HYDRATE_NONE) {
447
                if ( ! $this->_isSubquery && $componentAlias == $this->getRootAlias()) {
448
                    throw new Doctrine_Query_Exception("The root class of the query (alias $componentAlias) "
449
                            . " must have at least one field selected.");
450
                }
451
            }
452
            return;
453
        }
454
 
455
        // At this point we know the component is FETCHED (either it's the base class of
456
        // the query (FROM xyz) or its a "fetch join").
457
 
458
        // Check that the parent join (if there is one), is a "fetch join", too.
459
        if ( ! $this->isSubquery() && isset($this->_queryComponents[$componentAlias]['parent'])) {
460
            $parentAlias = $this->_queryComponents[$componentAlias]['parent'];
461
            if (is_string($parentAlias) && ! isset($this->_pendingFields[$parentAlias])
462
                    && $this->_hydrator->getHydrationMode() != Doctrine_Core::HYDRATE_NONE
463
                    && $this->_hydrator->getHydrationMode() != Doctrine_Core::HYDRATE_SCALAR
464
                    && $this->_hydrator->getHydrationMode() != Doctrine_Core::HYDRATE_SINGLE_SCALAR) {
465
                throw new Doctrine_Query_Exception("The left side of the join between "
466
                        . "the aliases '$parentAlias' and '$componentAlias' must have at least"
467
                        . " the primary key field(s) selected.");
468
            }
469
        }
470
 
471
        $fields = $this->_pendingFields[$componentAlias];
472
 
473
        // check for wildcards
474
        if (in_array('*', $fields)) {
475
            $fields = $table->getFieldNames();
476
        } else {
477
            $driverClassName = $this->_hydrator->getHydratorDriverClassName();
478
            // only auto-add the primary key fields if this query object is not
479
            // a subquery of another query object or we're using a child of the Object Graph
480
            // hydrator
481
            if ( ! $this->_isSubquery && is_subclass_of($driverClassName, 'Doctrine_Hydrator_Graph')) {
482
                $fields = array_unique(array_merge((array) $table->getIdentifier(), $fields));
483
            }
484
        }
485
 
486
        $sql = array();
487
        foreach ($fields as $fieldAlias => $fieldName) {
488
            $columnName = $table->getColumnName($fieldName);
489
            if (($owner = $table->getColumnOwner($columnName)) !== null &&
490
                    $owner !== $table->getComponentName()) {
491
 
492
                $parent = $this->_conn->getTable($owner);
493
                $columnName = $parent->getColumnName($fieldName);
494
                $parentAlias = $this->getSqlTableAlias($componentAlias . '.' . $parent->getComponentName());
495
                $sql[] = $this->_conn->quoteIdentifier($parentAlias) . '.' . $this->_conn->quoteIdentifier($columnName)
496
                       . ' AS '
497
                       . $this->_conn->quoteIdentifier($tableAlias . '__' . $columnName);
498
            } else {
499
                // Fix for http://www.doctrine-project.org/jira/browse/DC-585
500
                // Take the field alias if available
501
                if (isset($this->_aggregateAliasMap[$fieldAlias])) {
502
                    $aliasSql = $this->_aggregateAliasMap[$fieldAlias];
503
                } else {
504
                    $columnName = $table->getColumnName($fieldName);
505
                    $aliasSql = $this->_conn->quoteIdentifier($tableAlias . '__' . $columnName);
506
                }
507
                $sql[] = $this->_conn->quoteIdentifier($tableAlias) . '.' . $this->_conn->quoteIdentifier($columnName)
508
                       . ' AS '
509
                       . $aliasSql;
510
            }
511
        }
512
 
513
        $this->_neededTables[] = $tableAlias;
514
 
515
        return implode(', ', $sql);
516
    }
517
 
518
    /**
519
     * Parses a nested field
520
     * <code>
521
     * $q->parseSelectField('u.Phonenumber.value');
522
     * </code>
523
     *
524
     * @param string $field
525
     * @throws Doctrine_Query_Exception     if unknown component alias has been given
526
     * @return string   SQL fragment
527
     * @todo Description: Explain what this method does. Is there a relation to parseSelect()?
528
     *       This method is not used from any class or testcase in the Doctrine package.
529
     *
530
     */
531
    public function parseSelectField($field)
532
    {
533
        $terms = explode('.', $field);
534
 
535
        if (isset($terms[1])) {
536
            $componentAlias = $terms[0];
537
            $field = $terms[1];
538
        } else {
539
            reset($this->_queryComponents);
540
            $componentAlias = key($this->_queryComponents);
541
            $fields = $terms[0];
542
        }
543
 
544
        $tableAlias = $this->getSqlTableAlias($componentAlias);
545
        $table      = $this->_queryComponents[$componentAlias]['table'];
546
 
547
 
548
        // check for wildcards
549
        if ($field === '*') {
550
            $sql = array();
551
 
552
            foreach ($table->getColumnNames() as $field) {
553
                $sql[] = $this->parseSelectField($componentAlias . '.' . $field);
554
            }
555
 
556
            return implode(', ', $sql);
557
        } else {
558
            $name = $table->getColumnName($field);
559
 
560
            $this->_neededTables[] = $tableAlias;
561
 
562
            return $this->_conn->quoteIdentifier($tableAlias . '.' . $name)
563
                   . ' AS '
564
                   . $this->_conn->quoteIdentifier($tableAlias . '__' . $name);
565
        }
566
    }
567
 
568
    /**
569
     * getExpressionOwner
570
     * returns the component alias for owner of given expression
571
     *
572
     * @param string $expr      expression from which to get to owner from
573
     * @return string           the component alias
574
     * @todo Description: What does it mean if a component is an 'owner' of an expression?
575
     *       What kind of 'expression' are we talking about here?
576
     */
577
    public function getExpressionOwner($expr)
578
    {
579
        if (strtoupper(substr(trim($expr, '( '), 0, 6)) !== 'SELECT') {
580
            // Fix for http://www.doctrine-project.org/jira/browse/DC-754
581
            $expr = preg_replace('/([\'\"])[^\1]*\1/', '', $expr);
582
            preg_match_all("/[a-z_][a-z0-9_]*\.[a-z_][a-z0-9_]*[\.[a-z0-9]+]*/i", $expr, $matches);
583
 
584
            $match = current($matches);
585
 
586
            if (isset($match[0])) {
587
                $terms = explode('.', $match[0]);
588
 
589
                return $terms[0];
590
            }
591
        }
592
        return $this->getRootAlias();
593
 
594
    }
595
 
596
    /**
597
     * parseSelect
598
     * parses the query select part and
599
     * adds selected fields to pendingFields array
600
     *
601
     * @param string $dql
602
     * @todo Description: What information is extracted (and then stored)?
603
     */
604
    public function parseSelect($dql)
605
    {
606
        $refs = $this->_tokenizer->sqlExplode($dql, ',');
607
 
608
        $pos   = strpos(trim($refs[0]), ' ');
609
        $first = substr($refs[0], 0, $pos);
610
 
611
        // check for DISTINCT keyword
612
        if ($first === 'DISTINCT') {
613
            $this->_sqlParts['distinct'] = true;
614
 
615
            $refs[0] = substr($refs[0], ++$pos);
616
        }
617
 
618
        $parsedComponents = array();
619
 
620
        foreach ($refs as $reference) {
621
            $reference = trim($reference);
622
 
623
            if (empty($reference)) {
624
                continue;
625
            }
626
 
627
            $terms = $this->_tokenizer->sqlExplode($reference, ' ');
628
            $pos   = strpos($terms[0], '(');
629
 
630
            if (count($terms) > 1 || $pos !== false) {
631
                $expression = array_shift($terms);
632
                $alias = array_pop($terms);
633
 
634
                if ( ! $alias) {
635
                    $alias = substr($expression, 0, $pos);
636
                }
637
 
638
                // Fix for http://www.doctrine-project.org/jira/browse/DC-706
639
                if ($pos !== false && substr($expression, 0, 1) !== "'" && substr($expression, 0, $pos) == '') {
640
                    $_queryComponents = $this->_queryComponents;
641
                    reset($_queryComponents);
642
                    $componentAlias = key($_queryComponents);
643
                } else {
644
                    $componentAlias = $this->getExpressionOwner($expression);
645
                }
646
 
647
                $expression = $this->parseClause($expression);
648
 
649
                $tableAlias = $this->getSqlTableAlias($componentAlias);
650
 
651
                $index    = count($this->_aggregateAliasMap);
652
 
653
                $sqlAlias = $this->_conn->quoteIdentifier($tableAlias . '__' . $index);
654
 
655
                $this->_sqlParts['select'][] = $expression . ' AS ' . $sqlAlias;
656
 
657
                $this->_aggregateAliasMap[$alias] = $sqlAlias;
658
                $this->_expressionMap[$alias][0] = $expression;
659
 
660
                $this->_queryComponents[$componentAlias]['agg'][$index] = $alias;
661
 
662
                $this->_neededTables[] = $tableAlias;
663
 
664
                // Fix for http://www.doctrine-project.org/jira/browse/DC-585
665
                // Add selected columns to pending fields
666
                if (preg_match('/^([^\(]+)\.(\'?)(.*?)(\'?)$/', $expression, $field)) {
667
                    $this->_pendingFields[$componentAlias][$alias] = $field[3];
668
                }
669
 
670
            } else {
671
                $e = explode('.', $terms[0]);
672
 
673
                if (isset($e[1])) {
674
                    $componentAlias = $e[0];
675
                    $field = $e[1];
676
                } else {
677
                    reset($this->_queryComponents);
678
                    $componentAlias = key($this->_queryComponents);
679
                    $field = $e[0];
680
                }
681
 
682
                $this->_pendingFields[$componentAlias][] = $field;
683
            }
684
        }
685
    }
686
 
687
    /**
688
     * parseClause
689
     * parses given DQL clause
690
     *
691
     * this method handles five tasks:
692
     *
693
     * 1. Converts all DQL functions to their native SQL equivalents
694
     * 2. Converts all component references to their table alias equivalents
695
     * 3. Converts all field names to actual column names
696
     * 4. Quotes all identifiers
697
     * 5. Parses nested clauses and subqueries recursively
698
     *
699
     * @return string   SQL string
700
     * @todo Description: What is a 'dql clause' (and what not)?
701
     *       Refactor: Too long & nesting level
702
     */
703
    public function parseClause($clause)
704
    {
705
        $clause = $this->_conn->dataDict->parseBoolean(trim($clause));
706
 
707
        if (is_numeric($clause)) {
708
           return $clause;
709
        }
710
 
711
        $terms = $this->_tokenizer->clauseExplode($clause, array(' ', '+', '-', '*', '/', '<', '>', '=', '>=', '<=', '&', '|'));
712
        $str = '';
713
 
714
        foreach ($terms as $term) {
715
            $pos = strpos($term[0], '(');
716
 
717
            if ($pos !== false && substr($term[0], 0, 1) !== "'") {
718
                $name = substr($term[0], 0, $pos);
719
 
720
                $term[0] = $this->parseFunctionExpression($term[0]);
721
            } else {
722
                if (substr($term[0], 0, 1) !== "'" && substr($term[0], -1) !== "'") {
723
                    if (strpos($term[0], '.') !== false) {
724
                        if ( ! is_numeric($term[0])) {
725
                            $e = explode('.', $term[0]);
726
 
727
                            $field = array_pop($e);
728
 
729
                            if ($this->getType() === Doctrine_Query::SELECT) {
730
                                $componentAlias = implode('.', $e);
731
 
732
                                if (empty($componentAlias)) {
733
                                    $componentAlias = $this->getRootAlias();
734
                                }
735
 
736
                                $this->load($componentAlias);
737
 
738
                                // check the existence of the component alias
739
                                if ( ! isset($this->_queryComponents[$componentAlias])) {
740
                                    throw new Doctrine_Query_Exception('Unknown component alias ' . $componentAlias);
741
                                }
742
 
743
                                $table = $this->_queryComponents[$componentAlias]['table'];
744
 
745
                                $def = $table->getDefinitionOf($field);
746
 
747
                                // get the actual field name from alias
748
                                $field = $table->getColumnName($field);
749
 
750
                                // check column existence
751
                                if ( ! $def) {
752
                                    throw new Doctrine_Query_Exception('Unknown column ' . $field);
753
                                }
754
 
755
                                if (isset($def['owner'])) {
756
                                    $componentAlias = $componentAlias . '.' . $def['owner'];
757
                                }
758
 
759
                                $tableAlias = $this->getSqlTableAlias($componentAlias);
760
 
761
                                // build sql expression
762
                                $term[0] = $this->_conn->quoteIdentifier($tableAlias)
763
                                         . '.'
764
                                         . $this->_conn->quoteIdentifier($field);
765
                            } else {
766
                                // build sql expression
767
                                $field = $this->getRoot()->getColumnName($field);
768
                                $term[0] = $this->_conn->quoteIdentifier($field);
769
                            }
770
                        }
771
                    } else {
772
                        if ( ! empty($term[0]) && ! in_array(strtoupper($term[0]), self::$_keywords) &&
773
                             ! is_numeric($term[0]) && $term[0] !== '?' && substr($term[0], 0, 1) !== ':') {
774
 
775
                            $componentAlias = $this->getRootAlias();
776
 
777
                            $found = false;
778
 
779
                            if ($componentAlias !== false && $componentAlias !== null) {
780
                                $table = $this->_queryComponents[$componentAlias]['table'];
781
 
782
                                // check column existence
783
                                if ($table->hasField($term[0])) {
784
                                    $found = true;
785
 
786
                                    $def = $table->getDefinitionOf($term[0]);
787
 
788
                                    // get the actual column name from field name
789
                                    $term[0] = $table->getColumnName($term[0]);
790
 
791
 
792
                                    if (isset($def['owner'])) {
793
                                        $componentAlias = $componentAlias . '.' . $def['owner'];
794
                                    }
795
 
796
                                    $tableAlias = $this->getSqlTableAlias($componentAlias);
797
 
798
                                    if ($this->getType() === Doctrine_Query::SELECT) {
799
                                        // build sql expression
800
                                        $term[0] = $this->_conn->quoteIdentifier($tableAlias)
801
                                                 . '.'
802
                                                 . $this->_conn->quoteIdentifier($term[0]);
803
                                    } else {
804
                                        // build sql expression
805
                                        $term[0] = $this->_conn->quoteIdentifier($term[0]);
806
                                    }
807
                                } else {
808
                                    $found = false;
809
                                }
810
                            }
811
 
812
                            if ( ! $found) {
813
                                $term[0] = $this->getSqlAggregateAlias($term[0]);
814
                            }
815
                        }
816
                    }
817
                }
818
            }
819
 
820
            $str .= $term[0] . $term[1];
821
        }
822
        return $str;
823
    }
824
 
825
    public function parseIdentifierReference($expr)
826
    {
827
 
828
    }
829
 
830
    public function parseFunctionExpression($expr, $parseCallback = null)
831
    {
832
        $pos = strpos($expr, '(');
833
        $name = substr($expr, 0, $pos);
834
 
835
        if ($name === '') {
836
            return $this->parseSubquery($expr);
837
        }
838
 
839
        $argStr = substr($expr, ($pos + 1), -1);
840
        $args   = array();
841
        // parse args
842
 
843
        foreach ($this->_tokenizer->sqlExplode($argStr, ',') as $arg) {
844
           $args[] = $parseCallback ? call_user_func_array($parseCallback, array($arg)) : $this->parseClause($arg);
845
        }
846
 
847
        // convert DQL function to its RDBMS specific equivalent
848
        try {
849
            $expr = call_user_func_array(array($this->_conn->expression, $name), $args);
850
        } catch (Doctrine_Expression_Exception $e) {
851
            throw new Doctrine_Query_Exception('Unknown function ' . $name . '.');
852
        }
853
 
854
        return $expr;
855
    }
856
 
857
 
858
    public function parseSubquery($subquery)
859
    {
860
        $trimmed = trim($this->_tokenizer->bracketTrim($subquery));
861
 
862
        // check for possible subqueries
863
        if (substr($trimmed, 0, 4) == 'FROM' || substr($trimmed, 0, 6) == 'SELECT') {
864
            // parse subquery
865
            $q = $this->createSubquery()->parseDqlQuery($trimmed);
866
            $trimmed = $q->getSqlQuery();
867
            $q->free();
868
        } else if (substr($trimmed, 0, 4) == 'SQL:') {
869
            $trimmed = substr($trimmed, 4);
870
        } else {
871
            $e = $this->_tokenizer->sqlExplode($trimmed, ',');
872
 
873
            $value = array();
874
            $index = false;
875
 
876
            foreach ($e as $part) {
877
                $value[] = $this->parseClause($part);
878
            }
879
 
880
            $trimmed = implode(', ', $value);
881
        }
882
 
883
        return '(' . $trimmed . ')';
884
    }
885
 
886
 
887
    /**
888
     * processPendingSubqueries
889
     * processes pending subqueries
890
     *
891
     * subqueries can only be processed when the query is fully constructed
892
     * since some subqueries may be correlated
893
     *
894
     * @return void
895
     * @todo Better description. i.e. What is a 'pending subquery'? What does 'processed' mean?
896
     *       (parsed? sql is constructed? some information is gathered?)
897
     */
898
    public function processPendingSubqueries()
899
    {
900
        foreach ($this->_pendingSubqueries as $value) {
901
            list($dql, $alias) = $value;
902
 
903
            $subquery = $this->createSubquery();
904
 
905
            $sql = $subquery->parseDqlQuery($dql, false)->getQuery();
906
            $subquery->free();
907
 
908
            reset($this->_queryComponents);
909
            $componentAlias = key($this->_queryComponents);
910
            $tableAlias = $this->getSqlTableAlias($componentAlias);
911
 
912
            $sqlAlias = $tableAlias . '__' . count($this->_aggregateAliasMap);
913
 
914
            $this->_sqlParts['select'][] = '(' . $sql . ') AS ' . $this->_conn->quoteIdentifier($sqlAlias);
915
 
916
            $this->_aggregateAliasMap[$alias] = $sqlAlias;
917
            $this->_queryComponents[$componentAlias]['agg'][] = $alias;
918
        }
919
        $this->_pendingSubqueries = array();
920
    }
921
 
922
    /**
923
     * processPendingAggregates
924
     * processes pending aggregate values for given component alias
925
     *
926
     * @return void
927
     * @todo Better description. i.e. What is a 'pending aggregate'? What does 'processed' mean?
928
     */
929
    public function processPendingAggregates()
930
    {
931
        // iterate trhough all aggregates
932
        foreach ($this->_pendingAggregates as $aggregate) {
933
            list ($expression, $components, $alias) = $aggregate;
934
 
935
            $tableAliases = array();
936
 
937
            // iterate through the component references within the aggregate function
938
            if ( ! empty ($components)) {
939
                foreach ($components as $component) {
940
 
941
                    if (is_numeric($component)) {
942
                        continue;
943
                    }
944
 
945
                    $e = explode('.', $component);
946
 
947
                    $field = array_pop($e);
948
                    $componentAlias = implode('.', $e);
949
 
950
                    // check the existence of the component alias
951
                    if ( ! isset($this->_queryComponents[$componentAlias])) {
952
                        throw new Doctrine_Query_Exception('Unknown component alias ' . $componentAlias);
953
                    }
954
 
955
                    $table = $this->_queryComponents[$componentAlias]['table'];
956
 
957
                    $field = $table->getColumnName($field);
958
 
959
                    // check column existence
960
                    if ( ! $table->hasColumn($field)) {
961
                        throw new Doctrine_Query_Exception('Unknown column ' . $field);
962
                    }
963
 
964
                    $sqlTableAlias = $this->getSqlTableAlias($componentAlias);
965
 
966
                    $tableAliases[$sqlTableAlias] = true;
967
 
968
                    // build sql expression
969
 
970
                    $identifier = $this->_conn->quoteIdentifier($sqlTableAlias . '.' . $field);
971
                    $expression = str_replace($component, $identifier, $expression);
972
                }
973
            }
974
 
975
            if (count($tableAliases) !== 1) {
976
                $componentAlias = reset($this->_tableAliasMap);
977
                $tableAlias = key($this->_tableAliasMap);
978
            }
979
 
980
            $index    = count($this->_aggregateAliasMap);
981
            $sqlAlias = $this->_conn->quoteIdentifier($tableAlias . '__' . $index);
982
 
983
            $this->_sqlParts['select'][] = $expression . ' AS ' . $sqlAlias;
984
 
985
            $this->_aggregateAliasMap[$alias] = $sqlAlias;
986
            $this->_expressionMap[$alias][0] = $expression;
987
 
988
            $this->_queryComponents[$componentAlias]['agg'][$index] = $alias;
989
 
990
            $this->_neededTables[] = $tableAlias;
991
        }
992
        // reset the state
993
        $this->_pendingAggregates = array();
994
    }
995
 
996
    /**
997
     * _buildSqlQueryBase
998
     * returns the base of the generated sql query
999
     * On mysql driver special strategy has to be used for DELETE statements
1000
     * (where is this special strategy??)
1001
     *
1002
     * @return string       the base of the generated sql query
1003
     */
1004
    protected function _buildSqlQueryBase()
1005
    {
1006
        switch ($this->_type) {
1007
            case self::DELETE:
1008
                $q = 'DELETE FROM ';
1009
            break;
1010
            case self::UPDATE:
1011
                $q = 'UPDATE ';
1012
            break;
1013
            case self::SELECT:
1014
                $distinct = ($this->_sqlParts['distinct']) ? 'DISTINCT ' : '';
1015
                $q = 'SELECT ' . $distinct . implode(', ', $this->_sqlParts['select']) . ' FROM ';
1016
            break;
1017
        }
1018
        return $q;
1019
    }
1020
 
1021
    /**
1022
     * _buildSqlFromPart
1023
     * builds the from part of the query and returns it
1024
     *
1025
     * @return string   the query sql from part
1026
     */
1027
    protected function _buildSqlFromPart($ignorePending = false)
1028
    {
1029
        $q = '';
1030
 
1031
        foreach ($this->_sqlParts['from'] as $k => $part) {
1032
            $e = explode(' ', $part);
1033
 
1034
            if ($k === 0) {
1035
                if ( ! $ignorePending && $this->_type == self::SELECT) {
1036
                    // We may still have pending conditions
1037
                    $alias = count($e) > 1
1038
                        ? $this->getComponentAlias($e[1])
1039
                        : null;
1040
                    $where = $this->_processPendingJoinConditions($alias);
1041
 
1042
                    // apply inheritance to WHERE part
1043
                    if ( ! empty($where)) {
1044
                        if (count($this->_sqlParts['where']) > 0) {
1045
                            $this->_sqlParts['where'][] = 'AND';
1046
                        }
1047
 
1048
                        if (substr($where, 0, 1) === '(' && substr($where, -1) === ')') {
1049
                            $this->_sqlParts['where'][] = $where;
1050
                        } else {
1051
                            $this->_sqlParts['where'][] = '(' . $where . ')';
1052
                        }
1053
                    }
1054
                }
1055
 
1056
                $q .= $part;
1057
 
1058
                continue;
1059
            }
1060
 
1061
            // preserve LEFT JOINs only if needed
1062
            // Check if it's JOIN, if not add a comma separator instead of space
1063
            if ( ! preg_match('/\bJOIN\b/i', $part) && ! isset($this->_pendingJoinConditions[$k])) {
1064
                $q .= ', ' . $part;
1065
            } else {
1066
                if (substr($part, 0, 9) === 'LEFT JOIN') {
1067
                    $aliases = array_merge($this->_subqueryAliases,
1068
                                array_keys($this->_neededTables));
1069
 
1070
                    if ( ! in_array($e[3], $aliases) && ! in_array($e[2], $aliases) && ! empty($this->_pendingFields)) {
1071
                        continue;
1072
                    }
1073
 
1074
                }
1075
 
1076
                if ( ! $ignorePending && isset($this->_pendingJoinConditions[$k])) {
1077
                    if (strpos($part, ' ON ') !== false) {
1078
                        $part .= ' AND ';
1079
                    } else {
1080
                        $part .= ' ON ';
1081
                    }
1082
 
1083
                    $part .= $this->_processPendingJoinConditions($k);
1084
                }
1085
 
1086
                $componentAlias = $this->getComponentAlias($e[3]);
1087
                $string = $this->getInheritanceCondition($componentAlias);
1088
 
1089
                if ($string) {
1090
                    $part = $part . ' AND ' . $string;
1091
                }
1092
                $q .= ' ' . $part;
1093
            }
1094
 
1095
            $this->_sqlParts['from'][$k] = $part;
1096
        }
1097
        return $q;
1098
    }
1099
 
1100
    /**
1101
     * Processes the pending join conditions, used for dynamically add conditions
1102
     * to root component/joined components without interfering in the main dql
1103
     * handling.
1104
     *
1105
     * @param string $alias Component Alias
1106
     * @return Processed pending conditions
1107
     */
1108
    protected function _processPendingJoinConditions($alias)
1109
    {
1110
        $parts = array();
1111
 
1112
        if ($alias !== null && isset($this->_pendingJoinConditions[$alias])) {
1113
            $parser = new Doctrine_Query_JoinCondition($this, $this->_tokenizer);
1114
 
1115
            foreach ($this->_pendingJoinConditions[$alias] as $joinCondition) {
1116
                $parts[] = $parser->parse($joinCondition);
1117
            }
1118
 
1119
            // FIX #1860 and #1876: Cannot unset them, otherwise query cannot be reused later
1120
            //unset($this->_pendingJoinConditions[$alias]);
1121
        }
1122
 
1123
        return (count($parts) > 0 ? '(' . implode(') AND (', $parts) . ')' : '');
1124
    }
1125
 
1126
    /**
1127
     * builds the sql query from the given parameters and applies things such as
1128
     * column aggregation inheritance and limit subqueries if needed
1129
     *
1130
     * @param array $params             an array of prepared statement params (needed only in mysql driver
1131
     *                                  when limit subquery algorithm is used)
1132
     * @param bool $limitSubquery Whether or not to try and apply the limit subquery algorithm
1133
     * @return string                   the built sql query
1134
     */
1135
    public function getSqlQuery($params = array(), $limitSubquery = true)
1136
    {
1137
        // Assign building/execution specific params
1138
        $this->_params['exec'] = $params;
1139
 
1140
        // Initialize prepared parameters array
1141
        $this->_execParams = $this->getFlattenedParams();
1142
 
1143
        if ($this->_state !== self::STATE_DIRTY) {
1144
            $this->fixArrayParameterValues($this->getInternalParams());
1145
 
1146
            // Return compiled SQL
1147
            return $this->_sql;
1148
        }
1149
        return $this->buildSqlQuery($limitSubquery);
1150
    }
1151
 
1152
    /**
1153
     * Build the SQL query from the DQL
1154
     *
1155
     * @param bool $limitSubquery Whether or not to try and apply the limit subquery algorithm
1156
     * @return string $sql The generated SQL string
1157
     */
1158
    public function buildSqlQuery($limitSubquery = true)
1159
    {
1160
        // reset the state
1161
        if ( ! $this->isSubquery()) {
1162
            $this->_queryComponents = array();
1163
            $this->_pendingAggregates = array();
1164
            $this->_aggregateAliasMap = array();
1165
        }
1166
 
1167
        $this->reset();
1168
 
1169
        // invoke the preQuery hook
1170
        $this->_preQuery();
1171
 
1172
        // process the DQL parts => generate the SQL parts.
1173
        // this will also populate the $_queryComponents.
1174
        foreach ($this->_dqlParts as $queryPartName => $queryParts) {
1175
            // If we are parsing FROM clause, we'll need to diff the queryComponents later
1176
            if ($queryPartName == 'from') {
1177
                // Pick queryComponents before processing
1178
                $queryComponentsBefore = $this->getQueryComponents();
1179
            }
1180
 
1181
            // FIX #1667: _sqlParts are cleaned inside _processDqlQueryPart.
1182
            if ($queryPartName != 'forUpdate') {
1183
                $this->_processDqlQueryPart($queryPartName, $queryParts);
1184
            }
1185
 
1186
            // We need to define the root alias
1187
            if ($queryPartName == 'from') {
1188
                // Pick queryComponents aftr processing
1189
                $queryComponentsAfter = $this->getQueryComponents();
1190
 
1191
                // Root alias is the key of difference of query components
1192
                $diffQueryComponents = array_diff_key($queryComponentsAfter, $queryComponentsBefore);
1193
                $this->_rootAlias = key($diffQueryComponents);
1194
            }
1195
        }
1196
        $this->_state = self::STATE_CLEAN;
1197
 
1198
        // Proceed with the generated SQL
1199
        if (empty($this->_sqlParts['from'])) {
1200
            return false;
1201
        }
1202
 
1203
        $needsSubQuery = false;
1204
        $subquery = '';
1205
        $map = $this->getRootDeclaration();
1206
        $table = $map['table'];
1207
        $rootAlias = $this->getRootAlias();
1208
 
1209
        if ( ! empty($this->_sqlParts['limit']) && $this->_needsSubquery &&
1210
                $table->getAttribute(Doctrine_Core::ATTR_QUERY_LIMIT) == Doctrine_Core::LIMIT_RECORDS) {
1211
            // We do not need a limit-subquery if DISTINCT is used
1212
            // and the selected fields are either from the root component or from a localKey relation (hasOne)
1213
            // (i.e. DQL: SELECT DISTINCT u.id FROM User u LEFT JOIN u.phonenumbers LIMIT 5).
1214
            if(!$this->_sqlParts['distinct']) {
1215
                $this->_isLimitSubqueryUsed = true;
1216
                $needsSubQuery = true;
1217
            } else {
1218
                foreach( array_keys($this->_pendingFields) as $alias){
1219
                    //no subquery for root fields
1220
                    if($alias == $this->getRootAlias()){
1221
                        continue;
1222
                    }
1223
 
1224
                    //no subquery for ONE relations
1225
                    if(isset($this->_queryComponents[$alias]['relation']) &&
1226
                        $this->_queryComponents[$alias]['relation']->getType() == Doctrine_Relation::ONE){
1227
                        continue;
1228
                    }
1229
 
1230
                    $this->_isLimitSubqueryUsed = true;
1231
                    $needsSubQuery = true;
1232
                }
1233
            }
1234
        }
1235
 
1236
        $sql = array();
1237
 
1238
        if ( ! empty($this->_pendingFields)) {
1239
            foreach ($this->_queryComponents as $alias => $map) {
1240
                $fieldSql = $this->processPendingFields($alias);
1241
                if ( ! empty($fieldSql)) {
1242
                    $sql[] = $fieldSql;
1243
                }
1244
            }
1245
        }
1246
 
1247
        if ( ! empty($sql)) {
1248
            array_unshift($this->_sqlParts['select'], implode(', ', $sql));
1249
        }
1250
 
1251
        $this->_pendingFields = array();
1252
 
1253
        // build the basic query
1254
        $q  = $this->_buildSqlQueryBase();
1255
        $q .= $this->_buildSqlFromPart();
1256
 
1257
        if ( ! empty($this->_sqlParts['set'])) {
1258
            $q .= ' SET ' . implode(', ', $this->_sqlParts['set']);
1259
        }
1260
 
1261
        $string = $this->getInheritanceCondition($this->getRootAlias());
1262
 
1263
        // apply inheritance to WHERE part
1264
        if ( ! empty($string)) {
1265
            if (count($this->_sqlParts['where']) > 0) {
1266
                $this->_sqlParts['where'][] = 'AND';
1267
            }
1268
 
1269
            if (substr($string, 0, 1) === '(' && substr($string, -1) === ')') {
1270
                $this->_sqlParts['where'][] = $string;
1271
            } else {
1272
                $this->_sqlParts['where'][] = '(' . $string . ')';
1273
            }
1274
        }
1275
 
1276
        $modifyLimit = true;
1277
        $limitSubquerySql = '';
1278
 
1279
        if ( ( ! empty($this->_sqlParts['limit']) || ! empty($this->_sqlParts['offset'])) && $needsSubQuery && $limitSubquery) {
1280
            $subquery = $this->getLimitSubquery();
1281
 
1282
            // what about composite keys?
1283
            $idColumnName = $table->getColumnName($table->getIdentifier());
1284
 
1285
            switch (strtolower($this->_conn->getDriverName())) {
1286
                case 'mysql':
1287
                    $this->useQueryCache(false);
1288
 
1289
                    // mysql doesn't support LIMIT in subqueries
1290
                    $list = $this->_conn->execute($subquery, $this->_execParams)->fetchAll(Doctrine_Core::FETCH_COLUMN);
1291
                    $subquery = implode(', ', array_map(array($this->_conn, 'quote'), $list));
1292
 
1293
                    break;
1294
 
1295
                case 'pgsql':
1296
                    $subqueryAlias = $this->_conn->quoteIdentifier('doctrine_subquery_alias');
1297
 
1298
                    // pgsql needs special nested LIMIT subquery
1299
                    $subquery = 'SELECT ' . $subqueryAlias . '.' . $this->_conn->quoteIdentifier($idColumnName)
1300
                            . ' FROM (' . $subquery . ') AS ' . $subqueryAlias;
1301
 
1302
                    break;
1303
            }
1304
 
1305
            $field = $this->getSqlTableAlias($rootAlias) . '.' . $idColumnName;
1306
 
1307
            // FIX #1868: If not ID under MySQL is found to be restricted, restrict pk column for null
1308
            //            (which will lead to a return of 0 items)
1309
            $limitSubquerySql = $this->_conn->quoteIdentifier($field)
1310
                              . (( ! empty($subquery)) ? ' IN (' . $subquery . ')' : ' IS NULL')
1311
                              . ((count($this->_sqlParts['where']) > 0) ? ' AND ' : '');
1312
 
1313
            $modifyLimit = false;
1314
        }
1315
 
1316
        // FIX #DC-26: Include limitSubquerySql as major relevance in conditions
1317
        $emptyWhere = empty($this->_sqlParts['where']);
1318
 
1319
        if ( ! ($emptyWhere && $limitSubquerySql == '')) {
1320
            $where = implode(' ', $this->_sqlParts['where']);
1321
            $where = ($where == '' || (substr($where, 0, 1) === '(' && substr($where, -1) === ')'))
1322
                ? $where : '(' . $where . ')';
1323
 
1324
            $q .= ' WHERE ' . $limitSubquerySql . $where;
1325
            //   .  (($limitSubquerySql == '' && count($this->_sqlParts['where']) == 1) ? substr($where, 1, -1) : $where);
1326
        }
1327
 
1328
        // Fix the orderbys so we only have one orderby per value
1329
        foreach ($this->_sqlParts['orderby'] as $k => $orderBy) {
1330
            $e = explode(', ', $orderBy);
1331
            unset($this->_sqlParts['orderby'][$k]);
1332
            foreach ($e as $v) {
1333
                $this->_sqlParts['orderby'][] = $v;
1334
            }
1335
        }
1336
 
1337
        // Add the default orderBy statements defined in the relationships and table classes
1338
        // Only do this for SELECT queries
1339
        if ($this->_type === self::SELECT) {
1340
            foreach ($this->_queryComponents as $alias => $map) {
1341
                $sqlAlias = $this->getSqlTableAlias($alias);
1342
                if (isset($map['relation'])) {
1343
                    $orderBy = $map['relation']->getOrderByStatement($sqlAlias, true);
1344
                    if ($orderBy == $map['relation']['orderBy']) {
1345
                        if (isset($map['ref'])) {
1346
                            $orderBy = $map['relation']['refTable']->processOrderBy($sqlAlias, $map['relation']['orderBy'], true);
1347
                        } else {
1348
                            $orderBy = null;
1349
                        }
1350
                    }
1351
                } else {
1352
                    $orderBy = $map['table']->getOrderByStatement($sqlAlias, true);
1353
                }
1354
 
1355
                if ($orderBy) {
1356
                    $e = explode(',', $orderBy);
1357
                    $e = array_map('trim', $e);
1358
                    foreach ($e as $v) {
1359
                        if ( ! in_array($v, $this->_sqlParts['orderby'])) {
1360
                            $this->_sqlParts['orderby'][] = $v;
1361
                        }
1362
                    }
1363
                }
1364
            }
1365
        }
1366
 
1367
        $q .= ( ! empty($this->_sqlParts['groupby'])) ? ' GROUP BY ' . implode(', ', $this->_sqlParts['groupby'])  : '';
1368
        $q .= ( ! empty($this->_sqlParts['having'])) ?  ' HAVING '   . implode(' AND ', $this->_sqlParts['having']): '';
1369
        $q .= ( ! empty($this->_sqlParts['orderby'])) ? ' ORDER BY ' . implode(', ', $this->_sqlParts['orderby'])  : '';
1370
 
1371
        if ($modifyLimit) {
1372
            $q = $this->_conn->modifyLimitQuery($q, $this->_sqlParts['limit'], $this->_sqlParts['offset'], false, false, $this);
1373
        }
1374
 
1375
        $q .= $this->_sqlParts['forUpdate'] === true ? ' FOR UPDATE ' : '';
1376
 
1377
        $this->_sql = $q;
1378
 
1379
        $this->clear();
1380
 
1381
        return $q;
1382
    }
1383
 
1384
    /**
1385
     * getLimitSubquery
1386
     * this is method is used by the record limit algorithm
1387
     *
1388
     * when fetching one-to-many, many-to-many associated data with LIMIT clause
1389
     * an additional subquery is needed for limiting the number of returned records instead
1390
     * of limiting the number of sql result set rows
1391
     *
1392
     * @return string       the limit subquery
1393
     * @todo A little refactor to make the method easier to understand & maybe shorter?
1394
     */
1395
    public function getLimitSubquery()
1396
    {
1397
        $map = reset($this->_queryComponents);
1398
        $table = $map['table'];
1399
        $componentAlias = key($this->_queryComponents);
1400
 
1401
        // get short alias
1402
        $alias = $this->getSqlTableAlias($componentAlias);
1403
        // what about composite keys?
1404
        $primaryKey = $alias . '.' . $table->getColumnName($table->getIdentifier());
1405
 
1406
        $driverName = $this->_conn->getAttribute(Doctrine_Core::ATTR_DRIVER_NAME);
1407
 
1408
        // initialize the base of the subquery
1409
        if (($driverName == 'oracle' || $driverName == 'oci') && $this->_isOrderedByJoinedColumn()) {
1410
            $subquery = 'SELECT ';
1411
        } else {
1412
            $subquery = 'SELECT DISTINCT ';
1413
        }
1414
        $subquery .= $this->_conn->quoteIdentifier($primaryKey);
1415
 
1416
        // pgsql & oracle need the order by fields to be preserved in select clause
1417
        if ($driverName == 'pgsql' || $driverName == 'oracle' || $driverName == 'oci' || $driverName == 'mssql' || $driverName == 'odbc') {
1418
            foreach ($this->_sqlParts['orderby'] as $part) {
1419
                // Remove identifier quoting if it exists
1420
                $e = $this->_tokenizer->bracketExplode($part, ' ');
1421
                foreach ($e as $f) {
1422
                    if ($f == 0 || $f % 2 == 0) {
1423
                        $partOriginal = str_replace(',', '', trim($f));
1424
                        $callback = create_function('$e', 'return trim($e, \'[]`"\');');
1425
                        $part = trim(implode('.', array_map($callback, explode('.', $partOriginal))));
1426
 
1427
                        if (strpos($part, '.') === false) {
1428
                            continue;
1429
                        }
1430
 
1431
                        // don't add functions
1432
                        if (strpos($part, '(') !== false) {
1433
                            continue;
1434
                        }
1435
 
1436
                        // don't add primarykey column (its already in the select clause)
1437
                        if ($part !== $primaryKey) {
1438
                            $subquery .= ', ' . $partOriginal;
1439
                        }
1440
                    }
1441
                }
1442
            }
1443
        }
1444
 
1445
        $orderby = $this->_sqlParts['orderby'];
1446
        $having = $this->_sqlParts['having'];
1447
        if ($driverName == 'mysql' || $driverName == 'pgsql') {
1448
            foreach ($this->_expressionMap as $dqlAlias => $expr) {
1449
                if (isset($expr[1])) {
1450
                    $subquery .= ', ' . $expr[0] . ' AS ' . $this->_aggregateAliasMap[$dqlAlias];
1451
                }
1452
            }
1453
        } else {
1454
            foreach ($this->_expressionMap as $dqlAlias => $expr) {
1455
                if (isset($expr[1])) {
1456
                    foreach ($having as $k => $v) {
1457
                        $having[$k] = str_replace($this->_aggregateAliasMap[$dqlAlias], $expr[0], $v);
1458
                    }
1459
                    foreach ($orderby as $k => $v) {
1460
                        $e = explode(' ', $v);
1461
                        if ($e[0] == $this->_aggregateAliasMap[$dqlAlias]) {
1462
                            $orderby[$k] = $expr[0];
1463
                        }
1464
                    }
1465
                }
1466
            }
1467
        }
1468
 
1469
        // Add having fields that got stripped out of select
1470
        preg_match_all('/`[a-z0-9_]+`\.`[a-z0-9_]+`/i', implode(' ', $having), $matches, PREG_PATTERN_ORDER);
1471
        if (count($matches[0]) > 0) {
1472
            $subquery .= ', ' . implode(', ', array_unique($matches[0]));
1473
        }
1474
 
1475
        $subquery .= ' FROM';
1476
 
1477
        foreach ($this->_sqlParts['from'] as $part) {
1478
            // preserve LEFT JOINs only if needed
1479
            if (substr($part, 0, 9) === 'LEFT JOIN') {
1480
                $e = explode(' ', $part);
1481
                // Fix for http://www.doctrine-project.org/jira/browse/DC-706
1482
                // Fix for http://www.doctrine-project.org/jira/browse/DC-594
1483
                if (empty($this->_sqlParts['orderby']) && empty($this->_sqlParts['where']) && empty($this->_sqlParts['having']) && empty($this->_sqlParts['groupby'])) {
1484
                    continue;
1485
                }
1486
            }
1487
 
1488
            $subquery .= ' ' . $part;
1489
        }
1490
 
1491
        // all conditions must be preserved in subquery
1492
        $subquery .= ( ! empty($this->_sqlParts['where']))?   ' WHERE '    . implode(' ', $this->_sqlParts['where'])  : '';
1493
        $subquery .= ( ! empty($this->_sqlParts['groupby']))? ' GROUP BY ' . implode(', ', $this->_sqlParts['groupby'])   : '';
1494
        $subquery .= ( ! empty($having))?  ' HAVING '   . implode(' AND ', $having) : '';
1495
        $subquery .= ( ! empty($orderby))? ' ORDER BY ' . implode(', ', $orderby)  : '';
1496
 
1497
        if (($driverName == 'oracle' || $driverName == 'oci') && $this->_isOrderedByJoinedColumn()) {
1498
            // When using "ORDER BY x.foo" where x.foo is a column of a joined table,
1499
            // we may get duplicate primary keys because all columns in ORDER BY must appear
1500
            // in the SELECT list when using DISTINCT. Hence we need to filter out the
1501
            // primary keys with an additional DISTINCT subquery.
1502
            // #1038
1503
            $quotedIdentifierColumnName = $this->_conn->quoteIdentifier($table->getColumnName($table->getIdentifier()));
1504
            $subquery = 'SELECT doctrine_subquery_alias.' . $quotedIdentifierColumnName
1505
                    . ' FROM (' . $subquery . ') doctrine_subquery_alias'
1506
                    . ' GROUP BY doctrine_subquery_alias.' . $quotedIdentifierColumnName
1507
                    . ' ORDER BY MIN(ROWNUM)';
1508
        }
1509
 
1510
        // add driver specific limit clause
1511
        $subquery = $this->_conn->modifyLimitSubquery($table, $subquery, $this->_sqlParts['limit'], $this->_sqlParts['offset']);
1512
 
1513
        $parts = $this->_tokenizer->quoteExplode($subquery, ' ', "'", "'");
1514
 
1515
        foreach ($parts as $k => $part) {
1516
            if (strpos($part, ' ') !== false) {
1517
                continue;
1518
            }
1519
 
1520
            $part = str_replace(array('"', "'", '`'), "", $part);
1521
 
1522
            // Fix DC-645, Table aliases ending with ')' where not replaced properly
1523
            preg_match('/^(\(?)(.*?)(\)?)$/', $part, $matches);
1524
            if ($this->hasSqlTableAlias($matches[2])) {
1525
                $parts[$k] = $matches[1].$this->_conn->quoteIdentifier($this->generateNewSqlTableAlias($matches[2])).$matches[3];
1526
                continue;
1527
            }
1528
 
1529
            if (strpos($part, '.') === false) {
1530
                continue;
1531
            }
1532
 
1533
            preg_match_all("/[a-zA-Z0-9_]+\.[a-z0-9_]+/i", $part, $m);
1534
 
1535
            foreach ($m[0] as $match) {
1536
                $e = explode('.', $match);
1537
 
1538
                // Rebuild the original part without the newly generate alias and with quoting reapplied
1539
                $e2 = array();
1540
                foreach ($e as $k2 => $v2) {
1541
                  $e2[$k2] = $this->_conn->quoteIdentifier($v2);
1542
                }
1543
                $match = implode('.', $e2);
1544
 
1545
                // Generate new table alias
1546
                $e[0] = $this->generateNewSqlTableAlias($e[0]);
1547
 
1548
                // Requote the part with the newly generated alias
1549
                foreach ($e as $k2 => $v2) {
1550
                  $e[$k2] = $this->_conn->quoteIdentifier($v2);
1551
                }
1552
 
1553
                $replace = implode('.' , $e);
1554
 
1555
                // Replace the original part with the new part with new sql table alias
1556
                $parts[$k] = str_replace($match, $replace, $parts[$k]);
1557
            }
1558
        }
1559
 
1560
        if ($driverName == 'mysql' || $driverName == 'pgsql') {
1561
            foreach ($parts as $k => $part) {
1562
                if (strpos($part, "'") !== false) {
1563
                    continue;
1564
                }
1565
                if (strpos($part, '__') == false) {
1566
                    continue;
1567
                }
1568
 
1569
                preg_match_all("/[a-zA-Z0-9_]+\_\_[a-z0-9_]+/i", $part, $m);
1570
 
1571
                foreach ($m[0] as $match) {
1572
                    $e = explode('__', $match);
1573
                    $e[0] = $this->generateNewSqlTableAlias($e[0]);
1574
 
1575
                    $parts[$k] = str_replace($match, implode('__', $e), $parts[$k]);
1576
                }
1577
            }
1578
        }
1579
 
1580
        $subquery = implode(' ', $parts);
1581
        return $subquery;
1582
    }
1583
 
1584
    /**
1585
     * Checks whether the query has an ORDER BY on a column of a joined table.
1586
     * This information is needed in special scenarios like the limit-offset when its
1587
     * used with an Oracle database.
1588
     *
1589
     * @return boolean  TRUE if the query is ordered by a joined column, FALSE otherwise.
1590
     */
1591
    private function _isOrderedByJoinedColumn() {
1592
        if ( ! $this->_queryComponents) {
1593
            throw new Doctrine_Query_Exception("The query is in an invalid state for this "
1594
                    . "operation. It must have been fully parsed first.");
1595
        }
1596
        $componentAlias = key($this->_queryComponents);
1597
        $mainTableAlias = $this->getSqlTableAlias($componentAlias);
1598
        foreach ($this->_sqlParts['orderby'] as $part) {
1599
            $part = trim($part);
1600
            $e = $this->_tokenizer->bracketExplode($part, ' ');
1601
            $part = trim($e[0]);
1602
            if (strpos($part, '.') === false) {
1603
                continue;
1604
            }
1605
            list($tableAlias, $columnName) = explode('.', $part);
1606
            if ($tableAlias != $mainTableAlias) {
1607
                return true;
1608
            }
1609
        }
1610
        return false;
1611
    }
1612
 
1613
    /**
1614
     * DQL PARSER
1615
     * parses a DQL query
1616
     * first splits the query in parts and then uses individual
1617
     * parsers for each part
1618
     *
1619
     * @param string $query                 DQL query
1620
     * @param boolean $clear                whether or not to clear the aliases
1621
     * @throws Doctrine_Query_Exception     if some generic parsing error occurs
1622
     * @return Doctrine_Query
1623
     */
1624
    public function parseDqlQuery($query, $clear = true)
1625
    {
1626
        if ($clear) {
1627
            $this->clear();
1628
        }
1629
 
1630
        $query = trim($query);
1631
        $query = str_replace("\r", "\n", str_replace("\r\n", "\n", $query));
1632
        $query = str_replace("\n", ' ', $query);
1633
 
1634
        $parts = $this->_tokenizer->tokenizeQuery($query);
1635
 
1636
        foreach ($parts as $partName => $subParts) {
1637
            $subParts = trim($subParts);
1638
            $partName = strtolower($partName);
1639
            switch ($partName) {
1640
                case 'create':
1641
                    $this->_type = self::CREATE;
1642
                break;
1643
                case 'insert':
1644
                    $this->_type = self::INSERT;
1645
                break;
1646
                case 'delete':
1647
                    $this->_type = self::DELETE;
1648
                break;
1649
                case 'select':
1650
                    $this->_type = self::SELECT;
1651
                    $this->_addDqlQueryPart($partName, $subParts);
1652
                break;
1653
                case 'update':
1654
                    $this->_type = self::UPDATE;
1655
                    $partName = 'from';
1656
                case 'from':
1657
                    $this->_addDqlQueryPart($partName, $subParts);
1658
                break;
1659
                case 'set':
1660
                    $this->_addDqlQueryPart($partName, $subParts, true);
1661
                break;
1662
                case 'group':
1663
                case 'order':
1664
                    $partName .= 'by';
1665
                case 'where':
1666
                case 'having':
1667
                case 'limit':
1668
                case 'offset':
1669
                    $this->_addDqlQueryPart($partName, $subParts);
1670
                break;
1671
            }
1672
        }
1673
 
1674
        return $this;
1675
    }
1676
 
1677
    /**
1678
     * @todo Describe & refactor... too long and nested.
1679
     * @param string $path          component alias
1680
     * @param boolean $loadFields
1681
     */
1682
    public function load($path, $loadFields = true)
1683
    {
1684
        if (isset($this->_queryComponents[$path])) {
1685
            return $this->_queryComponents[$path];
1686
        }
1687
 
1688
        $e = $this->_tokenizer->quoteExplode($path, ' INDEXBY ');
1689
 
1690
        $mapWith = null;
1691
        if (count($e) > 1) {
1692
            $mapWith = trim($e[1]);
1693
 
1694
            $path = $e[0];
1695
        }
1696
 
1697
        // parse custom join conditions
1698
        $e = explode(' ON ', str_ireplace(' on ', ' ON ', $path));
1699
 
1700
        $joinCondition = '';
1701
 
1702
        if (count($e) > 1) {
1703
            $joinCondition = substr($path, strlen($e[0]) + 4, strlen($e[1]));
1704
            $path = substr($path, 0, strlen($e[0]));
1705
 
1706
            $overrideJoin = true;
1707
        } else {
1708
            $e = explode(' WITH ', str_ireplace(' with ', ' WITH ', $path));
1709
 
1710
            if (count($e) > 1) {
1711
                $joinCondition = substr($path, strlen($e[0]) + 6, strlen($e[1]));
1712
                $path = substr($path, 0, strlen($e[0]));
1713
            }
1714
 
1715
            $overrideJoin = false;
1716
        }
1717
 
1718
        $tmp            = explode(' ', $path);
1719
        $componentAlias = $originalAlias = (count($tmp) > 1) ? end($tmp) : null;
1720
 
1721
        $e = preg_split("/[.:]/", $tmp[0], -1);
1722
 
1723
        $fullPath = $tmp[0];
1724
        $prevPath = '';
1725
        $fullLength = strlen($fullPath);
1726
 
1727
        if (isset($this->_queryComponents[$e[0]])) {
1728
            $table = $this->_queryComponents[$e[0]]['table'];
1729
            $componentAlias = $e[0];
1730
 
1731
            $prevPath = $parent = array_shift($e);
1732
        }
1733
 
1734
        foreach ($e as $key => $name) {
1735
            // get length of the previous path
1736
            $length = strlen($prevPath);
1737
 
1738
            // build the current component path
1739
            $prevPath = ($prevPath) ? $prevPath . '.' . $name : $name;
1740
 
1741
            $delimeter = substr($fullPath, $length, 1);
1742
 
1743
            // if an alias is not given use the current path as an alias identifier
1744
            if (strlen($prevPath) === $fullLength && isset($originalAlias)) {
1745
                $componentAlias = $originalAlias;
1746
            } else {
1747
                $componentAlias = $prevPath;
1748
            }
1749
 
1750
            // if the current alias already exists, skip it
1751
            if (isset($this->_queryComponents[$componentAlias])) {
1752
                throw new Doctrine_Query_Exception("Duplicate alias '$componentAlias' in query.");
1753
            }
1754
 
1755
            if ( ! isset($table)) {
1756
                // process the root of the path
1757
 
1758
                $table = $this->loadRoot($name, $componentAlias);
1759
            } else {
1760
                $join = ($delimeter == ':') ? 'INNER JOIN ' : 'LEFT JOIN ';
1761
 
1762
                $relation = $table->getRelation($name);
1763
                $localTable = $table;
1764
 
1765
                $table = $relation->getTable();
1766
                $this->_queryComponents[$componentAlias] = array('table' => $table,
1767
                                                                 'parent'   => $parent,
1768
                                                                 'relation' => $relation,
1769
                                                                 'map'      => null);
1770
                // Fix for http://www.doctrine-project.org/jira/browse/DC-701
1771
                if ( ! $relation->isOneToOne() && ! $this->disableLimitSubquery) {
1772
                    $this->_needsSubquery = true;
1773
                }
1774
 
1775
                $localAlias   = $this->getSqlTableAlias($parent, $localTable->getTableName());
1776
                $foreignAlias = $this->getSqlTableAlias($componentAlias, $relation->getTable()->getTableName());
1777
 
1778
                $foreignSql   = $this->_conn->quoteIdentifier($relation->getTable()->getTableName())
1779
                              . ' '
1780
                              . $this->_conn->quoteIdentifier($foreignAlias);
1781
 
1782
                $map = $relation->getTable()->inheritanceMap;
1783
 
1784
                if ( ! $loadFields || ! empty($map) || $joinCondition) {
1785
                    $this->_subqueryAliases[] = $foreignAlias;
1786
                }
1787
 
1788
                if ($relation instanceof Doctrine_Relation_Association) {
1789
                    $asf = $relation->getAssociationTable();
1790
 
1791
                    $assocTableName = $asf->getTableName();
1792
 
1793
                    if ( ! $loadFields || ! empty($map) || $joinCondition) {
1794
                        $this->_subqueryAliases[] = $assocTableName;
1795
                    }
1796
 
1797
                    $assocPath = $prevPath . '.' . $asf->getComponentName() . ' ' . $componentAlias;
1798
 
1799
                    $this->_queryComponents[$assocPath] = array(
1800
                        'parent' => $prevPath,
1801
                        'relation' => $relation,
1802
                        'table' => $asf,
1803
                        'ref' => true);
1804
 
1805
                    $assocAlias = $this->getSqlTableAlias($assocPath, $asf->getTableName());
1806
 
1807
                    $queryPart = $join
1808
                            . $this->_conn->quoteIdentifier($assocTableName)
1809
                            . ' '
1810
                            . $this->_conn->quoteIdentifier($assocAlias);
1811
 
1812
                    $queryPart .= ' ON (' . $this->_conn->quoteIdentifier($localAlias
1813
                                . '.'
1814
                                . $localTable->getColumnName($localTable->getIdentifier())) // what about composite keys?
1815
                                . ' = '
1816
                                . $this->_conn->quoteIdentifier($assocAlias . '.' . $relation->getLocalRefColumnName());
1817
 
1818
                    if ($relation->isEqual()) {
1819
                        // equal nest relation needs additional condition
1820
                        $queryPart .= ' OR '
1821
                                    . $this->_conn->quoteIdentifier($localAlias
1822
                                    . '.'
1823
                                    . $table->getColumnName($table->getIdentifier()))
1824
                                    . ' = '
1825
                                    . $this->_conn->quoteIdentifier($assocAlias . '.' . $relation->getForeignRefColumnName());
1826
                    }
1827
 
1828
                    $queryPart .= ')';
1829
 
1830
                    $this->_sqlParts['from'][] = $queryPart;
1831
 
1832
                    $queryPart = $join . $foreignSql;
1833
 
1834
                    if ( ! $overrideJoin) {
1835
                        $queryPart .= $this->buildAssociativeRelationSql($relation, $assocAlias, $foreignAlias, $localAlias);
1836
                    }
1837
                } else {
1838
                    $queryPart = $this->buildSimpleRelationSql($relation, $foreignAlias, $localAlias, $overrideJoin, $join);
1839
                }
1840
 
1841
                $queryPart .= $this->buildInheritanceJoinSql($table->getComponentName(), $componentAlias);
1842
                $this->_sqlParts['from'][$componentAlias] = $queryPart;
1843
 
1844
                if ( ! empty($joinCondition)) {
1845
                    $this->addPendingJoinCondition($componentAlias, $joinCondition);
1846
                }
1847
            }
1848
 
1849
            if ($loadFields) {
1850
                $restoreState = false;
1851
 
1852
                // load fields if necessary
1853
                if ($loadFields && empty($this->_dqlParts['select'])) {
1854
                    $this->_pendingFields[$componentAlias] = array('*');
1855
                }
1856
            }
1857
 
1858
            $parent = $prevPath;
1859
        }
1860
 
1861
        $table = $this->_queryComponents[$componentAlias]['table'];
1862
 
1863
        return $this->buildIndexBy($componentAlias, $mapWith);
1864
    }
1865
 
1866
    protected function buildSimpleRelationSql(Doctrine_Relation $relation, $foreignAlias, $localAlias, $overrideJoin, $join)
1867
    {
1868
        $queryPart = $join . $this->_conn->quoteIdentifier($relation->getTable()->getTableName())
1869
                           . ' '
1870
                           . $this->_conn->quoteIdentifier($foreignAlias);
1871
 
1872
        if ( ! $overrideJoin) {
1873
            $queryPart .= ' ON '
1874
                       . $this->_conn->quoteIdentifier($localAlias . '.' . $relation->getLocalColumnName())
1875
                       . ' = '
1876
                       . $this->_conn->quoteIdentifier($foreignAlias . '.' . $relation->getForeignColumnName());
1877
        }
1878
 
1879
        return $queryPart;
1880
    }
1881
 
1882
    protected function buildIndexBy($componentAlias, $mapWith = null)
1883
    {
1884
        $table = $this->_queryComponents[$componentAlias]['table'];
1885
 
1886
        $indexBy = null;
1887
        $column = false;
1888
 
1889
        if (isset($mapWith)) {
1890
            $terms = explode('.', $mapWith);
1891
 
1892
            if (count($terms) == 1) {
1893
                $indexBy = $terms[0];
1894
            } else if (count($terms) == 2) {
1895
                $column = true;
1896
                $indexBy = $terms[1];
1897
            }
1898
        } else if ($table->getBoundQueryPart('indexBy') !== null) {
1899
            $indexBy = $table->getBoundQueryPart('indexBy');
1900
        }
1901
 
1902
        if ($indexBy !== null) {
1903
            if ( $column && ! $table->hasColumn($table->getColumnName($indexBy))) {
1904
                throw new Doctrine_Query_Exception("Couldn't use key mapping. Column " . $indexBy . " does not exist.");
1905
            }
1906
 
1907
            $this->_queryComponents[$componentAlias]['map'] = $indexBy;
1908
        }
1909
 
1910
        return $this->_queryComponents[$componentAlias];
1911
    }
1912
 
1913
 
1914
    protected function buildAssociativeRelationSql(Doctrine_Relation $relation, $assocAlias, $foreignAlias, $localAlias)
1915
    {
1916
        $table = $relation->getTable();
1917
 
1918
        $queryPart = ' ON ';
1919
 
1920
        if ($relation->isEqual()) {
1921
            $queryPart .= '(';
1922
        }
1923
 
1924
        $localIdentifier = $table->getColumnName($table->getIdentifier());
1925
 
1926
        $queryPart .= $this->_conn->quoteIdentifier($foreignAlias . '.' . $localIdentifier)
1927
                    . ' = '
1928
                    . $this->_conn->quoteIdentifier($assocAlias . '.' . $relation->getForeignRefColumnName());
1929
 
1930
        if ($relation->isEqual()) {
1931
            $queryPart .= ' OR '
1932
                        . $this->_conn->quoteIdentifier($foreignAlias . '.' . $localIdentifier)
1933
                        . ' = '
1934
                        . $this->_conn->quoteIdentifier($assocAlias . '.' . $relation->getLocalRefColumnName())
1935
                        . ') AND '
1936
                        . $this->_conn->quoteIdentifier($foreignAlias . '.' . $localIdentifier)
1937
                        . ' != '
1938
                        . $this->_conn->quoteIdentifier($localAlias . '.' . $localIdentifier);
1939
        }
1940
 
1941
        return $queryPart;
1942
    }
1943
 
1944
    /**
1945
     * loadRoot
1946
     *
1947
     * @param string $name
1948
     * @param string $componentAlias
1949
     * @return Doctrine_Table
1950
     * @todo DESCRIBE ME!
1951
     * @todo this method is called only in Doctrine_Query class. Shouldn't be private or protected?
1952
     */
1953
    public function loadRoot($name, $componentAlias)
1954
    {
1955
        // get the connection for the component
1956
        $manager = Doctrine_Manager::getInstance();
1957
        if ( ! $this->_passedConn && $manager->hasConnectionForComponent($name)) {
1958
            $this->_conn = $manager->getConnectionForComponent($name);
1959
        }
1960
 
1961
        $table = $this->_conn->getTable($name);
1962
        $tableName = $table->getTableName();
1963
 
1964
        // get the short alias for this table
1965
        $tableAlias = $this->getSqlTableAlias($componentAlias, $tableName);
1966
        // quote table name
1967
        $queryPart = $this->_conn->quoteIdentifier($tableName);
1968
 
1969
        if ($this->_type === self::SELECT) {
1970
            $queryPart .= ' ' . $this->_conn->quoteIdentifier($tableAlias);
1971
        }
1972
 
1973
        $this->_tableAliasMap[$tableAlias] = $componentAlias;
1974
 
1975
        $queryPart .= $this->buildInheritanceJoinSql($name, $componentAlias);
1976
 
1977
        $this->_sqlParts['from'][] = $queryPart;
1978
 
1979
        $this->_queryComponents[$componentAlias] = array('table' => $table, 'map' => null);
1980
 
1981
        return $table;
1982
    }
1983
 
1984
    /**
1985
     * @todo DESCRIBE ME!
1986
     * @param string $name              component class name
1987
     * @param string $componentAlias    alias of the component in the dql
1988
     * @return string                   query part
1989
     */
1990
    public function buildInheritanceJoinSql($name, $componentAlias)
1991
    {
1992
        // get the connection for the component
1993
        $manager = Doctrine_Manager::getInstance();
1994
        if ( ! $this->_passedConn && $manager->hasConnectionForComponent($name)) {
1995
            $this->_conn = $manager->getConnectionForComponent($name);
1996
        }
1997
 
1998
        $table = $this->_conn->getTable($name);
1999
        $tableName = $table->getTableName();
2000
 
2001
        // get the short alias for this table
2002
        $tableAlias = $this->getSqlTableAlias($componentAlias, $tableName);
2003
 
2004
        $queryPart = '';
2005
 
2006
        foreach ($table->getOption('joinedParents') as $parent) {
2007
            $parentTable = $this->_conn->getTable($parent);
2008
 
2009
            $parentAlias = $componentAlias . '.' . $parent;
2010
 
2011
            // get the short alias for the parent table
2012
            $parentTableAlias = $this->getSqlTableAlias($parentAlias, $parentTable->getTableName());
2013
 
2014
            $queryPart .= ' LEFT JOIN ' . $this->_conn->quoteIdentifier($parentTable->getTableName())
2015
                        . ' ' . $this->_conn->quoteIdentifier($parentTableAlias) . ' ON ';
2016
 
2017
            //Doctrine_Core::dump($table->getIdentifier());
2018
            foreach ((array) $table->getIdentifier() as $identifier) {
2019
                $column = $table->getColumnName($identifier);
2020
 
2021
                $queryPart .= $this->_conn->quoteIdentifier($tableAlias)
2022
                            . '.' . $this->_conn->quoteIdentifier($column)
2023
                            . ' = ' . $this->_conn->quoteIdentifier($parentTableAlias)
2024
                            . '.' . $this->_conn->quoteIdentifier($column);
2025
            }
2026
        }
2027
 
2028
        return $queryPart;
2029
    }
2030
 
2031
    /**
2032
     * Get count sql query for this Doctrine_Query instance.
2033
     *
2034
     * This method is used in Doctrine_Query::count() for returning an integer
2035
     * for the number of records which will be returned when executed.
2036
     *
2037
     * @return string $q
2038
     */
2039
    public function getCountSqlQuery()
2040
    {
2041
        // triggers dql parsing/processing
2042
        $this->getSqlQuery(array(), false); // this is ugly
2043
 
2044
        // initialize temporary variables
2045
        $where   = $this->_sqlParts['where'];
2046
        $having  = $this->_sqlParts['having'];
2047
        $groupby = $this->_sqlParts['groupby'];
2048
 
2049
        $rootAlias = $this->getRootAlias();
2050
        $tableAlias = $this->getSqlTableAlias($rootAlias);
2051
 
2052
        // Build the query base
2053
        $q = 'SELECT COUNT(*) AS ' . $this->_conn->quoteIdentifier('num_results') . ' FROM ';
2054
 
2055
        // Build the from clause
2056
        $from = $this->_buildSqlFromPart(true);
2057
 
2058
        // Build the where clause
2059
        $where = ( ! empty($where)) ? ' WHERE ' . implode(' ', $where) : '';
2060
 
2061
        // Build the group by clause
2062
        $groupby = ( ! empty($groupby)) ? ' GROUP BY ' . implode(', ', $groupby) : '';
2063
 
2064
        // Build the having clause
2065
        $having = ( ! empty($having)) ? ' HAVING ' . implode(' AND ', $having) : '';
2066
 
2067
        // Building the from clause and finishing query
2068
        if (count($this->_queryComponents) == 1 && empty($having)) {
2069
            $q .= $from . $where . $groupby . $having;
2070
        } else {
2071
            // Subselect fields will contain only the pk of root entity
2072
            $ta = $this->_conn->quoteIdentifier($tableAlias);
2073
 
2074
            $map = $this->getRootDeclaration();
2075
            $idColumnNames = $map['table']->getIdentifierColumnNames();
2076
 
2077
            $pkFields = $ta . '.' . implode(', ' . $ta . '.', $this->_conn->quoteMultipleIdentifier($idColumnNames));
2078
 
2079
            // We need to do some magic in select fields if the query contain anything in having clause
2080
            $selectFields = $pkFields;
2081
 
2082
            if ( ! empty($having)) {
2083
                // For each field defined in select clause
2084
                foreach ($this->_sqlParts['select'] as $field) {
2085
                    // We only include aggregate expressions to count query
2086
                    // This is needed because HAVING clause will use field aliases
2087
                    if (strpos($field, '(') !== false) {
2088
                        $selectFields .= ', ' . $field;
2089
                    }
2090
                }
2091
                // Add having fields that got stripped out of select
2092
                preg_match_all('/`[a-z0-9_]+`\.`[a-z0-9_]+`/i', $having, $matches, PREG_PATTERN_ORDER);
2093
                if (count($matches[0]) > 0) {
2094
                    $selectFields .= ', ' . implode(', ', array_unique($matches[0]));
2095
                }
2096
            }
2097
 
2098
            // If we do not have a custom group by, apply the default one
2099
            if (empty($groupby)) {
2100
                $groupby = ' GROUP BY ' . $pkFields;
2101
            }
2102
 
2103
            $q .= '(SELECT ' . $selectFields . ' FROM ' . $from . $where . $groupby . $having . ') '
2104
                . $this->_conn->quoteIdentifier('dctrn_count_query');
2105
        }
2106
 
2107
        return $q;
2108
    }
2109
 
2110
    /**
2111
     * Fetches the count of the query.
2112
     *
2113
     * This method executes the main query without all the
2114
     * selected fields, ORDER BY part, LIMIT part and OFFSET part.
2115
     *
2116
     * Example:
2117
     * Main query:
2118
     *      SELECT u.*, p.phonenumber FROM User u
2119
     *          LEFT JOIN u.Phonenumber p
2120
     *          WHERE p.phonenumber = '123 123' LIMIT 10
2121
     *
2122
     * The modified DQL query:
2123
     *      SELECT COUNT(DISTINCT u.id) FROM User u
2124
     *          LEFT JOIN u.Phonenumber p
2125
     *          WHERE p.phonenumber = '123 123'
2126
     *
2127
     * @param array $params        an array of prepared statement parameters
2128
     * @return integer             the count of this query
2129
     */
2130
    public function count($params = array())
2131
    {
2132
        $q = $this->getCountSqlQuery();
2133
        $params = $this->getCountQueryParams($params);
2134
        $params = $this->_conn->convertBooleans($params);
2135
 
2136
        if ($this->_resultCache) {
2137
            $conn = $this->getConnection();
2138
            $cacheDriver = $this->getResultCacheDriver();
2139
            $hash = $this->getResultCacheHash($params).'_count';
2140
            $cached = ($this->_expireResultCache) ? false : $cacheDriver->fetch($hash);
2141
 
2142
            if ($cached === false) {
2143
                // cache miss
2144
                $results = $this->getConnection()->fetchAll($q, $params);
2145
                $cacheDriver->save($hash, serialize($results), $this->getResultCacheLifeSpan());
2146
            } else {
2147
                $results = unserialize($cached);
2148
            }
2149
        } else {
2150
            $results = $this->getConnection()->fetchAll($q, $params);
2151
        }
2152
 
2153
        if (count($results) > 1) {
2154
            $count = count($results);
2155
        } else {
2156
            if (isset($results[0])) {
2157
                $results[0] = array_change_key_case($results[0], CASE_LOWER);
2158
                $count = $results[0]['num_results'];
2159
            } else {
2160
                $count = 0;
2161
            }
2162
        }
2163
 
2164
        return (int) $count;
2165
    }
2166
 
2167
    /**
2168
     * Queries the database with DQL (Doctrine Query Language).
2169
     *
2170
     * This methods parses a Dql query and builds the query parts.
2171
     *
2172
     * @param string $query      Dql query
2173
     * @param array $params      prepared statement parameters
2174
     * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD
2175
     * @see Doctrine_Core::FETCH_* constants
2176
     * @return mixed
2177
     */
2178
    public function query($query, $params = array(), $hydrationMode = null)
2179
    {
2180
        $this->parseDqlQuery($query);
2181
        return $this->execute($params, $hydrationMode);
2182
    }
2183
 
2184
    /**
2185
     * Copies a Doctrine_Query object.
2186
     *
2187
     * @return Doctrine_Query  Copy of the Doctrine_Query instance.
2188
     */
2189
    public function copy(Doctrine_Query $query = null)
2190
    {
2191
        if ( ! $query) {
2192
            $query = $this;
2193
        }
2194
 
2195
        $new = clone $query;
2196
 
2197
        return $new;
2198
    }
2199
 
2200
    /**
2201
     * Magic method called after cloning process.
2202
     *
2203
     * @return void
2204
     */
2205
    public function __clone()
2206
    {
2207
        $this->_parsers = array();
2208
        $this->_hydrator = clone $this->_hydrator;
2209
 
2210
        // Subqueries share some information from the parent so it can intermingle
2211
        // with the dql of the main query. So when a subquery is cloned we need to
2212
        // kill those references or it causes problems
2213
        if ($this->isSubquery()) {
2214
            $this->_killReference('_params');
2215
            $this->_killReference('_tableAliasMap');
2216
            $this->_killReference('_queryComponents');
2217
        }
2218
    }
2219
 
2220
    /**
2221
     * Kill the reference for the passed class property.
2222
     * This method simply copies the value to a temporary variable and then unsets
2223
     * the reference and re-assigns the old value but not by reference
2224
     *
2225
     * @param string $key
2226
     */
2227
    protected function _killReference($key)
2228
    {
2229
        $tmp = $this->$key;
2230
        unset($this->$key);
2231
        $this->$key = $tmp;
2232
    }
2233
 
2234
    /**
2235
     * Frees the resources used by the query object. It especially breaks a
2236
     * cyclic reference between the query object and it's parsers. This enables
2237
     * PHP's current GC to reclaim the memory.
2238
     * This method can therefore be used to reduce memory usage when creating
2239
     * a lot of query objects during a request.
2240
     *
2241
     * @return Doctrine_Query   this object
2242
     */
2243
    public function free()
2244
    {
2245
        $this->reset();
2246
        $this->_parsers = array();
2247
        $this->_dqlParts = array();
2248
    }
2249
}