summaryrefslogtreecommitdiffstats
path: root/vendor/ipl/sql/src/QueryBuilder.php
blob: 3a551d2eeefee664cbdebaafc561d81ddf812fca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
<?php

namespace ipl\Sql;

use InvalidArgumentException;
use ipl\Sql\Adapter\Mssql;
use ipl\Sql\Contract\Adapter;
use ipl\Stdlib\Events;

use function ipl\Stdlib\get_php_type;

class QueryBuilder
{
    use Events;

    /**
     * Event raised when a {@link Select} object is assembled into a SQL statement string
     *
     * The {@link Select} object is passed as parameter to the event callbacks.
     *
     * **Example usage:**
     *
     * ```
     * $queryBuilder->on(QueryBuilder::ON_ASSEMBLE_SELECT, function (Select $select) {
     *     // ...
     * });
     * ```
     */
    const ON_ASSEMBLE_SELECT = 'assembleSelect';

    /**
     * Event raised after a {@link Select} object is assembled into a SQL statement string
     *
     * The assembled SQL statement string and the values to bind to the statement are passed as parameters by reference
     * to the event callbacks.
     *
     * **Example usage:**
     *
     * ```
     * $queryBuilder->on(QueryBuilder::ON_SELECT_ASSEMBLED, function (&$sql, &$values) {
     *     // ...
     * });
     * ```
     */
    const ON_SELECT_ASSEMBLED = 'selectAssembled';

    /**
     * Event raised before an {@see Insert} object is assembled into a SQL statement string
     *
     * **Example usage:**
     *
     * ```
     * $queryBuilder->on(QueryBuilder::ON_ASSEMBLE_INSERT, function (Insert $insert) {
     *     // ...
     * });
     * ```
     *
     * @var string
     */
    const ON_ASSEMBLE_INSERT = 'assembleInsert';

    /**
     * Event raised after an {@see Insert} object is assembled into a SQL statement string
     *
     * The assembled SQL statement string and the prepared values are passed by reference to the event callbacks
     *
     * **Example usage:**
     *
     * ```
     * $queryBuilder->on(QueryBuilder::ON_INSERT_ASSEMBLED, function (&$sql, &$values) {
     *     // ...
     * });
     * ```
     *
     * @var string
     */
    const ON_INSERT_ASSEMBLED = 'insertAssembled';

    /**
     * Event raised before an {@see Update} object is assembled into a SQL statement string
     *
     * **Example usage:**
     *
     * ```
     * $queryBuilder->on(QueryBuilder::ON_ASSEMBLE_UPDATE, function (Update $update) {
     *     // ...
     * });
     * ```
     *
     * @var string
     */
    const ON_ASSEMBLE_UPDATE = 'assembleUpdate';

    /**
     * Event raised after an {@see Update} object is assembled into a SQL statement string
     *
     * The assembled SQL statement string and the prepared values are passed by reference to the event callbacks
     *
     * **Example usage:**
     *
     * ```
     * $queryBuilder->on(QueryBuilder::ON_UPDATE_ASSEMBLED, function (&$sql, &$values) {
     *     // ...
     * });
     * ```
     *
     * @var string
     */
    const ON_UPDATE_ASSEMBLED = 'updateAssembled';

    /**
     * Event raised before a {@see Delete} object is assembled into a SQL statement string
     *
     * **Example usage:**
     *
     * ```
     * $queryBuilder->on(QueryBuilder::ON_ASSEMBLE_DELETE, function (Delete $delete) {
     *     // ...
     * });
     * ```
     *
     * @var string
     */
    const ON_ASSEMBLE_DELETE = 'assembleDelete';

    /**
     * Event raised after a {@see Delete} object is assembled into a SQL statement string
     *
     * The assembled SQL statement string and the prepared values are passed by reference to the event callbacks
     *
     * **Example usage:**
     *
     * ```
     * $queryBuilder->on(QueryBuilder::ON_DELETE_ASSEMBLED, function (&$sql, &$values) {
     *     // ...
     * });
     * ```
     *
     * @var string
     */
    const ON_DELETE_ASSEMBLED = 'deleteAssembled';

    /** @var Adapter */
    protected $adapter;

    protected $separator = " ";

    /**
     * Create a new query builder for the specified database adapter
     *
     * @param Adapter $adapter
     */
    public function __construct(Adapter $adapter)
    {
        $adapter->registerQueryBuilderCallbacks($this);

        $this->adapter = $adapter;
    }

