Completed
Push — master ( 6d673d...7f4ef4 )
by Sergei
40:47 queued 40:43
created

QueryBuilder::appendToPredicate()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 5.0488

Importance

Changes 0
Metric Value
eloc 7
c 0
b 0
f 0
dl 0
loc 13
ccs 7
cts 8
cp 0.875
rs 9.6111
cc 5
nc 4
nop 3
crap 5.0488
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\DBAL\Query;
6
7
use Doctrine\DBAL\Connection;
8
use Doctrine\DBAL\Driver\Statement;
9
use Doctrine\DBAL\ParameterType;
10
use Doctrine\DBAL\Query\Exception\NonUniqueAlias;
11
use Doctrine\DBAL\Query\Exception\UnknownAlias;
12
use Doctrine\DBAL\Query\Expression\CompositeExpression;
13
use Doctrine\DBAL\Query\Expression\ExpressionBuilder;
14
use function array_key_exists;
15
use function array_keys;
16
use function array_merge;
17
use function array_unshift;
18
use function count;
19
use function implode;
20
use function is_object;
21
use function substr;
22
23
/**
24
 * QueryBuilder class is responsible to dynamically create SQL queries.
25
 *
26
 * Important: Verify that every feature you use will work with your database vendor.
27
 * SQL Query Builder does not attempt to validate the generated SQL at all.
28
 *
29
 * The query builder does no validation whatsoever if certain features even work with the
30
 * underlying database vendor. Limit queries and joins are NOT applied to UPDATE and DELETE statements
31
 * even if some vendors such as MySQL support it.
32
 */