    /**
     * Assemble the given statement
     *
     * @param Delete|Insert|Select|Update $stmt
     *
     * @return array
     *
     * @throw InvalidArgumentException If statement type is invalid
     */
    public function assemble($stmt)
    {
        switch (true) {
            case $stmt instanceof Delete:
                return $this->assembleDelete($stmt);
            case $stmt instanceof Insert:
                return $this->assembleInsert($stmt);
            case $stmt instanceof Select:
                return $this->assembleSelect($stmt);
            case $stmt instanceof Update:
                return $this->assembleUpdate($stmt);
            default:
                throw new InvalidArgumentException(sprintf(
                    __METHOD__ . ' expects instances of Delete, Insert, Select or Update. Got %s instead.',
                    get_php_type($stmt)
                ));
        }
    }

    /**
     * Assemble a DELETE query
     *
     * @param Delete $delete
     *
     * @return array
     */
    public function assembleDelete(Delete $delete)
    {
        $values = [];

        $this->emit(self::ON_ASSEMBLE_DELETE, [$delete]);

        $sql = array_filter([
            $this->buildWith($delete->getWith(), $values),
            $this->buildDeleteFrom($delete->getFrom()),
            $this->buildWhere($delete->getWhere(), $values)
        ]);

        $sql = implode($this->separator, $sql);

        $this->emit(static::ON_DELETE_ASSEMBLED, [&$sql, &$values]);

        return [$sql, $values];
    }

    /**
     * Assemble a INSERT statement
     *
     * @param Insert $insert
     *
     * @return array
     */
    public function assembleInsert(Insert $insert)
    {
        $values = [];

        $this->emit(static::ON_ASSEMBLE_INSERT, [$insert]);

        $select = $insert->getSelect();

        $sql = array_filter([
            $this->buildWith($insert->getWith(), $values),
            $this->buildInsertInto($insert->getInto()),
            $select
                ? $this->buildInsertIntoSelect($insert->getColumns(), $select, $values)
                : $this->buildInsertColumnsAndValues($insert->getColumns(), $insert->getValues(), $values)
        ]);

        $sql = implode($this->separator, $sql);

        $this->emit(static::ON_INSERT_ASSEMBLED, [&$sql, &$values]);

        return [$sql, $values];
    }

    /**
     * Assemble a SELECT query
     *
     * @param Select $select
     * @param array  $values
     *
     * @return array
     */
    public function assembleSelect(Select $select, array &$values = [])
    {
        $select = clone $select;

        $this->emit(static::ON_ASSEMBLE_SELECT, [$select]);

        $sql = array_filter([
            $this->buildWith($select->getWith(), $values),
            $this->buildSelect($select->getColumns(), $select->getDistinct(), $values),
            $this->buildFrom($select->getFrom(), $values),
            $this->buildJoin($select->getJoin(), $values),
            $this->buildWhere($select->getWhere(), $values),
            $this->buildGroupBy($select->getGroupBy(), $values),
            $this->buildHaving($select->getHaving(), $values),
            $this->buildOrderBy($select->getOrderBy(), $values),
            $this->buildLimitOffset($select->getLimit(), $select->getOffset())
        ]);

        $sql = implode($this->separator, $sql);

        $unions = $this->buildUnions($select->getUnion(), $values);
        if ($unions) {
            list($unionKeywords, $selects) = $unions;

            if ($sql) {
                $sql = "($sql)";

                $requiresUnionKeyword = true;
            } else {
                $requiresUnionKeyword = false;
            }

            do {
                $unionKeyword = array_shift($unionKeywords);
                $select = array_shift($selects);

                if ($requiresUnionKeyword) {
                    $sql .= "{$this->separator}$unionKeyword{$this->separator}";
                }

                $sql .= "($select)";

                $requiresUnionKeyword = true;
            } while (! empty($unionKeywords));
        }

        $this->emit(static::ON_SELECT_ASSEMBLED, [&$sql, &$values]);

        return [$sql, $values];
    }

    /**
     * Assemble a UPDATE query
     *
     * @param Update $update
     *
     * @return array
     */
    public function assembleUpdate(Update $update)
    {
        $values = [];

        $this->emit(self::ON_ASSEMBLE_UPDATE, [$update]);

        $sql = array_filter([
            $this->buildWith($update->getWith(), $values),
            $this->buildUpdateTable($update->getTable()),
            $this->buildUpdateSet($update->getSet(), $values),
            $this->buildWhere($update->getWhere(), $values)
        ]);

        $sql = implode($this->separator, $sql);

        $this->emit(static::ON_UPDATE_ASSEMBLED, [&$sql, &$values]);

        return [$sql, $values];
    }

    /**
     * Build the WITH part of a query
     *
     * @param array $with
     * @param array $values
     *
     * @return string The WITH part of a query
     */
    public function buildWith(array $with, array &$values)
    {
        if (empty($with)) {
            return '';
        }

        $ctes = [];
        $hasRecursive = false;

        foreach ($with as $cte) {
            list($query, $alias, $recursive) = $cte;
            list($cteSql, $cteValues) = $this->assembleSelect($query);

            $ctes[] = "$alias AS ($cteSql)";

            $values = array_merge($values, $cteValues);
            $hasRecursive |= $recursive;
        }

        return ($hasRecursive ? 'WITH RECURSIVE ' : 'WITH ') . implode(', ', $ctes);
    }

    /**
     * Build the DELETE FROM part of a query
     *
     * @param array $from
     *
     * @return string The DELETE FROM part of a query
     */
    public function buildDeleteFrom(array $from = null)
    {
        if ($from === null) {
            return '';
        }

        $deleteFrom = 'DELETE FROM';

        reset($from);
        $alias = key($from);
        $table = current($from);

        if (is_int($alias)) {
            $deleteFrom .= " $table";
        } else {
            $deleteFrom .= " $table $alias";
        }

        return $deleteFrom;
    }

    /**
     * Outsourced logic of {@link buildCondition()}
     *
     * @param string $expression
     * @param array  $values
     *
     * @return array
     */
    public function unpackCondition($expression, array $values)
    {
        $placeholders = preg_match_all('/(\?)/', $expression, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);

        if ($placeholders === 0) {
            return [$expression, []];
        }

        if ($placeholders === 1) {
            $offset = $matches[0][1][1];
            $expression = substr($expression, 0, $offset)
                . implode(', ', array_fill(0, count($values), '?'))
                . substr($expression, $offset + 1);

            return [$expression, $values];
        }

        $unpackedExpression = [];
        $unpackedValues = [];
        $offset = 0;

        foreach ($matches as $match) {
            $value = array_shift($values);
            $unpackedExpression[] = substr($expression, $offset, $match[1][1] - $offset);
            if (is_array($value)) {
                $unpackedExpression[] = implode(', ', array_fill(0, count($value), '?'));
                $unpackedValues = array_merge($unpackedValues, $value);
            } else {
                $unpackedExpression[] = '?';
                $unpackedValues[] = $value;
            }
            $offset = $match[1][1] + 1; // 1 is the length of '?'
        }

        $unpackedExpression[] = substr($expression, $offset);

        return [implode('', array_filter($unpackedExpression)), $unpackedValues];
    }

    /**
     * Outsourced logic {@link buildWhere()} and {@link buildHaving()} have in common
     *
     * @param array $condition
     * @param array $values
     *
     * @return string
     */
    public function buildCondition(array $condition, array &$values)
    {
        $sql = [];

        $operator = array_shift($condition);
        $conditions = array_shift($condition);

        foreach ($conditions as $expression => $value) {
            if (is_array($value)) {
                if (is_int($expression)) {
                    // Operator format
                    $sql[] = $this->buildCondition($value, $values);
                } else {
                    list($unpackedExpression, $unpackedValues) = $this->unpackCondition($expression, $value);
                    $sql[] = $unpackedExpression;
                    $values = array_merge($values, $unpackedValues);
                }
            } else {
                if ($value instanceof ExpressionInterface) {
                    $sql[] = $this->buildExpression($value, $values);
                } elseif ($value instanceof Select) {
                    $stmt = '(' . $this->assembleSelect($value, $values)[0] . ')';
                    if (is_int($expression)) {
                        $sql[] = $stmt;
                    } else {
                        $sql[] = str_replace('?', $stmt, $expression);
                    }
                } elseif (is_int($expression)) {
                    $sql[] = $value;
                } else {
                    $sql[] = $expression;
                    $values[] = $value;
                }
            }
        }

        if ($operator === Sql::NOT_ALL || $operator === Sql::NOT_ANY) {
            return 'NOT (' . implode(") $operator (", $sql) . ')';
        }

        return count($sql) === 1 ? $sql[0] : '(' . implode(") $operator (", $sql) . ')';
    }

    /**
     * Build the WHERE part of a query
     *
     * @param array $where
     * @oaram array $values
     *
     * @return string The WHERE part of the query
     */
    public function buildWhere(array $where = null, array &$values = [])
    {
        if ($where === null) {
            return '';
        }

        return 'WHERE ' . $this->buildCondition($where, $values);
    }

    /**
     * Build the INSERT INTO part of a INSERT INTO ... statement
     *
     * @param string|null $into
     *
     * @return string The INSERT INTO part of a INSERT INTO ... statement
     */
    public function buildInsertInto($into)
    {
        if (empty($into)) {
            return '';
        }

        return "INSERT INTO $into";
    }