33
class QueryBuilder
34
{
35
    /*
36
     * The query types.
37
     */
38
    public const SELECT = 0;
39
    public const DELETE = 1;
40
    public const UPDATE = 2;
41
    public const INSERT = 3;
42
43
    /*
44
     * The builder states.
45
     */
46
    public const STATE_DIRTY = 0;
47
    public const STATE_CLEAN = 1;
48
49
    /**
50
     * The DBAL Connection.
51
     *
52
     * @var Connection
53
     */
54
    private $connection;
55
56
    /**
57
     * The complete SQL string for this query.
58
     *
59
     * @var string
60
     */
61
    private $sql;
62
63
    /**
64
     * The query parameters.
65
     *
66
     * @var array<int, mixed>|array<string, mixed>
67
     */
68
    private $params = [];
69
70
    /**
71
     * The parameter type map of this query.
72
     *
73
     * @var array<int, mixed>|array<string, mixed>
74
     */
75
    private $paramTypes = [];
76
77
    /**
78
     * The type of query this is. Can be select, update or delete.
79
     *
80
     * @var int
81
     */
82
    private $type = self::SELECT;
83
84
    /**
85
     * The state of the query object. Can be dirty or clean.
86
     *
87
     * @var int
88
     */
89
    private $state = self::STATE_CLEAN;
90
91
    /**
92
     * The index of the first result to retrieve.
93
     *
94
     * @var int
95
     */
96
    private $firstResult = 0;
97
98
    /**
99
     * The maximum number of results to retrieve or NULL to retrieve all results.
100
     *
101
     * @var int|null
102
     */
103
    private $maxResults;
104
105
    /**
106
     * The counter of bound parameters used with {@see bindValue).
107
     *
108
     * @var int
109
     */
110
    private $boundCounter = 0;
111
112
    /**
113
     * The SELECT parts of the query.
114
     *
115
     * @var string[]
116
     */
117
    private $select = [];
118
119
    /**
120
     * Whether this is a SELECT DISTINCT query.
121
     *
122
     * @var bool
123
     */
124
    private $distinct = false;
125
126
    /**
127
     * The FROM parts of a SELECT query.
128
     *
129
     * @var From[]
130
     */
131
    private $from = [];
132
133
    /**
134
     * The table name for an INSERT, UPDATE or DELETE query.
135
     *
136
     * @var string|null
137
     */
138
    private $table;
139
140
    /**
141
     * The list of joins, indexed by from alias.
142
     *
143
     * @var array<string, Join[]>
144
     */
145
    private $join = [];
146
147
    /**
148
     * The SET parts of an UPDATE query.
149
     *
150
     * @var string[]
151
     */
152
    private $set = [];
153
154
    /**
155
     * The WHERE part of a SELECT, UPDATE or DELETE query.
156
     *
157
     * @var string|CompositeExpression|null
158
     */
159
    private $where;
160
161
    /**
162
     * The GROUP BY part of a SELECT query.
163
     *
164
     * @var string[]
165
     */
166
    private $groupBy = [];
167
168
    /**
169
     * The HAVING part of a SELECT query.
170
     *
171
     * @var string|CompositeExpression|null
172
     */
173
    private $having;
174
175
    /**
176
     * The ORDER BY parts of a SELECT query.
177
     *
178
     * @var string[]
179
     */
180
    private $orderBy = [];
181
182
    /**
183
     * The values of an INSERT query.
184
     *
185
     * @var array<string, mixed>
186
     */
187
    private $values = [];
188
189
    /**
190
     * Initializes a new <tt>QueryBuilder</tt>.
191
     *
192
     * @param Connection $connection The DBAL Connection.
193
     */
194 1593
    public function __construct(Connection $connection)
195
    {
196 1593
        $this->connection = $connection;
197 1593
    }
198
199
    /**
200
     * Gets an ExpressionBuilder used for object-oriented construction of query expressions.
201
     * This producer method is intended for convenient inline usage. Example:
202
     *
203
     * <code>
204
     *     $qb = $conn->createQueryBuilder()
205
     *         ->select('u')
206
     *         ->from('users', 'u')
207
     *         ->where($qb->expr()->eq('u.id', 1));
208
     * </code>
209
     *
210
     * For more complex expression construction, consider storing the expression
211
     * builder object in a local variable.
212
     */
213 216
    public function expr() : ExpressionBuilder
214
    {
215 216
        return $this->connection->getExpressionBuilder();
216
    }
217
218
    /**
219
     * Gets the type of the currently built query.
220
     */
221 189
    public function getType() : int
222
    {
223 189
        return $this->type;
224
    }
225
226
    /**
227
     * Gets the associated DBAL Connection for this query builder.
228
     */
229 27
    public function getConnection() : Connection
230
    {
231 27
        return $this->connection;
232
    }
233
234
    /**
235
     * Gets the state of this query builder instance.
236
     *
237
     * @return int Either QueryBuilder::STATE_DIRTY or QueryBuilder::STATE_CLEAN.
238
     */
239 108
    public function getState() : int
240
    {
241 108
        return $this->state;
242
    }
243
244
    /**
245
     * Executes this query using the bound parameters and their types.
246
     *
247
     * Uses {@see Connection::executeQuery} for select statements and {@see Connection::executeUpdate}
248
     * for insert, update and delete statements.
249
     *
250
     * @return Statement|int
251
     */
252
    public function execute()
253
    {
254
        if ($this->type === self::SELECT) {
255
            return $this->connection->executeQuery($this->getSQL(), $this->params, $this->paramTypes);
256
        }
257
258
        return $this->connection->executeUpdate($this->getSQL(), $this->params, $this->paramTypes);
259
    }
260
261
    /**
262
     * Gets the complete SQL string formed by the current specifications of this QueryBuilder.
263
     *
264
     * <code>
265
     *     $qb = $em->createQueryBuilder()
266
     *         ->select('u')
267
     *         ->from('User', 'u')
268
     *     echo $qb->getSQL(); // SELECT u FROM User u
269
     * </code>
270
     *
271
     * @return string The SQL query string.
272
     *
273
     * @throws QueryException If the object doesn't represent a valid query in its current state.
274
     */
275 1431
    public function getSQL() : string
276
    {
277 1431
        if ($this->sql !== null && $this->state === self::STATE_CLEAN) {
278 27
            return $this->sql;
279
        }
280
281 1431
        switch ($this->type) {
282 1431
            case self::INSERT:
283 108
                $sql = $this->getSQLForInsert();
284 108
                break;
285 1323
            case self::DELETE:
286 54
                $sql = $this->getSQLForDelete();
287 54
                break;
288
289 1269
            case self::UPDATE:
290 54
                $sql = $this->getSQLForUpdate();
291 54
                break;
292
293 1215
            case self::SELECT:
294
            default:
295 1215
                $sql = $this->getSQLForSelect();
296 1134
                break;
297
        }
298
299 1350
        $this->state = self::STATE_CLEAN;
300 1350
        $this->sql   = $sql;
301
302 1350
        return $sql;
303
    }
304
305
    /**
306
     * Sets a query parameter for the query being constructed.
307
     *
308
     * <code>
309
     *     $qb = $conn->createQueryBuilder()
310
     *         ->select('u')
311
     *         ->from('users', 'u')
312
     *         ->where('u.id = :user_id')
313
     *         ->setParameter(':user_id', 1);
314
     * </code>
315
     *
316
     * @param string|int      $key   The parameter position or name.
317
     * @param mixed           $value The parameter value.
318
     * @param string|int|null $type  One of the {@link \Doctrine\DBAL\ParameterType} constants.
319
     *
320
     * @return $this This QueryBuilder instance.
321
     */
322 162
    public function setParameter($key, $value, $type = null) : self
323
    {
324 162
        if ($type !== null) {
325 135
            $this->paramTypes[$key] = $type;
326
        }
327
328 162
        $this->params[$key] = $value;
329
330 162
        return $this;
331
    }
332
333
    /**
334
     * Sets a collection of query parameters for the query being constructed.
335
     *
336
     * <code>
337
     *     $qb = $conn->createQueryBuilder()
338
     *         ->select('u')
339
     *         ->from('users', 'u')
340
     *         ->where('u.id = :user_id1 OR u.id = :user_id2')
341
     *         ->setParameters(array(
342
     *             ':user_id1' => 1,
343
     *             ':user_id2' => 2
344
     *         ));
345
     * </code>
346
     *
347
     * @param array<int, mixed>|array<string, mixed> $params The query parameters to set.
348
     * @param array<int, mixed>|array<string, mixed> $types  The query parameters types to set.
349
     *
350
     * @return $this This QueryBuilder instance.
351
     */
352
    public function setParameters(array $params, array $types = []) : self
353
    {
354
        $this->paramTypes = $types;
355
        $this->params     = $params;
356
357
        return $this;
358
    }
359
360
    /**
361
     * Gets all defined query parameters for the query being constructed indexed by parameter index or name.
362
     *
363
     * @return array<string|int, mixed> The currently defined query parameters indexed by parameter index or name.
364
     */
365 27
    public function getParameters() : array
366
    {
367 27
        return $this->params;
368
    }
369
370
    /**
371
     * Gets a (previously set) query parameter of the query being constructed.
372
     *
373
     * @param string|int $key The key (index or name) of the bound parameter.
374
     *
375
     * @return mixed The value of the bound parameter.
376
     */
377 81
    public function getParameter($key)
378
    {
379 81
        return $this->params[$key] ?? null;
380
    }
381
382
    /**
383
     * Gets all defined query parameter types for the query being constructed indexed by parameter index or name.
384
     *
385
     * @return array<string|int, mixed> The currently defined query parameter types indexed by parameter index or name.
386
     */
387 27
    public function getParameterTypes() : array
388
    {
389 27
        return $this->paramTypes;
390
    }
391
392
    /**
393
     * Gets a (previously set) query parameter type of the query being constructed.
394
     *
395
     * @param string|int $key The key (index or name) of the bound parameter type.
396
     *
397
     * @return mixed The value of the bound parameter type.
398
     */
399 108
    public function getParameterType($key)
400
    {
401 108
        return $this->paramTypes[$key] ?? null;
402
    }
403
404
    /**
405
     * Sets the position of the first result to retrieve (the "offset").
406
     *
407
     * @param int $firstResult The first result to return.
408
     *
409
     * @return $this This QueryBuilder instance.
410
     */
411 27
    public function setFirstResult(int $firstResult) : self
412
    {
413 27
        $this->state       = self::STATE_DIRTY;
414 27
        $this->firstResult = $firstResult;
415
416 27
        return $this;
417
    }
418
419
    /**
420
     * Gets the position of the first result the query object was set to retrieve (the "offset").
421
     *
422
     * @return int The position of the first result.
423
     */
424 27
    public function getFirstResult() : int
425
    {
426 27
        return $this->firstResult;
427
    }
428
429
    /**
430
     * Sets the maximum number of results to retrieve (the "limit").
431
     *
432
     * @param int|null $maxResults The maximum number of results to retrieve or NULL to retrieve all results.
433
     *
434
     * @return $this This QueryBuilder instance.
435
     */
436 54
    public function setMaxResults(?int $maxResults) : self
437
    {
438 54
        $this->state      = self::STATE_DIRTY;
439 54
        $this->maxResults = $maxResults;
440
441 54
        return $this;
442
    }
443
444
    /**
445
     * Gets the maximum number of results the query object was set to retrieve (the "limit").
446
     * Returns NULL if all results will be returned.
447
     *
448
     * @return int|null The maximum number of results.
449
     */
450 54
    public function getMaxResults() : ?int
451
    {
452 54
        return $this->maxResults;
453
    }
454
455
    /**
456
     * Specifies an item that is to be returned in the query result.
457
     * Replaces any previously specified selections, if any.
458
     *
459
     * <code>
460
     *     $qb = $conn->createQueryBuilder()
461
     *         ->select('u.id', 'p.id')
462
     *         ->from('users', 'u')
463
     *         ->leftJoin('u', 'phonenumbers', 'p', 'u.id = p.user_id');
464
     * </code>
465
     *
466
     * @param string ...$expressions The selection expressions.
467
     *
468
     * @return $this This QueryBuilder instance.
469
     */
470 1269
    public function select(string ...$expressions) : self
471
    {
472 1269
        $this->type = self::SELECT;
473
474 1269
        if (count($expressions) < 1) {
475 27
            return $this;
476
        }
477
478 1242
        $this->select = $expressions;
479
480 1242
        $this->state = self::STATE_DIRTY;
481
482 1242
        return $this;
483
    }
484
485
    /**
486
     * Adds DISTINCT to the query.
487
     *
488
     * <code>
489
     *     $qb = $conn->createQueryBuilder()
490
     *         ->select('u.id')
491
     *         ->distinct()
492
     *         ->from('users', 'u')
493
     * </code>
494
     *
495
     * @return $this This QueryBuilder instance.
496
     */
497 27
    public function distinct() : self
498
    {
499 27
        $this->distinct = true;
500
501 27
        $this->state = self::STATE_DIRTY;
502
503 27
        return $this;
504
    }
505
506
    /**
507
     * Adds an item that is to be returned in the query result.
508
     *
509
     * <code>
510
     *     $qb = $conn->createQueryBuilder()
511
     *         ->select('u.id')
512
     *         ->addSelect('p.id')
513
     *         ->from('users', 'u')
514
     *         ->leftJoin('u', 'phonenumbers', 'u.id = p.user_id');
515
     * </code>
516
     *
517
     * @param string $expression     The selection expression.
518
     * @param string ...$expressions Additional selection expressions.
519
     *
520
     * @return $this This QueryBuilder instance.
521
     */
522 54
    public function addSelect(string $expression, string ...$expressions) : self
523
    {
524 54
        $this->type = self::SELECT;
525
526 54
        $this->select = array_merge($this->select, [$expression], $expressions);
527
528 54
        $this->state = self::STATE_DIRTY;
529
530 54
        return $this;
531
    }
532
533
    /**
534
     * Turns the query being built into a bulk delete query that ranges over
535
     * a certain table.
536
     *
537
     * <code>
538
     *     $qb = $conn->createQueryBuilder()
539
     *         ->delete('users', 'u')
540
     *         ->where('u.id = :user_id')
541
     *         ->setParameter(':user_id', 1);
542
     * </code>
543
     *
544
     * @param string $table The table whose rows are subject to the deletion.
545
     *
546
     * @return $this This QueryBuilder instance.
547
     */
548 54
    public function delete(string $table) : self
549
    {
550 54
        $this->type = self::DELETE;
551
552 54
        $this->table = $table;
553
554 54
        $this->state = self::STATE_DIRTY;
555
556 54
        return $this;
557
    }
558
559
    /**
560
     * Turns the query being built into a bulk update query that ranges over
561
     * a certain table
562
     *
563
     * <code>
564
     *     $qb = $conn->createQueryBuilder()
565
     *         ->update('counters', 'c')
566
     *         ->set('c.value', 'c.value + 1')
567
     *         ->where('c.id = ?');
568
     * </code>
569
     *
570
     * @param string $table The table whose rows are subject to the update.
571
     *
572
     * @return $this This QueryBuilder instance.
573
     */
574 54
    public function update(string $table) : self
575
    {
576 54
        $this->type = self::UPDATE;
577
578 54
        $this->table = $table;
579
580 54
        $this->state = self::STATE_DIRTY;
581
582 54
        return $this;
583
    }
584
585
    /**
586
     * Turns the query being built into an insert query that inserts into
587
     * a certain table
588
     *
589
     * <code>
590
     *     $qb = $conn->createQueryBuilder()
591
     *         ->insert('users')
592
     *         ->values(
593
     *             array(
594
     *                 'name' => '?',
595
     *                 'password' => '?'
596
     *             )
597
     *         );
598
     * </code>
599
     *
600
     * @param string $table The table into which the rows should be inserted.
601
     *
602
     * @return $this This QueryBuilder instance.
603
     */
604 108
    public function insert(string $table) : self
605
    {
606 108
        $this->type = self::INSERT;
607
608 108
        $this->table = $table;
609
610 108
        $this->state = self::STATE_DIRTY;
611
612 108
        return $this;
613
    }
614
615
    /**
616
     * Creates and adds a query root corresponding to the table identified by the
617
     * given alias, forming a cartesian product with any existing query roots.
618
     *
619
     * <code>
620
     *     $qb = $conn->createQueryBuilder()
621
     *         ->select('u.id')
622
     *         ->from('users', 'u')
623
     * </code>
624
     *
625
     * @param string      $table The table.
626
     * @param string|null $alias The alias of the table.
627
     *
628
     * @return $this This QueryBuilder instance.
629
     */
630 1215
    public function from(string $table, ?string $alias = null) : self
631
    {
632 1215
        $this->from[] = new From($table, $alias);
633
634 1215
        $this->state = self::STATE_DIRTY;
635
636 1215
        return $this;
637
    }
638
639
    /**
640
     * Creates and adds a join to the query.
641
     *
642
     * <code>
643
     *     $qb = $conn->createQueryBuilder()
644
     *         ->select('u.name')
645
     *         ->from('users', 'u')
646
     *         ->join('u', 'phonenumbers', 'p', 'p.is_primary = 1');
647
     * </code>
648
     *
649
     * @param string $fromAlias The alias that points to a from clause.
650
     * @param string $join      The table name to join.
651
     * @param string $alias     The alias of the join table.
652
     * @param string $condition The condition for the join.
653
     *
654
     * @return $this This QueryBuilder instance.
655
     */
656 108
    public function join(string $fromAlias, string $join, string $alias, ?string $condition = null) : self
657
    {
658 108
        return $this->innerJoin($fromAlias, $join, $alias, $condition);
659
    }
660
661
    /**
662
     * Creates and adds a join to the query.
663
     *
664
     * <code>
665
     *     $qb = $conn->createQueryBuilder()
666
     *         ->select('u.name')
667
     *         ->from('users', 'u')
668
     *         ->innerJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
669
     * </code>
670
     *
671
     * @param string $fromAlias The alias that points to a from clause.
672
     * @param string $join      The table name to join.
673
     * @param string $alias     The alias of the join table.
674
     * @param string $condition The condition for the join.
675
     *
676
     * @return $this This QueryBuilder instance.
677
     */
678 270
    public function innerJoin(string $fromAlias, string $join, string $alias, ?string $condition = null) : self
679
    {
680 270
        $this->join[$fromAlias][] = Join::inner($join, $alias, $condition);
681
682 270
        $this->state = self::STATE_DIRTY;
683
684 270
        return $this;
685
    }
686
687
    /**
688
     * Creates and adds a left join to the query.
689
     *
690
     * <code>
691
     *     $qb = $conn->createQueryBuilder()
692
     *         ->select('u.name')
693
     *         ->from('users', 'u')
694
     *         ->leftJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
695
     * </code>
696
     *
697
     * @param string $fromAlias The alias that points to a from clause.
698
     * @param string $join      The table name to join.
699
     * @param string $alias     The alias of the join table.
700
     * @param string $condition The condition for the join.
701
     *
702
     * @return $this This QueryBuilder instance.
703
     */
704 27
    public function leftJoin(string $fromAlias, string $join, string $alias, ?string $condition = null) : self
705
    {
706 27
        $this->join[$fromAlias][] = Join::left($join, $alias, $condition);
707
708 27
        $this->state = self::STATE_DIRTY;
709
710 27
        return $this;
711
    }
712
713
    /**
714
     * Creates and adds a right join to the query.
715
     *
716
     * <code>
717
     *     $qb = $conn->createQueryBuilder()
718
     *         ->select('u.name')
719
     *         ->from('users', 'u')
720
     *         ->rightJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
721
     * </code>
722
     *
723
     * @param string $fromAlias The alias that points to a from clause.
724
     * @param string $join      The table name to join.
725
     * @param string $alias     The alias of the join table.
726
     * @param string $condition The condition for the join.
727
     *
728
     * @return $this This QueryBuilder instance.
729
     */
730 27
    public function rightJoin(string $fromAlias, string $join, string $alias, ?string $condition = null) : self
731
    {
732 27
        $this->join[$fromAlias][] = Join::right($join, $alias, $condition);
733
734 27
        $this->state = self::STATE_DIRTY;
735
736 27
        return $this;
737
    }
738
739
    /**
740
     * Sets a new value for a column in a bulk update query.
741
     *
742
     * <code>
743
     *     $qb = $conn->createQueryBuilder()
744
     *         ->update('counters', 'c')
745
     *         ->set('c.value', 'c.value + 1')
746
     *         ->where('c.id = ?');
747
     * </code>
748
     *
749
     * @param string $key   The column to set.
750
     * @param string $value The value, expression, placeholder, etc.
751
     *
752
     * @return $this This QueryBuilder instance.
753
     */
754 54
    public function set(string $key, string $value) : self
755
    {
756 54
        $this->set[] = $key . ' = ' . $value;
757
758 54
        $this->state = self::STATE_DIRTY;
759
760 54
        return $this;
761
    }
762
763
    /**
764
     * Specifies one or more restrictions to the query result.
765
     * Replaces any previously specified restrictions, if any.
766
     *
767
     * <code>
768
     *     $qb = $conn->createQueryBuilder()
769
     *         ->select('c.value')
770
     *         ->from('counters', 'c')
771
     *         ->where('c.id = ?');
772
     *
773
     *     // You can optionally programmatically build and/or expressions
774
     *     $qb = $conn->createQueryBuilder();
775
     *
776
     *     $or = $qb->expr()->orx();
777
     *     $or->add($qb->expr()->eq('c.id', 1));
778
     *     $or->add($qb->expr()->eq('c.id', 2));
779
     *
780
     *     $qb->update('counters', 'c')
781
     *         ->set('c.value', 'c.value + 1')
782
     *         ->where($or);
783
     * </code>
784
     *
785
     * @param string|CompositeExpression $predicate     The WHERE clause predicate.
786
     * @param string|CompositeExpression ...$predicates Additional WHERE clause predicates.
787
     *
788
     * @return $this This QueryBuilder instance.
789
     */
790 459
    public function where($predicate, ...$predicates) : self
791
    {
792 459
        $this->where = $this->createPredicate($predicate, ...$predicates);
793
794 459
        $this->state = self::STATE_DIRTY;
795
796 459
        return $this;
797
    }
798
799
    /**
800
     * Adds one or more restrictions to the query results, forming a logical
801
     * conjunction with any previously specified restrictions.
802
     *
803
     * <code>
804
     *     $qb = $conn->createQueryBuilder()
805
     *         ->select('u')
806
     *         ->from('users', 'u')
807
     *         ->where('u.username LIKE ?')
808
     *         ->andWhere('u.is_active = 1');
809
     * </code>
810
     *
811
     * @see where()
812
     *
813
     * @param string|CompositeExpression $predicate     The predicate to append.
814
     * @param string|CompositeExpression ...$predicates Additional predicates to append.
815
     *
816
     * @return $this This QueryBuilder instance.
817
     */
818 162
    public function andWhere($predicate, ...$predicates) : self
819
    {
820 162
        $this->where = $this->appendToPredicate($this->where, CompositeExpression::TYPE_AND, $predicate, ...$predicates);
821
822 162
        $this->state = self::STATE_DIRTY;
823
824 162
        return $this;
825
    }
826
827
    /**
828
     * Adds one or more restrictions to the query results, forming a logical
829
     * disjunction with any previously specified restrictions.
830
     *
831
     * <code>
832
     *     $qb = $em->createQueryBuilder()
833
     *         ->select('u.name')
834
     *         ->from('users', 'u')
835
     *         ->where('u.id = 1')
836
     *         ->orWhere('u.id = 2');
837
     * </code>
838
     *
839
     * @see where()
840
     *
841
     * @param string|CompositeExpression $predicate     The predicate to append.
842
     * @param string|CompositeExpression ...$predicates Additional predicates to append.
843
     *
844
     * @return $this This QueryBuilder instance.
845
     */
846 81
    public function orWhere($predicate, ...$predicates) : self
847
    {
848 81
        $this->where = $this->appendToPredicate($this->where, CompositeExpression::TYPE_OR, $predicate, ...$predicates);
849
850 81
        $this->state = self::STATE_DIRTY;
851
852 81
        return $this;
853
    }
854
855
    /**
856
     * Specifies one or more grouping expressions over the results of the query.
857
     * Replaces any previously specified groupings, if any.
858
     *
859
     * <code>
860
     *     $qb = $conn->createQueryBuilder()
861
     *         ->select('u.name')
862
     *         ->from('users', 'u')
863
     *         ->groupBy('u.id');
864
     * </code>
865
     *
866
     * @param string $expression     The grouping expression
867
     * @param string ...$expressions Additional grouping expressions
868
     *
869
     * @return $this This QueryBuilder instance.
870
     */
871 243
    public function groupBy(string $expression, string ...$expressions) : self
872
    {
873 243
        $this->groupBy = array_merge([$expression], $expressions);
874
875 243
        $this->state = self::STATE_DIRTY;
876
877 243
        return $this;
878
    }
879
880
    /**
881
     * Adds one or more grouping expressions to the query.
882
     *
883
     * <code>
884
     *     $qb = $conn->createQueryBuilder()
885
     *         ->select('u.name')
886
     *         ->from('users', 'u')
887
     *         ->groupBy('u.lastLogin')
888
     *         ->addGroupBy('u.createdAt');
889
     * </code>
890
     *
891
     * @param string $expression     The grouping expression
892
     * @param string ...$expressions Additional grouping expressions
893
     *
894
     * @return $this This QueryBuilder instance.
895
     */
896 54
    public function addGroupBy(string $expression, string ...$expressions) : self
897
    {
898 54
        $this->groupBy = array_merge($this->groupBy, [$expression], $expressions);
899
900 54
        $this->state = self::STATE_DIRTY;
901
902 54
        return $this;
903
    }
904
905
    /**
906
     * Sets a value for a column in an insert query.
907
     *
908
     * <code>
909
     *     $qb = $conn->createQueryBuilder()
910
     *         ->insert('users')
911
     *         ->values(
912
     *             array(
913
     *                 'name' => '?'
914
     *             )
915
     *         )
916
     *         ->setValue('password', '?');
917
     * </code>
918
     *
919
     * @param string $column The column into which the value should be inserted.
920
     * @param string $value  The value that should be inserted into the column.
921
     *
922
     * @return $this This QueryBuilder instance.
923
     */
924 54
    public function setValue(string $column, string $value) : self
925
    {
926 54
        $this->values[$column] = $value;
927
928 54
        return $this;
929
    }
930
931
    /**
932
     * Specifies values for an insert query indexed by column names.
933
     * Replaces any previous values, if any.
934
     *
935
     * <code>
936
     *     $qb = $conn->createQueryBuilder()
937
     *         ->insert('users')
938
     *         ->values(
939
     *             array(
940
     *                 'name' => '?',
941
     *                 'password' => '?'
942
     *             )
943
     *         );
944
     * </code>
945
     *
946
     * @param array<string, mixed> $values The values to specify for the insert query indexed by column names.
947
     *
948
     * @return $this This QueryBuilder instance.
949
     */
950 81
    public function values(array $values) : self
951
    {
952 81
        $this->values = $values;
953
954 81
        $this->state = self::STATE_DIRTY;
955
956 81
        return $this;
957
    }
958
959
    /**
960
     * Specifies a restriction over the groups of the query.
961
     * Replaces any previous having restrictions, if any.
962
     *
963
     * @param string|CompositeExpression $predicate     The HAVING clause predicate.
964
     * @param string|CompositeExpression ...$predicates Additional HAVING clause predicates.
965
     *
966
     * @return $this This QueryBuilder instance.
967
     */
968 108
    public function having($predicate, ...$predicates) : self
969
    {
970 108
        $this->having = $this->createPredicate($predicate, ...$predicates);
971
972 108
        $this->state = self::STATE_DIRTY;
973
974 108
        return $this;
975
    }
976
977
    /**
978
     * Adds a restriction over the groups of the query, forming a logical
979
     * conjunction with any existing having restrictions.
980
     *
981
     * @param string|CompositeExpression $predicate     The predicate to append.
982
     * @param string|CompositeExpression ...$predicates Additional predicates to append.
983
     *
984
     * @return $this This QueryBuilder instance.
985
     */
986 81
    public function andHaving($predicate, ...$predicates) : self
987
    {
988 81
        $this->having = $this->appendToPredicate($this->having, CompositeExpression::TYPE_AND, $predicate, ...$predicates);
989
990 81
        $this->state = self::STATE_DIRTY;
991
992 81
        return $this;
993
    }
994
995
    /**
996
     * Adds a restriction over the groups of the query, forming a logical
997
     * disjunction with any existing having restrictions.
998
     *
999
     * @param string|CompositeExpression $predicate     The predicate to append.
1000
     * @param string|CompositeExpression ...$predicates Additional predicates to append.
1001
     *
1002
     * @return $this This QueryBuilder instance.
1003
     */
1004 81
    public function orHaving($predicate, ...$predicates) : self
1005
    {
1006 81
        $this->having = $this->appendToPredicate($this->having, CompositeExpression::TYPE_OR, $predicate, ...$predicates);
1007
1008 81
        $this->state = self::STATE_DIRTY;
1009
1010 81
        return $this;
1011
    }
1012
1013
    /**
1014
     * Creates a CompositeExpression from one or more predicates combined by the AND logic.
1015
     *
1016
     * @param string|CompositeExpression $predicate
1017
     * @param string|CompositeExpression ...$predicates
1018
     *
1019
     * @return string|CompositeExpression
1020
     */
1021 567
    private function createPredicate($predicate, ...$predicates)
1022
    {
1023 567
        if (count($predicates) === 0) {
1024 567
            return $predicate;
1025
        }
1026
1027
        return new CompositeExpression(CompositeExpression::TYPE_AND, array_merge([$predicate], $predicates));
1028
    }
1029
1030
    /**
1031
     * Appends the given predicates combined by the given type of logic to the current predicate.
1032
     *
1033
     * @param string|CompositeExpression|null $currentPredicate
1034
     * @param string|CompositeExpression      ...$predicates
1035
     *
1036
     * @return string|CompositeExpression
1037
     */
1038 351
    private function appendToPredicate($currentPredicate, string $type, ...$predicates)
1039
    {
1040 351
        if ($currentPredicate instanceof CompositeExpression && $currentPredicate->getType() === $type) {
1041
            return $currentPredicate->addMultiple($predicates);
1042
        }
1043
1044 351
        if ($currentPredicate !== null) {
1045 324
            array_unshift($predicates, $currentPredicate);
1046 81
        } elseif (count($predicates) === 1) {
1047 81
            return $predicates[0];
1048
        }
1049
1050 324
        return new CompositeExpression($type, $predicates);
1051
    }
1052
1053
    /**
1054
     * Specifies an ordering for the query results.
1055
     * Replaces any previously specified orderings, if any.
1056
     *
1057
     * @param string $sort  The ordering expression.
1058
     * @param string $order The ordering direction.
1059
     *
1060
     * @return $this This QueryBuilder instance.
1061
     */
1062 54
    public function orderBy(string $sort, ?string $order = null) : self
1063
    {
1064 54
        $orderBy = $sort;
1065
1066 54
        if ($order !== null) {
1067
            $orderBy .= ' ' . $order;
1068
        }
1069
1070 54
        $this->orderBy = [$orderBy];
1071
1072 54
        $this->state = self::STATE_DIRTY;
1073
1074 54
        return $this;
1075
    }
1076
1077
    /**
1078
     * Adds an ordering to the query results.
1079
     *
1080
     * @param string $sort  The ordering expression.
1081
     * @param string $order The ordering direction.
1082
     *
1083
     * @return $this This QueryBuilder instance.
1084
     */
1085 54
    public function addOrderBy(string $sort, ?string $order = null) : self
1086
    {
1087 54
        $orderBy = $sort;
1088
1089 54
        if ($order !== null) {
1090 54
            $orderBy .= ' ' . $order;
1091
        }
1092
1093 54
        $this->orderBy[] = $orderBy;
1094
1095 54
        $this->state = self::STATE_DIRTY;
1096
1097 54
        return $this;
1098
    }
1099
1100
    /**
1101
     * @throws QueryException
1102
     */
1103 1215
    private function getSQLForSelect() : string
1104
    {
1105 1215
        if (count($this->select) === 0) {
1106 27
            throw new QueryException('No SELECT expressions given. Please use select() or addSelect().');
1107
        }
1108
1109 1188
        $query = 'SELECT';
1110
1111 1188
        if ($this->distinct) {
1112 27
            $query .= ' DISTINCT';
1113
        }
1114
1115 1188
        $query .= ' ' . implode(', ', $this->select);
1116
1117 1188
        if (count($this->from) !== 0) {
1118 1161
            $query .= ' FROM ' . implode(', ', $this->getFromClauses());
1119
        }
1120
1121 1134
        if ($this->where !== null) {
1122 351
            $query .= ' WHERE ' . $this->where;
1123
        }
1124
1125 1134
        if (count($this->groupBy) !== 0) {
1126 243
            $query .= ' GROUP BY ' . implode(', ', $this->groupBy);
1127
        }
1128
1129 1134
        if ($this->having !== null) {
1130 162
            $query .= ' HAVING ' . $this->having;
1131
        }
1132
1133 1134
        if (count($this->orderBy) !== 0) {
1134 81
            $query .= ' ORDER BY ' . implode(', ', $this->orderBy);
1135
        }
1136
1137 1134
        if ($this->isLimitQuery()) {
1138
            return $this->connection->getDatabasePlatform()->modifyLimitQuery(
1139
                $query,
1140
                $this->maxResults,
1141
                $this->firstResult
1142
            );
1143
        }
1144
1145 1134
        return $query;
1146
    }
1147
1148
    /**
1149
     * @return array<string, string>
1150
     */
1151 1161
    private function getFromClauses() : array
1152
    {
1153 1161
        $fromClauses  = [];
1154 1161
        $knownAliases = [];
1155
1156 1161
        foreach ($this->from as $from) {
1157 1161
            if ($from->alias === null || $from->alias === $from->table) {
1158 189
                $tableSql       = $from->table;
1159 189
                $tableReference = $from->table;
1160
            } else {
1161 999
                $tableSql       = $from->table . ' ' . $from->alias;
1162 999
                $tableReference = $from->alias;
1163
            }
1164
1165 1161
            $knownAliases[$tableReference] = true;
1166
1167 1161
            $fromClauses[$tableReference] = $tableSql . $this->getSQLForJoins($tableReference, $knownAliases);
1168
        }
1169
1170 1134
        $this->verifyAllAliasesAreKnown($knownAliases);
1171
1172 1107
        return $fromClauses;
1173
    }
1174
1175
    /**
1176
     * @param array<string, true> $knownAliases
1177
     *
1178
     * @throws QueryException
1179
     */
1180 1134
    private function verifyAllAliasesAreKnown(array $knownAliases) : void
1181
    {
1182 1134
        foreach ($this->join as $fromAlias => $joins) {
1183 297
            if (! isset($knownAliases[$fromAlias])) {
1184 27
                throw UnknownAlias::new($fromAlias, array_keys($knownAliases));
1185
            }
1186
        }
1187 1107
    }
1188
1189 1134
    private function isLimitQuery() : bool
1190
    {
1191 1134
        return $this->maxResults !== null || $this->firstResult !== 0;
1192
    }
1193
1194
    /**
1195
     * Converts this instance into an INSERT string in SQL.
1196
     */
1197 108
    private function getSQLForInsert() : string
1198
    {
1199 108
        return 'INSERT INTO ' . $this->table .
1200 108
        ' (' . implode(', ', array_keys($this->values)) . ')' .
1201 108
        ' VALUES(' . implode(', ', $this->values) . ')';
1202
    }
1203
1204
    /**
1205
     * Converts this instance into an UPDATE string in SQL.
1206
     */
1207 54
    private function getSQLForUpdate() : string
1208
    {
1209 54
        $query = 'UPDATE ' . $this->table . ' SET ' . implode(', ', $this->set);
1210
1211 54
        if ($this->where !== null) {
1212 27
            $query .= ' WHERE ' . $this->where;
1213
        }
1214
1215 54
        return $query;
1216
    }
1217
1218
    /**
1219
     * Converts this instance into a DELETE string in SQL.
1220
     */
1221 54
    private function getSQLForDelete() : string
1222
    {
1223 54
        $query = 'DELETE FROM ' . $this->table;
1224
1225 54
        if ($this->where !== null) {
1226 27
            $query .= ' WHERE ' . $this->where;
1227
        }
1228
1229 54
        return $query;
1230
    }
1231
1232
    /**
1233
     * Gets a string representation of this QueryBuilder which corresponds to
1234
     * the final SQL query being constructed.
1235
     *
1236
     * @return string The string representation of this QueryBuilder.
1237
     */
1238 1215
    public function __toString() : string
1239
    {
1240 1215
        return $this->getSQL();
1241
    }
1242
1243
    /**
1244
     * Creates a new named parameter and bind the value $value to it.
1245
     *
1246
     * This method provides a shortcut for PDOStatement::bindValue
1247
     * when using prepared statements.
1248
     *
1249
     * The parameter $value specifies the value that you want to bind. If
1250
     * $placeholder is not provided bindValue() will automatically create a
1251
     * placeholder for you. An automatic placeholder will be of the name
1252
     * ':dcValue1', ':dcValue2' etc.
1253
     *
1254
     * For more information see {@link http://php.net/pdostatement-bindparam}
1255
     *
1256
     * Example:
1257
     * <code>
1258
     * $value = 2;
1259
     * $q->eq( 'id', $q->bindValue( $value ) );
1260
     * $stmt = $q->executeQuery(); // executed with 'id = 2'
1261
     * </code>
1262
     *
1263
     * @link http://www.zetacomponents.org
1264
     *
1265
     * @param mixed  $value
1266
     * @param mixed  $type
1267
     * @param string $placeHolder The name to bind with. The string must start with a colon ':'.
1268
     *
1269
     * @return string the placeholder name used.
1270
     */
1271 54
    public function createNamedParameter($value, $type = ParameterType::STRING, ?string $placeHolder = null) : string
1272
    {
1273 54
        if ($placeHolder === null) {
1274 27
            $this->boundCounter++;
1275 27
            $placeHolder = ':dcValue' . $this->boundCounter;
1276
        }
1277 54
        $this->setParameter(substr($placeHolder, 1), $value, $type);
1278
1279 54
        return $placeHolder;
1280
    }
1281
1282
    /**
1283
     * Creates a new positional parameter and bind the given value to it.
1284
     *
1285
     * Attention: If you are using positional parameters with the query builder you have
1286
     * to be very careful to bind all parameters in the order they appear in the SQL
1287
     * statement , otherwise they get bound in the wrong order which can lead to serious
1288
     * bugs in your code.
1289
     *
1290
     * Example:
1291
     * <code>
1292
     *  $qb = $conn->createQueryBuilder();
1293
     *  $qb->select('u.*')
1294
     *     ->from('users', 'u')
1295
     *     ->where('u.username = ' . $qb->createPositionalParameter('Foo', ParameterType::STRING))
1296
     *     ->orWhere('u.username = ' . $qb->createPositionalParameter('Bar', ParameterType::STRING))
1297
     * </code>
1298
     *
1299
     * @param mixed $value
1300
     */
1301 27
    public function createPositionalParameter($value, int $type = ParameterType::STRING) : string
1302
    {
1303 27
        $this->boundCounter++;
1304 27
        $this->setParameter($this->boundCounter, $value, $type);
1305
1306 27
        return '?';
1307
    }
1308
1309
    /**
1310
     * @param array<string, true> $knownAliases
1311
     *
1312
     * @throws QueryException
1313
     */
1314 1161
    private function getSQLForJoins(string $fromAlias, array &$knownAliases) : string
1315
    {
1316 1161
        $sql = '';
1317
1318 1161
        if (! isset($this->join[$fromAlias])) {
1319 1134
            return $sql;
1320
        }
1321
1322 324
        foreach ($this->join[$fromAlias] as $join) {
1323 324
            if (array_key_exists($join->alias, $knownAliases)) {
1324 27
                throw NonUniqueAlias::new($join->alias, array_keys($knownAliases));
1325
            }
1326 297
            $sql                       .= ' ' . $join->type
1327 297
                . ' JOIN ' . $join->table . ' ' . $join->alias
1328 297
                . ' ON ' . ((string) $join->condition);
1329 297
            $knownAliases[$join->alias] = true;
1330
        }
1331
1332 297
        foreach ($this->join[$fromAlias] as $join) {
1333 297
            $sql .= $this->getSQLForJoins($join->alias, $knownAliases);
1334
        }
1335
1336 297
        return $sql;
1337
    }
1338
1339
    /**
1340
     * Deep clone of all expression objects in the SQL parts.
1341
     */
1342 27
    public function __clone()
1343
    {
1344 27
        foreach ($this->from as $key => $from) {
1345 27
            $this->from[$key] = clone $from;
1346
        }
1347
1348 27
        foreach ($this->join as $fromAlias => $joins) {
1349
            foreach ($joins as $key => $join) {
1350
                $this->join[$fromAlias][$key] = clone $join;
1351
            }
1352
        }
1353
1354 27
        if (is_object($this->where)) {
1355
            $this->where = clone $this->where;
1356
        }
1357
1358 27
        if (is_object($this->having)) {
1359
            $this->having = clone $this->having;
1360
        }
1361
1362 27
        foreach ($this->params as $name => $param) {
1363 27
            if (! is_object($param)) {
1364
                continue;
1365
            }
1366
1367 27
            $this->params[$name] = clone $param;
1368
        }
1369 27
    }
1370
}
1371