    /**
     * Build the columns and SELECT part of a INSERT INTO ... SELECT statement
     *
     * @param array  $columns
     * @param Select $select
     * @param array  $values
     *
     * @return string The columns and SELECT part of the INSERT INTO ... SELECT statement
     */
    public function buildInsertIntoSelect(array $columns, Select $select, array &$values)
    {
        $sql = [
            '(' . implode(',', $columns) . ')',
            $this->assembleSelect($select, $values)[0]
        ];

        return implode($this->separator, $sql);
    }

    /**
     * Build the columns and values part of a INSERT INTO ... statement
     *
     * @param array $columns
     * @param array $insertValues
     * @param array $values
     *
     * @return string The columns and values part of a INSERT INTO ... statement
     */
    public function buildInsertColumnsAndValues(array $columns, array $insertValues, array &$values)
    {
        $sql = ['(' . implode(',', $columns) . ')'];

        $preparedValues = [];

        foreach ($insertValues as $value) {
            if ($value instanceof ExpressionInterface) {
                $preparedValues[] = $this->buildExpression($value, $values);
            } elseif ($value instanceof Select) {
                $preparedValues[] = "({$this->assembleSelect($value, $values)[0]})";
            } else {
                $preparedValues[] = '?';
                $values[] = $value;
            }
        }

        $sql[] = 'VALUES(' . implode(',', $preparedValues) . ')';

        return implode($this->separator, $sql);
    }

    /**
     * Build the SELECT part of a query
     *
     * @param array $columns
     * @param bool  $distinct
     * @param array $values
     *
     * @return string The SELECT part of the query
     */
    public function buildSelect(array $columns, $distinct, array &$values)
    {
        if (empty($columns)) {
            return '';
        }

        $select = 'SELECT';

        if ($distinct) {
            $select .= ' DISTINCT';
        }

        if (empty($columns)) {
            return "$select *";
        }

        $sql = [];

        foreach ($columns as $alias => $column) {
            if ($column instanceof ExpressionInterface) {
                $column = "({$this->buildExpression($column, $values)})";
            } elseif ($column instanceof Select) {
                $column = "({$this->assembleSelect($column, $values)[0]})";
            }

            if (is_int($alias)) {
                $sql[] = $column;
            } else {
                $sql[] = "$column AS $alias";
            }
        }

        return "$select " . implode(', ', $sql);
    }

    /**
     * Build the FROM part of a query
     *
     * @param array $from
     * @param array $values
     *
     * @return string The FROM part of the query
     */
    public function buildFrom(array $from = null, array &$values = [])
    {
        if ($from === null) {
            return '';
        }

        $sql = [];

        foreach ($from as $alias => $table) {
            if ($table instanceof Select) {
                $table = "({$this->assembleSelect($table, $values)[0]})";
            }

            if (is_int($alias) || $alias === $table) {
                $sql[] = $table;
            } else {
                $sql[] = "$table $alias";
            }
        }

        return 'FROM ' . implode(', ', $sql);
    }

    /**
     * Build the JOIN part(s) of a query
     *
     * @param array $joins
     * @oaram array $values
     *
     * @return string The JOIN part(s) of the query
     */
    public function buildJoin($joins, array &$values)
    {
        if ($joins === null) {
            return '';
        }

        $sql = [];
        foreach ($joins as $join) {
            list($joinType, $table, $condition) = $join;

            if (is_array($table)) {
                foreach ($table as $alias => $tableName) {
                    break;
                }
            } else {
                $alias = null;
                $tableName = $table;
            }

            if ($tableName instanceof Select) {
                $tableName = "({$this->assembleSelect($tableName, $values)[0]})";
            }

            if (is_array($condition)) {
                $condition = $this->buildCondition($condition, $values);
            }

            if (empty($alias) || $alias === $tableName) {
                $sql[] = "$joinType JOIN $tableName ON $condition";
            } else {
                $sql[] = "$joinType JOIN $tableName $alias ON $condition";
            }
        }

        return implode($this->separator, $sql);
    }

    /**
     * Build the GROUP BY part of a query
     *
     * @param array $groupBy
     * @param array $values
     *
     * @return string The GROUP BY part of the query
     */
    public function buildGroupBy(array $groupBy = null, array &$values = [])
    {
        if ($groupBy === null) {
            return '';
        }

        foreach ($groupBy as &$column) {
            if ($column instanceof ExpressionInterface) {
                $column = $this->buildExpression($column, $values);
            } elseif ($column instanceof Select) {
                $column = "({$this->assembleSelect($column, $values)[0]})";
            }
        }

        return 'GROUP BY ' . implode(', ', $groupBy);
    }

    /**
     * Build the HAVING part of a query
     *
     * @param array $having
     * @param array $values
     *
     * @return string The HAVING part of the query
     */
    public function buildHaving(array $having = null, array &$values = [])
    {
        if ($having === null) {
            return '';
        }

        return 'HAVING ' . $this->buildCondition($having, $values);
    }

    /**
     * Build the ORDER BY part of a query
     *
     * @param array $orderBy
     * @param array $values
     *
     * @return string The ORDER BY part of the query
     */
    public function buildOrderBy(array $orderBy = null, array &$values = [])
    {
        if ($orderBy === null) {
            return '';
        }

        $sql = [];

        foreach ($orderBy as $column) {
            list($column, $direction) = $column;

            if ($column instanceof ExpressionInterface) {
                $column = $this->buildExpression($column, $values);
            } elseif ($column instanceof Select) {
                $column = "({$this->assembleSelect($column, $values)[0]})";
            }

            if ($direction !== null) {
                $sql[] = "$column $direction";
            } else {
                $sql[] = $column;
            }
        }

        return 'ORDER BY ' . implode(', ', $sql);
    }

    /**
     * Build the LIMIT and OFFSET part of a query
     *
     * @param int $limit
     * @param int $offset
     *
     * @return string The LIMIT and OFFSET part of the query
     */
    public function buildLimitOffset($limit = null, $offset = null)
    {
        $sql = [];

        if ($this->adapter instanceof Mssql) {
            if ($offset !== null || $limit !== null) {
                // If offset is null, sprintf will convert it to 0
                $sql[] = sprintf('OFFSET %d ROWS', $offset);
            }

            if ($limit !== null) {
                // FETCH FIRST n ROWS ONLY for OFFSET 0 would be an alternative here
                $sql[] = "FETCH NEXT $limit ROWS ONLY";
            }
        } else {
            if ($limit !== null) {
                $sql[] = "LIMIT $limit";
            }

            if ($offset !== null) {
                $sql[] = "OFFSET $offset";
            }
        }

        return implode($this->separator, $sql);
    }

    /**
     * Build the UNION parts of a query
     *
     * @param array $unions
     * @param array $values
     *
     * @return array|null The UNION parts of the query
     */
    public function buildUnions(array $unions = null, array &$values = [])
    {
        if ($unions === null) {
            return null;
        }

        $unionKeywords = [];
        $selects = [];

        foreach ($unions as $union) {
            list($select, $all) = $union;

            if ($select instanceof Select) {
                list($select, $values) = $this->assembleSelect($select, $values);
            }

            $unionKeywords[] = ($all ? 'UNION ALL' : 'UNION');
            $selects[] = $select;
        }

        return [$unionKeywords, $selects];
    }

    /**
     * Build the UPDATE {table} part of a query
     *
     * @param array $updateTable The table to UPDATE
     *
     * @return string The UPDATE {table} part of the query
     */
    public function buildUpdateTable(array $updateTable = null)
    {
        if ($updateTable === null) {
            return '';
        }

        $update = 'UPDATE';

        reset($updateTable);
        $alias = key($updateTable);
        $table = current($updateTable);

        if (is_int($alias)) {
            $update .= " $table";
        } else {
            $update .= " $table $alias";
        }

        return $update;
    }

    /**
     * Build the SET part of a UPDATE query
     *
     * @param array $set
     * @param array $values
     *
     * @return string The SET part of a UPDATE query
     */
    public function buildUpdateSet(array $set = null, array &$values = [])
    {
        if (empty($set)) {
            return '';
        }

        $sql = [];

        foreach ($set as $column => $value) {
            if ($value instanceof ExpressionInterface) {
                $sql[] = "$column = {$this->buildExpression($value, $values)}";
            } elseif ($value instanceof Select) {
                $sql[] = "$column = ({$this->assembleSelect($value, $values)[0]})";
            } else {
                $sql[] = "$column = ?";
                $values[] = $value;
            }
        }

        return 'SET ' . implode(', ', $sql);
    }

    /**
     * Build expression
     *
     * @param ExpressionInterface $expression
     * @param array $values
     *
     * @return string The expression's statement
     */
    public function buildExpression(ExpressionInterface $expression, array &$values = [])
    {
        $stmt = $expression->getStatement();
        $columns = $expression->getColumns();
        if (! empty($columns)) {
            $stmt = vsprintf($stmt, $columns);
        }

        $values = array_merge($values, $expression->getValues());

        return $stmt;
    }
}