Passed
Push — master ( 9607e5...058f8b )
by Wilmer
09:15
created

QueryBuilder::dropCheck()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Query;
6
7
use function array_combine;
8
use function array_diff;
9
use function array_filter;
10
use function array_keys;
11
use function array_map;
12
use function array_merge;
13
use function array_reverse;
14
use function array_shift;
15
use function array_unique;
16
use function array_values;
17
use function array_walk;
18
use function count;
19
use function ctype_digit;
20
use Generator;
21
use function get_class;
22
use function implode;
23
use function in_array;
24
use function is_array;
25
use function is_int;
26
use function is_object;
27
use function is_string;
28
29
use function is_subclass_of;
30
use function json_encode;
31
use JsonException;
32
use function ltrim;
33
use function preg_match;
34
use function preg_replace;
35
use function preg_split;
36
use function reset;
37
use function strpos;
38
use function strtoupper;
39
use function strtr;
40
use function trim;
41
use Yiisoft\Db\Connection\Connection;
42
use Yiisoft\Db\Constraint\Constraint;
43
use Yiisoft\Db\Constraint\ConstraintFinderInterface;
44
use Yiisoft\Db\Exception\Exception;
45
use Yiisoft\Db\Exception\InvalidArgumentException;
46
use Yiisoft\Db\Exception\InvalidConfigException;
47
use Yiisoft\Db\Exception\NotSupportedException;
48
use Yiisoft\Db\Expression\Expression;
49
use Yiisoft\Db\Expression\ExpressionBuilder;
50
use Yiisoft\Db\Expression\ExpressionBuilderInterface;
51
use Yiisoft\Db\Expression\ExpressionInterface;
52
use Yiisoft\Db\Pdo\PdoValue;
53
use Yiisoft\Db\Pdo\PdoValueBuilder;
54
use Yiisoft\Db\Query\Conditions\ConditionInterface;
55
use Yiisoft\Db\Query\Conditions\HashCondition;
56
use Yiisoft\Db\Query\Conditions\SimpleCondition;
57
use Yiisoft\Db\Schema\ColumnSchemaBuilder;
58
use Yiisoft\Db\Schema\Schema;
59
use Yiisoft\Strings\NumericHelper;
60
61
/**
62
 * QueryBuilder builds a SELECT SQL statement based on the specification given as a {@see Query} object.
63
 *
64
 * SQL statements are created from {@see Query} objects using the {@see build()}-method.
65
 *
66
 * QueryBuilder is also used by {@see Command} to build SQL statements such as INSERT, UPDATE, DELETE, CREATE TABLE.
67
 *
68
 * For more details and usage information on QueryBuilder:
69
 * {@see [guide article on query builders](guide:db-query-builder)}.
70
 *
71
 * @property string[] $conditionClasses Map of condition aliases to condition classes. This property is write-only.
72
 *
73
 * For example:
74
 * ```php
75
 *     ['LIKE' => \Yiisoft\Db\Condition\LikeCondition::class]
76
 * ```
77
 * @property string[] $expressionBuilders Array of builders that should be merged with the pre-defined ones in
78
 * {@see expressionBuilders} property. This property is write-only.
79
 */
80
class QueryBuilder
81
{
82
    /**
83
     * The prefix for automatically generated query binding parameters.
84
     */
85
    public const PARAM_PREFIX = ':qp';
86
87
    /**
88
     * @var array the abstract column types mapped to physical column types.
89
     * This is mainly used to support creating/modifying tables using DB-independent data type specifications.
90
     * Child classes should override this property to declare supported type mappings.
91
     */
92
    protected array $typeMap = [];
93
94
    /**
95
     * @var array map of condition aliases to condition classes. For example:
96
     *
97
     * ```php
98
     * return [
99
     *     'LIKE' => \Yiisoft\Db\Condition\LikeCondition::class,
100
     * ];
101
     * ```
102
     *
103
     * This property is used by {@see createConditionFromArray} method.
104
     * See default condition classes list in {@see defaultConditionClasses()} method.
105
     *
106
     * In case you want to add custom conditions support, use the {@see setConditionClasses()} method.
107
     *
108
     * @see setConditonClasses()
109
     * @see defaultConditionClasses()
110
     */
111
    protected array $conditionClasses = [];
112
113
    /**
114
     * @var ExpressionBuilderInterface[]|string[] maps expression class to expression builder class.
115
     * For example:
116
     *
117
     * ```php
118
     * [
119
     *    Expression::class => ExpressionBuilder::class
120
     * ]
121
     * ```
122
     * This property is mainly used by {@see buildExpression()} to build SQL expressions form expression objects.
123
     * See default values in {@see defaultExpressionBuilders()} method.
124
     *
125
     * {@see setExpressionBuilders()}
126
     * {@see defaultExpressionBuilders()}
127
     */
128
    protected array $expressionBuilders = [];
129
    protected string $separator = ' ';
130
    private Connection $db;
131
132 1930
    public function __construct(Connection $db)
133
    {
134 1930
        $this->db = $db;
135 1930
        $this->expressionBuilders = $this->defaultExpressionBuilders();
136 1930
        $this->conditionClasses = $this->defaultConditionClasses();
137 1930
    }
138
139
    /**
140
     * Contains array of default condition classes. Extend this method, if you want to change default condition classes
141
     * for the query builder.
142
     *
143
     * @return array
144
     *
145
     * See {@see conditionClasses} docs for details.
146
     */
147 1930
    protected function defaultConditionClasses(): array
148
    {
149
        return [
150 1930
            'NOT' => Conditions\NotCondition::class,
151
            'AND' => Conditions\AndCondition::class,
152
            'OR' => Conditions\OrCondition::class,
153
            'BETWEEN' => Conditions\BetweenCondition::class,
154
            'NOT BETWEEN' => Conditions\BetweenCondition::class,
155
            'IN' => Conditions\InCondition::class,
156
            'NOT IN' => Conditions\InCondition::class,
157
            'LIKE' => Conditions\LikeCondition::class,
158
            'NOT LIKE' => Conditions\LikeCondition::class,
159
            'OR LIKE' => Conditions\LikeCondition::class,
160
            'OR NOT LIKE' => Conditions\LikeCondition::class,
161
            'EXISTS' => Conditions\ExistsCondition::class,
162
            'NOT EXISTS' => Conditions\ExistsCondition::class,
163
        ];
164
    }
165
166
    /**
167
     * Contains array of default expression builders. Extend this method and override it, if you want to change default
168
     * expression builders for this query builder.
169
     *
170
     * @return array
171
     *
172
     * See {@see expressionBuilders} docs for details.
173
     */
174 1930
    protected function defaultExpressionBuilders(): array
175
    {
176
        return [
177 1930
            Query::class => QueryExpressionBuilder::class,
178
            PdoValue::class => PdoValueBuilder::class,
179
            Expression::class => ExpressionBuilder::class,
180
            Conditions\ConjunctionCondition::class => Conditions\ConjunctionConditionBuilder::class,
181
            Conditions\NotCondition::class => Conditions\NotConditionBuilder::class,
182
            Conditions\AndCondition::class => Conditions\ConjunctionConditionBuilder::class,
183
            Conditions\OrCondition::class => Conditions\ConjunctionConditionBuilder::class,
184
            Conditions\BetweenCondition::class => Conditions\BetweenConditionBuilder::class,
185
            Conditions\InCondition::class => Conditions\InConditionBuilder::class,
186
            Conditions\LikeCondition::class => Conditions\LikeConditionBuilder::class,
187
            Conditions\ExistsCondition::class => Conditions\ExistsConditionBuilder::class,
188
            Conditions\SimpleCondition::class => Conditions\SimpleConditionBuilder::class,
189
            Conditions\HashCondition::class => Conditions\HashConditionBuilder::class,
190
            Conditions\BetweenColumnsCondition::class => Conditions\BetweenColumnsConditionBuilder::class,
191
        ];
192
    }
193
194
    /**
195
     * Setter for {@see expressionBuilders property.
196
     *
197
     * @param string[] $builders array of builders that should be merged with the pre-defined ones in property.
198
     *
199
     * See {@see expressionBuilders} docs for details.
200
     */
201
    public function setExpressionBuilders(array $builders): void
202
    {
203
        $this->expressionBuilders = array_merge($this->expressionBuilders, $builders);
204
    }
205
206
    /**
207
     * Setter for {@see conditionClasses} property.
208
     *
209
     * @param string[] $classes map of condition aliases to condition classes. For example:
210
     *
211
     * ```php
212
     * ['LIKE' => \Yiisoft\Db\Condition\LikeCondition::class]
213
     * ```
214
     *
215
     * See {@see conditionClasses} docs for details.
216
     */
217
    public function setConditionClasses(array $classes): void
218
    {
219
        $this->conditionClasses = array_merge($this->conditionClasses, $classes);
220
    }
221
222
    /**
223
     * Generates a SELECT SQL statement from a {@see Query} object.
224
     *
225
     * @param Query $query the {@see Query} object from which the SQL statement will be generated.
226
     * @param array $params the parameters to be bound to the generated SQL statement. These parameters will be included
227
     * in the result with the additional parameters generated during the query building process.
228
     *
229
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException
230
     *
231
     * @return array the generated SQL statement (the first array element) and the corresponding parameters to be bound
232
     * to the SQL statement (the second array element). The parameters returned include those provided in `$params`.
233
     */
234 1219
    public function build(Query $query, array $params = []): array
235
    {
236 1219
        $query = $query->prepare($this);
237
238 1219
        $params = empty($params) ? $query->getParams() : array_merge($params, $query->getParams());
239
240
        $clauses = [
241 1219
            $this->buildSelect($query->getSelect(), $params, $query->getDistinct(), $query->getSelectOption()),
242 1219
            $this->buildFrom($query->getFrom(), $params),
243 1219
            $this->buildJoin($query->getJoin(), $params),
244 1219
            $this->buildWhere($query->getWhere(), $params),
245 1219
            $this->buildGroupBy($query->getGroupBy(), $params),
246 1219
            $this->buildHaving($query->getHaving(), $params),
247
        ];
248
249 1219
        $sql = implode($this->separator, array_filter($clauses));
250
251 1219
        $sql = $this->buildOrderByAndLimit($sql, $query->getOrderBy(), $query->getLimit(), $query->getOffset());
252
253 1219
        if (!empty($query->getOrderBy())) {
254 180
            foreach ($query->getOrderBy() as $expression) {
255 180
                if ($expression instanceof ExpressionInterface) {
256 4
                    $this->buildExpression($expression, $params);
257
                }
258
            }
259
        }
260
261 1219
        if (!empty($query->getGroupBy())) {
262 12
            foreach ($query->getGroupBy() as $expression) {
263 12
                if ($expression instanceof ExpressionInterface) {
264 4
                    $this->buildExpression($expression, $params);
265
                }
266
            }
267
        }
268
269 1219
        $union = $this->buildUnion($query->getUnion(), $params);
270
271 1219
        if ($union !== '') {
272 9
            $sql = "($sql){$this->separator}$union";
273
        }
274
275 1219
        $with = $this->buildWithQueries($query->getWithQueries(), $params);
276
277 1219
        if ($with !== '') {
278 8
            $sql = "$with{$this->separator}$sql";
279
        }
280
281 1219
        return [$sql, $params];
282
    }
283
284
    /**
285
     * Builds given $expression.
286
     *
287
     * @param ExpressionInterface $expression the expression to be built
288
     * @param array $params the parameters to be bound to the generated SQL statement. These parameters will be included
289
     * in the result with the additional parameters generated during the expression building process.
290
     *
291
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException when $expression building
292
     * is not supported by this QueryBuilder.
293
     *
294
     * @return string the SQL statement that will not be neither quoted nor encoded before passing to DBMS.
295
     *
296
     * {@see ExpressionInterface}
297
     * {@see ExpressionBuilderInterface}
298
     * {@see expressionBuilders}
299
     */
300 1368
    public function buildExpression(ExpressionInterface $expression, array &$params = []): string
301
    {
302 1368
        $builder = $this->getExpressionBuilder($expression);
303
304 1368
        return (string) $builder->build($expression, $params);
305
    }
306
307
    /**
308
     * Gets object of {@see ExpressionBuilderInterface} that is suitable for $expression.
309
     *
310
     * Uses {@see expressionBuilders} array to find a suitable builder class.
311
     *
312
     * @param ExpressionInterface $expression
313
     *
314
     * @throws InvalidArgumentException when $expression building is not supported by this QueryBuilder.
315
     *
316
     * @return ExpressionBuilderInterface|QueryBuilder|string
317
     *
318
     * {@see expressionBuilders}
319
     */
320 1368
    public function getExpressionBuilder(ExpressionInterface $expression)
321
    {
322 1368
        $className = get_class($expression);
323
324 1368
        if (!isset($this->expressionBuilders[$className])) {
325
            foreach (array_reverse($this->expressionBuilders) as $expressionClass => $builderClass) {
326
                if (is_subclass_of($expression, $expressionClass)) {
327
                    $this->expressionBuilders[$className] = $builderClass;
328
                    break;
329
                }
330
            }
331
332
            if (!isset($this->expressionBuilders[$className])) {
333
                throw new InvalidArgumentException(
334
                    'Expression of class ' . $className . ' can not be built in ' . static::class
335
                );
336
            }
337
        }
338
339 1368
        if ($this->expressionBuilders[$className] === __CLASS__) {
340
            return $this;
341
        }
342
343 1368
        if (!is_object($this->expressionBuilders[$className])) {
0 ignored issues
show
introduced by
The condition is_object($this->expressionBuilders[$className]) is always false.
Loading history...
344 1368
            $this->expressionBuilders[$className] = new $this->expressionBuilders[$className]($this);
345
        }
346
347 1368
        return $this->expressionBuilders[$className];
348
    }
349
350
    /**
351
     * Creates an INSERT SQL statement.
352
     *
353
     * For example,.
354
     *
355
     * ```php
356
     * $sql = $queryBuilder->insert('user', [
357
     *     'name' => 'Sam',
358
     *     'age' => 30,
359
     * ], $params);
360
     * ```
361
     *
362
     * The method will properly escape the table and column names.
363
     *
364
     * @param string $table the table that new rows will be inserted into.
365
     * @param array|Query $columns the column data (name => value) to be inserted into the table or instance of
366
     * {@see Query} to perform INSERT INTO ... SELECT SQL statement. Passing of {@see Query}.
367
     * @param array $params the binding parameters that will be generated by this method. They should be bound to the
368
     * DB command later.
369
     *
370
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException
371
     *
372
     * @return string the INSERT SQL.
373
     */
374 197
    public function insert(string $table, $columns, array &$params = []): string
375
    {
376 197
        [$names, $placeholders, $values, $params] = $this->prepareInsertValues($table, $columns, $params);
377
378 185
        return 'INSERT INTO ' . $this->db->quoteTableName($table)
379 185
            . (!empty($names) ? ' (' . implode(', ', $names) . ')' : '')
380 185
            . (!empty($placeholders) ? ' VALUES (' . implode(', ', $placeholders) . ')' : $values);
381
    }
382
383
    /**
384
     * Prepares a `VALUES` part for an `INSERT` SQL statement.
385
     *
386
     * @param string $table the table that new rows will be inserted into.
387
     * @param array|Query $columns the column data (name => value) to be inserted into the table or instance of
388
     * {@see Query} to perform INSERT INTO ... SELECT SQL statement.
389
     * @param array $params the binding parameters that will be generated by this method.
390
     * They should be bound to the DB command later.
391
     *
392
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException
393
     *
394
     * @return array array of column names, placeholders, values and params.
395
     */
396 281
    protected function prepareInsertValues(string $table, $columns, array $params = []): array
397
    {
398 281
        $schema = $this->db->getSchema();
399 281
        $tableSchema = $schema->getTableSchema($table);
400 281
        $columnSchemas = $tableSchema !== null ? $tableSchema->getColumns() : [];
401 281
        $names = [];
402 281
        $placeholders = [];
403 281
        $values = ' DEFAULT VALUES';
404
405 281
        if ($columns instanceof Query) {
406 69
            [$names, $values, $params] = $this->prepareInsertSelectSubQuery($columns, $schema, $params);
407
        } else {
408 221
            foreach ($columns as $name => $value) {
409 216
                $names[] = $schema->quoteColumnName($name);
410 216
                $value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
411
412 216
                if ($value instanceof ExpressionInterface) {
413 43
                    $placeholders[] = $this->buildExpression($value, $params);
414 210
                } elseif ($value instanceof Query) {
415
                    [$sql, $params] = $this->build($value, $params);
416
                    $placeholders[] = "($sql)";
417
                } else {
418 210
                    $placeholders[] = $this->bindParam($value, $params);
419
                }
420
            }
421
        }
422
423 266
        return [$names, $placeholders, $values, $params];
424
    }
425
426
    /**
427
     * Prepare select-subquery and field names for INSERT INTO ... SELECT SQL statement.
428
     *
429
     * @param Query $columns Object, which represents select query.
430
     * @param Schema $schema Schema object to quote column name.
431
     * @param array $params the parameters to be bound to the generated SQL statement. These parameters will be included
432
     * in the result with the additional parameters generated during the query building process.
433
     *
434
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException
435
     *
436
     * @return array array of column names, values and params.
437
     */
438 69
    protected function prepareInsertSelectSubQuery(Query $columns, Schema $schema, array $params = []): array
439
    {
440
        if (
441 69
            !is_array($columns->getSelect())
0 ignored issues
show
introduced by
The condition is_array($columns->getSelect()) is always true.
Loading history...
442 69
            || empty($columns->getSelect())
443 69
            || in_array('*', $columns->getSelect(), true)
444
        ) {
445 15
            throw new InvalidArgumentException('Expected select query object with enumerated (named) parameters');
446
        }
447
448 54
        [$values, $params] = $this->build($columns, $params);
449
450 54
        $names = [];
451 54
        $values = ' ' . $values;
452
453 54
        foreach ($columns->getSelect() as $title => $field) {
454 54
            if (is_string($title)) {
455 54
                $names[] = $schema->quoteColumnName($title);
456
            } elseif (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_.]+)$/', $field, $matches)) {
457
                $names[] = $schema->quoteColumnName($matches[2]);
458
            } else {
459
                $names[] = $schema->quoteColumnName($field);
460
            }
461
        }
462
463 54
        return [$names, $values, $params];
464
    }
465
466
    /**
467
     * Generates a batch INSERT SQL statement.
468
     *
469
     * For example,
470
     *
471
     * ```php
472
     * $sql = $queryBuilder->batchInsert('user', ['name', 'age'], [
473
     *     ['Tom', 30],
474
     *     ['Jane', 20],
475
     *     ['Linda', 25],
476
     * ]);
477
     * ```
478
     *
479
     * Note that the values in each row must match the corresponding column names.
480
     *
481
     * The method will properly escape the column names, and quote the values to be inserted.
482
     *
483
     * @param string $table the table that new rows will be inserted into.
484
     * @param array $columns the column names.
485
     * @param array|Generator $rows the rows to be batch inserted into the table.
486
     * @param array $params the binding parameters. This parameter exists.
487
     *
488
     * @throws Exception|InvalidArgumentException
489
     *
490
     * @return string the batch INSERT SQL statement.
491
     */
492 40
    public function batchInsert(string $table, array $columns, $rows, array &$params = []): string
493
    {
494 40
        if (empty($rows)) {
495 4
            return '';
496
        }
497
498 38
        $schema = $this->db->getSchema();
499
500
501 38
        if (($tableSchema = $schema->getTableSchema($table)) !== null) {
502 38
            $columnSchemas = $tableSchema->getColumns();
503
        } else {
504
            $columnSchemas = [];
505
        }
506
507 38
        $values = [];
508
509 38
        foreach ($rows as $row) {
510 35
            $vs = [];
511 35
            foreach ($row as $i => $value) {
512 35
                if (isset($columns[$i], $columnSchemas[$columns[$i]])) {
513 26
                    $value = $columnSchemas[$columns[$i]]->dbTypecast($value);
514
                }
515 35
                if (is_string($value)) {
516 23
                    $value = $schema->quoteValue($value);
517 21
                } elseif (is_float($value)) {
518
                    /* ensure type cast always has . as decimal separator in all locales */
519 2
                    $value = NumericHelper::normalize((string) $value);
520 21
                } elseif ($value === false) {
521 7
                    $value = 0;
522 21
                } elseif ($value === null) {
523 12
                    $value = 'NULL';
524 13
                } elseif ($value instanceof ExpressionInterface) {
525 9
                    $value = $this->buildExpression($value, $params);
526
                }
527 35
                $vs[] = $value;
528
            }
529 35
            $values[] = '(' . implode(', ', $vs) . ')';
530
        }
531
532 38
        if (empty($values)) {
533 3
            return '';
534
        }
535
536 35
        foreach ($columns as $i => $name) {
537 32
            $columns[$i] = $schema->quoteColumnName($name);
538
        }
539
540 35
        return 'INSERT INTO ' . $schema->quoteTableName($table)
541 35
            . ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values);
542
    }
543
544
    /**
545
     * Creates an SQL statement to insert rows into a database table if they do not already exist (matching unique
546
     * constraints), or update them if they do.
547
     *
548
     * For example,
549
     *
550
     * ```php
551
     * $sql = $queryBuilder->upsert('pages', [
552
     *     'name' => 'Front page',
553
     *     'url' => 'http://example.com/', // url is unique
554
     *     'visits' => 0,
555
     * ], [
556
     *     'visits' => new \Yiisoft\Db\Expression('visits + 1'),
557
     * ], $params);
558
     * ```
559
     *
560
     * The method will properly escape the table and column names.
561
     *
562
     * @param string $table the table that new rows will be inserted into/updated in.
563
     * @param array|Query $insertColumns the column data (name => value) to be inserted into the table or instance
564
     * of {@see Query} to perform `INSERT INTO ... SELECT` SQL statement.
565
     * @param array|bool $updateColumns the column data (name => value) to be updated if they already exist.
566
     * If `true` is passed, the column data will be updated to match the insert column data.
567
     * If `false` is passed, no update will be performed if the column data already exists.
568
     * @param array $params the binding parameters that will be generated by this method. They should be bound to the DB
569
     * command later.
570
     *
571
     * @throws Exception|NotSupportedException if this is not supported by the underlying DBMS.
572
     *
573
     * @return string the resulting SQL.
574
     */
575
    public function upsert(string $table, $insertColumns, $updateColumns, array &$params): string
576
    {
577
        throw new NotSupportedException($this->db->getDriverName() . ' does not support upsert statements.');
578
    }
579
580
    /**
581
     * @param string $table
582
     * @param array|Query $insertColumns
583
     * @param array|bool $updateColumns
584
     * @param Constraint[] $constraints this parameter recieves a matched constraint list.
585
     * The constraints will be unique by their column names.
586
     *
587
     * @throws Exception|JsonException
588
     *
589
     * @return array
590
     */
591 89
    protected function prepareUpsertColumns(string $table, $insertColumns, $updateColumns, array &$constraints = []): array
592
    {
593 89
        if ($insertColumns instanceof Query) {
594 40
            [$insertNames] = $this->prepareInsertSelectSubQuery($insertColumns, $this->db->getSchema());
595
        } else {
596
            /** @psalm-suppress UndefinedMethod */
597 49
            $insertNames = array_map([$this->db, 'quoteColumnName'], array_keys($insertColumns));
598
        }
599
600 89
        $uniqueNames = $this->getTableUniqueColumnNames($table, $insertNames, $constraints);
601
602
        /** @psalm-suppress UndefinedMethod */
603 89
        $uniqueNames = array_map([$this->db, 'quoteColumnName'], $uniqueNames);
604
605 89
        if ($updateColumns !== true) {
606 64
            return [$uniqueNames, $insertNames, null];
607
        }
608
609 25
        return [$uniqueNames, $insertNames, array_diff($insertNames, $uniqueNames)];
610
    }
611
612
    /**
613
     * Returns all column names belonging to constraints enforcing uniqueness (`PRIMARY KEY`, `UNIQUE INDEX`, etc.)
614
     * for the named table removing constraints which did not cover the specified column list.
615
     *
616
     * The column list will be unique by column names.
617
     *
618
     * @param string $name table name. The table name may contain schema name if any. Do not quote the table name.
619
     * @param string[] $columns source column list.
620
     * @param Constraint[] $constraints this parameter optionally recieves a matched constraint list. The constraints
621
     * will be unique by their column names.
622
     *
623
     * @throws JsonException
624
     *
625
     * @return array column list.
626
     */
627 89
    private function getTableUniqueColumnNames(string $name, array $columns, array &$constraints = []): array
628
    {
629 89
        $schema = $this->db->getSchema();
630
631 89
        if (!$schema instanceof ConstraintFinderInterface) {
632
            return [];
633
        }
634
635 89
        $constraints = [];
636 89
        $primaryKey = $schema->getTablePrimaryKey($name);
637
638 89
        if ($primaryKey !== null) {
639 88
            $constraints[] = $primaryKey;
640
        }
641
642 89
        foreach ($schema->getTableIndexes($name) as $constraint) {
643 88
            if ($constraint->isUnique()) {
644 88
                $constraints[] = $constraint;
645
            }
646
        }
647
648 89
        $constraints = array_merge($constraints, $schema->getTableUniques($name));
649
650
        /** Remove duplicates */
651 89
        $constraints = array_combine(
652 89
            array_map(
653 89
                static function ($constraint) {
654 89
                    $columns = $constraint->getColumnNames();
655 89
                    sort($columns, SORT_STRING);
656
657 89
                    return json_encode($columns, JSON_THROW_ON_ERROR);
658
                },
659 89
                $constraints
660
            ),
661 89
            $constraints
662
        );
663
664 89
        $columnNames = [];
665
666
        /** Remove all constraints which do not cover the specified column list */
667 89
        $constraints = array_values(
668 89
            array_filter(
669 89
                $constraints,
0 ignored issues
show
Bug introduced by
It seems like $constraints can also be of type false; however, parameter $input of array_filter() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

669
                /** @scrutinizer ignore-type */ $constraints,
Loading history...
670 89
                static function ($constraint) use ($schema, $columns, &$columnNames) {
671
                    /** @psalm-suppress UndefinedClass, UndefinedMethod */
672 89
                    $constraintColumnNames = array_map([$schema, 'quoteColumnName'], $constraint->getColumnNames());
673 89
                    $result = !array_diff($constraintColumnNames, $columns);
674
675 89
                    if ($result) {
676 74
                        $columnNames = array_merge($columnNames, $constraintColumnNames);
677
                    }
678
679 89
                    return $result;
680 89
                }
681
            )
682
        );
683
684 89
        return array_unique($columnNames);
685
    }
686
687
    /**
688
     * Creates an UPDATE SQL statement.
689
     *
690
     * For example,
691
     *
692
     * ```php
693
     * $params = [];
694
     * $sql = $queryBuilder->update('user', ['status' => 1], 'age > 30', $params);
695
     * ```
696
     *
697
     * The method will properly escape the table and column names.
698
     *
699
     * @param string $table the table to be updated.
700
     * @param array $columns the column data (name => value) to be updated.
701
     * @param array|string $condition the condition that will be put in the WHERE part. Please refer to
702
     * {@see Query::where()} on how to specify condition.
703
     * @param array $params the binding parameters that will be modified by this method so that they can be bound to the
704
     * DB command later.
705
     *
706
     * @throws Exception|InvalidArgumentException
707
     *
708
     * @return string the UPDATE SQL.
709
     */
710 94
    public function update(string $table, array $columns, $condition, array &$params = []): string
711
    {
712 94
        [$lines, $params] = $this->prepareUpdateSets($table, $columns, $params);
713 94
        $sql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $lines);
714 94
        $where = $this->buildWhere($condition, $params);
715
716 94
        return ($where === '') ? $sql : ($sql . ' ' . $where);
717
    }
718
719
    /**
720
     * Prepares a `SET` parts for an `UPDATE` SQL statement.
721
     *
722
     * @param string $table the table to be updated.
723
     * @param array $columns the column data (name => value) to be updated.
724
     * @param array $params the binding parameters that will be modified by this method so that they can be bound to the
725
     * DB command later.
726
     *
727
     * @throws Exception|InvalidArgumentException
728
     *
729
     * @return array an array `SET` parts for an `UPDATE` SQL statement (the first array element) and params (the second
730
     * array element).
731
     */
732 139
    protected function prepareUpdateSets(string $table, array $columns, array $params = []): array
733
    {
734 139
        $tableSchema = $this->db->getTableSchema($table);
735
736 139
        $columnSchemas = $tableSchema !== null ? $tableSchema->getColumns() : [];
737
738 139
        $sets = [];
739
740 139
        foreach ($columns as $name => $value) {
741 139
            $value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
742 139
            if ($value instanceof ExpressionInterface) {
743 69
                $placeholder = $this->buildExpression($value, $params);
744
            } else {
745 96
                $placeholder = $this->bindParam($value, $params);
746
            }
747
748 139
            $sets[] = $this->db->quoteColumnName($name) . '=' . $placeholder;
749
        }
750
751 139
        return [$sets, $params];
752
    }
753
754
    /**
755
     * Creates a DELETE SQL statement.
756
     *
757
     * For example,
758
     *
759
     * ```php
760
     * $sql = $queryBuilder->delete('user', 'status = 0');
761
     * ```
762
     *
763
     * The method will properly escape the table and column names.
764
     *
765
     * @param string $table the table where the data will be deleted from.
766
     * @param array|string $condition the condition that will be put in the WHERE part. Please refer to
767
     * {@see Query::where()} on how to specify condition.
768
     * @param array $params the binding parameters that will be modified by this method so that they can be bound to the
769
     * DB command later.
770
     *
771
     * @throws Exception|InvalidArgumentException
772
     *
773
     * @return string the DELETE SQL.
774
     */
775 41
    public function delete(string $table, $condition, array &$params): string
776
    {
777 41
        $sql = 'DELETE FROM ' . $this->db->quoteTableName($table);
778 41
        $where = $this->buildWhere($condition, $params);
779
780 41
        return ($where === '') ? $sql : ($sql . ' ' . $where);
781
    }
782
783
    /**
784
     * Builds a SQL statement for creating a new DB table.
785
     *
786
     * The columns in the new  table should be specified as name-definition pairs (e.g. 'name' => 'string'), where name
787
     * stands for a column name which will be properly quoted by the method, and definition stands for the column type
788
     * which can contain an abstract DB type.
789
     *
790
     * The {@see getColumnType()} method will be invoked to convert any abstract type into a physical one.
791
     *
792
     * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly inserted
793
     * into the generated SQL.
794
     *
795
     * For example,
796
     *
797
     * ```php
798
     * $sql = $queryBuilder->createTable('user', [
799
     *  'id' => 'pk',
800
     *  'name' => 'string',
801
     *  'age' => 'integer',
802
     * ]);
803
     * ```
804
     *
805
     * @param string $table the name of the table to be created. The name will be properly quoted by the method.
806
     * @param array $columns the columns (name => definition) in the new table.
807
     * @param string|null $options additional SQL fragment that will be appended to the generated SQL.
808
     *
809
     * @return string the SQL statement for creating a new DB table.
810
     */
811 59
    public function createTable(string $table, array $columns, ?string $options = null): string
812
    {
813 59
        $cols = [];
814 59
        foreach ($columns as $name => $type) {
815 59
            if (is_string($name)) {
816 59
                $cols[] = "\t" . $this->db->quoteColumnName($name) . ' ' . $this->getColumnType($type);
817
            } else {
818 5
                $cols[] = "\t" . $type;
819
            }
820
        }
821
822 59
        $sql = 'CREATE TABLE ' . $this->db->quoteTableName($table) . " (\n" . implode(",\n", $cols) . "\n)";
823
824 59
        return ($options === null) ? $sql : ($sql . ' ' . $options);
825
    }
826
827
    /**
828
     * Builds a SQL statement for renaming a DB table.
829
     *
830
     * @param string $oldName the table to be renamed. The name will be properly quoted by the method.
831
     * @param string $newName the new table name. The name will be properly quoted by the method.
832
     *
833
     * @return string the SQL statement for renaming a DB table.
834
     */
835 2
    public function renameTable(string $oldName, string $newName): string
836
    {
837 2
        return 'RENAME TABLE ' . $this->db->quoteTableName($oldName) . ' TO ' . $this->db->quoteTableName($newName);
838
    }
839
840
    /**
841
     * Builds a SQL statement for dropping a DB table.
842
     *
843
     * @param string $table the table to be dropped. The name will be properly quoted by the method.
844
     *
845
     * @return string the SQL statement for dropping a DB table.
846
     */
847 9
    public function dropTable(string $table): string
848
    {
849 9
        return 'DROP TABLE ' . $this->db->quoteTableName($table);
850
    }
851
852
    /**
853
     * Builds a SQL statement for adding a primary key constraint to an existing table.
854
     *
855
     * @param string $name the name of the primary key constraint.
856
     * @param string $table the table that the primary key constraint will be added to.
857
     * @param array|string $columns comma separated string or array of columns that the primary key will consist of.
858
     *
859
     * @return string the SQL statement for adding a primary key constraint to an existing table.
860
     */
861 11
    public function addPrimaryKey(string $name, string $table, $columns): string
862
    {
863 11
        if (is_string($columns)) {
864 8
            $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
865
        }
866
867 11
        foreach ($columns as $i => $col) {
868 11
            $columns[$i] = $this->db->quoteColumnName($col);
869
        }
870
871 11
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
872 11
            . $this->db->quoteColumnName($name) . ' PRIMARY KEY ('
873 11
            . implode(', ', $columns) . ')';
0 ignored issues
show
Bug introduced by
It seems like $columns can also be of type false; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

873
            . implode(', ', /** @scrutinizer ignore-type */ $columns) . ')';
Loading history...
874
    }
875
876
    /**
877
     * Builds a SQL statement for removing a primary key constraint to an existing table.
878
     *
879
     * @param string $name the name of the primary key constraint to be removed.
880
     * @param string $table the table that the primary key constraint will be removed from.
881
     *
882
     * @return string the SQL statement for removing a primary key constraint from an existing table.
883
     */
884 5
    public function dropPrimaryKey(string $name, string $table): string
885
    {
886 5
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
887 5
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
888
    }
889
890
    /**
891
     * Builds a SQL statement for truncating a DB table.
892
     *
893
     * @param string $table the table to be truncated. The name will be properly quoted by the method.
894
     *
895
     * @return string the SQL statement for truncating a DB table.
896
     */
897 3
    public function truncateTable(string $table): string
898
    {
899 3
        return 'TRUNCATE TABLE ' . $this->db->quoteTableName($table);
900
    }
901
902
    /**
903
     * Builds a SQL statement for adding a new DB column.
904
     *
905
     * @param string $table the table that the new column will be added to. The table name will be properly quoted by
906
     * the method.
907
     * @param string $column the name of the new column. The name will be properly quoted by the method.
908
     * @param string $type the column type. The {@see getColumnType()} method will be invoked to convert abstract column
909
     * type (if any) into the physical one. Anything that is not recognized as abstract type will be kept in the
910
     * generated SQL.
911
     * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become
912
     * 'varchar(255) not null'.
913
     *
914
     * @return string the SQL statement for adding a new column.
915
     */
916 2
    public function addColumn(string $table, string $column, string $type): string
917
    {
918 2
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
919 2
            . ' ADD ' . $this->db->quoteColumnName($column) . ' '
920 2
            . $this->getColumnType($type);
921
    }
922
923
    /**
924
     * Builds a SQL statement for dropping a DB column.
925
     *
926
     * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
927
     * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
928
     *
929
     * @return string the SQL statement for dropping a DB column.
930
     */
931
    public function dropColumn(string $table, string $column): string
932
    {
933
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
934
            . ' DROP COLUMN ' . $this->db->quoteColumnName($column);
935
    }
936
937
    /**
938
     * Builds a SQL statement for renaming a column.
939
     *
940
     * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
941
     * @param string $oldName the old name of the column. The name will be properly quoted by the method.
942
     * @param string $newName the new name of the column. The name will be properly quoted by the method.
943
     *
944
     * @return string the SQL statement for renaming a DB column.
945
     */
946
    public function renameColumn(string $table, string $oldName, string $newName): string
947
    {
948
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
949
            . ' RENAME COLUMN ' . $this->db->quoteColumnName($oldName)
950
            . ' TO ' . $this->db->quoteColumnName($newName);
951
    }
952
953
    /**
954
     * Builds a SQL statement for changing the definition of a column.
955
     *
956
     * @param string $table the table whose column is to be changed. The table name will be properly quoted by the
957
     * method.
958
     * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
959
     * @param string $type the new column type. The {@see getColumnType()} method will be invoked to convert abstract
960
     * column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept
961
     * in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null'
962
     * will become 'varchar(255) not null'.
963
     *
964
     * @return string the SQL statement for changing the definition of a column.
965
     */
966 1
    public function alterColumn(string $table, string $column, string $type): string
967
    {
968 1
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
969 1
            . $this->db->quoteColumnName($column) . ' '
970 1
            . $this->db->quoteColumnName($column) . ' '
971 1
            . $this->getColumnType($type);
972
    }
973
974
    /**
975
     * Builds a SQL statement for adding a foreign key constraint to an existing table. The method will properly quote
976
     * the table and column names.
977
     *
978
     * @param string $name the name of the foreign key constraint.
979
     * @param string $table the table that the foreign key constraint will be added to.
980
     * @param array|string $columns the name of the column to that the constraint will be added on. If there are
981
     * multiple columns, separate them with commas or use an array to represent them.
982
     * @param string $refTable the table that the foreign key references to.
983
     * @param array|string $refColumns the name of the column that the foreign key references to. If there are multiple
984
     * columns, separate them with commas or use an array to represent them.
985
     * @param string|null $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION,
986
     * SET DEFAULT, SET NULL.
987
     * @param string|null $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION,
988
     * SET DEFAULT, SET NULL.
989
     *
990
     * @throws Exception|InvalidArgumentException
991
     *
992
     * @return string the SQL statement for adding a foreign key constraint to an existing table.
993
     */
994 9
    public function addForeignKey(
995
        string $name,
996
        string $table,
997
        $columns,
998
        string $refTable,
999
        $refColumns,
1000
        ?string $delete = null,
1001
        ?string $update = null
1002
    ): string {
1003 9
        $sql = 'ALTER TABLE ' . $this->db->quoteTableName($table)
1004 9
            . ' ADD CONSTRAINT ' . $this->db->quoteColumnName($name)
1005 9
            . ' FOREIGN KEY (' . $this->buildColumns($columns) . ')'
1006 9
            . ' REFERENCES ' . $this->db->quoteTableName($refTable)
1007 9
            . ' (' . $this->buildColumns($refColumns) . ')';
1008
1009 9
        if ($delete !== null) {
1010 6
            $sql .= ' ON DELETE ' . $delete;
1011
        }
1012
1013 9
        if ($update !== null) {
1014 6
            $sql .= ' ON UPDATE ' . $update;
1015
        }
1016
1017 9
        return $sql;
1018
    }
1019
1020
    /**
1021
     * Builds a SQL statement for dropping a foreign key constraint.
1022
     *
1023
     * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by
1024
     * the method.
1025
     * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
1026
     *
1027
     * @return string the SQL statement for dropping a foreign key constraint.
1028
     */
1029 7
    public function dropForeignKey(string $name, string $table): string
1030
    {
1031 7
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
1032 7
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
1033
    }
1034
1035
    /**
1036
     * Builds a SQL statement for creating a new index.
1037
     *
1038
     * @param string $name the name of the index. The name will be properly quoted by the method.
1039
     * @param string $table the table that the new index will be created for. The table name will be properly quoted by
1040
     * the method.
1041
     * @param array|string $columns the column(s) that should be included in the index. If there are multiple columns,
1042
     * separate them with commas or use an array to represent them. Each column name will be properly quoted by the
1043
     * method, unless a parenthesis is found in the name.
1044
     * @param bool $unique whether to add UNIQUE constraint on the created index.
1045
     *
1046
     * @throws Exception|InvalidArgumentException
1047
     *
1048
     * @return string the SQL statement for creating a new index.
1049
     */
1050 11
    public function createIndex(string $name, string $table, $columns, bool $unique = false): string
1051
    {
1052 11
        return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
1053 11
            . $this->db->quoteTableName($name) . ' ON '
1054 11
            . $this->db->quoteTableName($table)
1055 11
            . ' (' . $this->buildColumns($columns) . ')';
1056
    }
1057
1058
    /**
1059
     * Builds a SQL statement for dropping an index.
1060
     *
1061
     * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
1062
     * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
1063
     *
1064
     * @return string the SQL statement for dropping an index.
1065
     */
1066 6
    public function dropIndex(string $name, string $table): string
1067
    {
1068 6
        return 'DROP INDEX ' . $this->db->quoteTableName($name) . ' ON ' . $this->db->quoteTableName($table);
1069
    }
1070
1071
    /**
1072
     * Creates a SQL command for adding an unique constraint to an existing table.
1073
     *
1074
     * @param string $name the name of the unique constraint. The name will be properly quoted by the method.
1075
     * @param string $table the table that the unique constraint will be added to. The name will be properly quoted by
1076
     * the method.
1077
     * @param array|string $columns the name of the column to that the constraint will be added on. If there are
1078
     * multiple columns, separate them with commas. The name will be properly quoted by the method.
1079
     *
1080
     * @return string the SQL statement for adding an unique constraint to an existing table.
1081
     */
1082 12
    public function addUnique(string $name, string $table, $columns): string
1083
    {
1084 12
        if (is_string($columns)) {
1085 8
            $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
1086
        }
1087 12
        foreach ($columns as $i => $col) {
1088 12
            $columns[$i] = $this->db->quoteColumnName($col);
1089
        }
1090
1091 12
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
1092 12
            . $this->db->quoteColumnName($name) . ' UNIQUE ('
1093 12
            . implode(', ', $columns) . ')';
0 ignored issues
show
Bug introduced by
It seems like $columns can also be of type false; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1093
            . implode(', ', /** @scrutinizer ignore-type */ $columns) . ')';
Loading history...
1094
    }
1095
1096
    /**
1097
     * Creates a SQL command for dropping an unique constraint.
1098
     *
1099
     * @param string $name the name of the unique constraint to be dropped. The name will be properly quoted by the
1100
     * method.
1101
     * @param string $table the table whose unique constraint is to be dropped. The name will be properly quoted by the
1102
     * method.
1103
     *
1104
     * @return string the SQL statement for dropping an unique constraint.
1105
     */
1106 6
    public function dropUnique(string $name, string $table): string
1107
    {
1108 6
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
1109 6
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
1110
    }
1111
1112
    /**
1113
     * Creates a SQL command for adding a check constraint to an existing table.
1114
     *
1115
     * @param string $name the name of the check constraint. The name will be properly quoted by the method.
1116
     * @param string $table the table that the check constraint will be added to. The name will be properly quoted by
1117
     * the method.
1118
     * @param string $expression the SQL of the `CHECK` constraint.
1119
     *
1120
     * @return string the SQL statement for adding a check constraint to an existing table.
1121
     */
1122 6
    public function addCheck(string $name, string $table, string $expression): string
1123
    {
1124 6
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
1125 6
            . $this->db->quoteColumnName($name) . ' CHECK (' . $this->db->quoteSql($expression) . ')';
1126
    }
1127
1128
    /**
1129
     * Creates a SQL command for dropping a check constraint.
1130
     *
1131
     * @param string $name the name of the check constraint to be dropped. The name will be properly quoted by the
1132
     * method.
1133
     * @param string $table the table whose check constraint is to be dropped. The name will be properly quoted by the
1134
     * method.
1135
     *
1136
     * @return string the SQL statement for dropping a check constraint.
1137
     */
1138 6
    public function dropCheck(string $name, string $table): string
1139
    {
1140 6
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
1141 6
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
1142
    }
1143
1144
    /**
1145
     * Creates a SQL command for adding a default value constraint to an existing table.
1146
     *
1147
     * @param string $name the name of the default value constraint.
1148
     * The name will be properly quoted by the method.
1149
     * @param string $table the table that the default value constraint will be added to.
1150
     * The name will be properly quoted by the method.
1151
     * @param string $column the name of the column to that the constraint will be added on.
1152
     * The name will be properly quoted by the method.
1153
     * @param mixed $value default value.
1154
     *
1155
     * @throws Exception|NotSupportedException if this is not supported by the underlying DBMS.
1156
     *
1157
     * @return string the SQL statement for adding a default value constraint to an existing table.
1158
     */
1159
    public function addDefaultValue(string $name, string $table, string $column, $value): string
1160
    {
1161
        throw new NotSupportedException(
1162
            $this->db->getDriverName() . ' does not support adding default value constraints.'
1163
        );
1164
    }
1165
1166
    /**
1167
     * Creates a SQL command for dropping a default value constraint.
1168
     *
1169
     * @param string $name the name of the default value constraint to be dropped.
1170
     * The name will be properly quoted by the method.
1171
     * @param string $table the table whose default value constraint is to be dropped.
1172
     * The name will be properly quoted by the method.
1173
     *
1174
     * @throws Exception|NotSupportedException if this is not supported by the underlying DBMS.
1175
     *
1176
     * @return string the SQL statement for dropping a default value constraint.
1177
     */
1178
    public function dropDefaultValue(string $name, string $table): string
1179
    {
1180
        throw new NotSupportedException(
1181
            $this->db->getDriverName() . ' does not support dropping default value constraints.'
1182
        );
1183
    }
1184
1185
    /**
1186
     * Creates a SQL statement for resetting the sequence value of a table's primary key.
1187
     *
1188
     * The sequence will be reset such that the primary key of the next new row inserted will have the specified value
1189
     * or 1.
1190
     *
1191
     * @param string $tableName the name of the table whose primary key sequence will be reset.
1192
     * @param array|string|null $value the value for the primary key of the next new row inserted. If this is not set,
1193
     * the next new row's primary key will have a value 1.
1194
     *
1195
     * @throws Exception|NotSupportedException if this is not supported by the underlying DBMS.
1196
     *
1197
     * @return string the SQL statement for resetting sequence.
1198
     */
1199
    public function resetSequence(string $tableName, $value = null): string
0 ignored issues
show
Unused Code introduced by
The parameter $tableName is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

1199
    public function resetSequence(/** @scrutinizer ignore-unused */ string $tableName, $value = null): string

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1200
    {
1201
        throw new NotSupportedException($this->db->getDriverName() . ' does not support resetting sequence.');
1202
    }
1203
1204
    /**
1205
     * Builds a SQL statement for enabling or disabling integrity check.
1206
     *
1207
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
1208
     * @param string $table the table name. Defaults to empty string, meaning that no table will be changed.
1209
     * @param bool $check whether to turn on or off the integrity check.
1210
     *
1211
     * @throws Exception|NotSupportedException if this is not supported by the underlying DBMS.
1212
     *
1213
     * @return string the SQL statement for checking integrity.
1214
     */
1215
    public function checkIntegrity(string $schema = '', string $table = '', bool $check = true): string
0 ignored issues
show
Unused Code introduced by
The parameter $check is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

1215
    public function checkIntegrity(string $schema = '', string $table = '', /** @scrutinizer ignore-unused */ bool $check = true): string

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1216
    {
1217
        throw new NotSupportedException(
1218
            $this->db->getDriverName() . ' does not support enabling/disabling integrity check.'
1219
        );
1220
    }
1221
1222
    /**
1223
     * Builds a SQL command for adding comment to column.
1224
     *
1225
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the
1226
     * method.
1227
     * @param string $column the name of the column to be commented. The column name will be properly quoted by the
1228
     * method.
1229
     * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
1230
     *
1231
     * @return string the SQL statement for adding comment on column.
1232
     */
1233 3
    public function addCommentOnColumn(string $table, string $column, string $comment): string
1234
    {
1235 3
        return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column)
1236 3
            . ' IS ' . $this->db->quoteValue($comment);
1237
    }
1238
1239
    /**
1240
     * Builds a SQL command for adding comment to table.
1241
     *
1242
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the
1243
     * method.
1244
     * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
1245
     *
1246
     * @return string the SQL statement for adding comment on table.
1247
     */
1248 2
    public function addCommentOnTable(string $table, string $comment): string
1249
    {
1250 2
        return 'COMMENT ON TABLE ' . $this->db->quoteTableName($table) . ' IS ' . $this->db->quoteValue($comment);
1251
    }
1252
1253
    /**
1254
     * Builds a SQL command for adding comment to column.
1255
     *
1256
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the
1257
     * method.
1258
     * @param string $column the name of the column to be commented. The column name will be properly quoted by the
1259
     * method.
1260
     *
1261
     * @return string the SQL statement for adding comment on column.
1262
     */
1263 1
    public function dropCommentFromColumn(string $table, string $column): string
1264
    {
1265 1
        return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column)
1266 1
            . ' IS NULL';
1267
    }
1268
1269
    /**
1270
     * Builds a SQL command for adding comment to table.
1271
     *
1272
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the
1273
     * method.
1274
     *
1275
     * @return string the SQL statement for adding comment on column.
1276
     */
1277 1
    public function dropCommentFromTable(string $table): string
1278
    {
1279 1
        return 'COMMENT ON TABLE ' . $this->db->quoteTableName($table) . ' IS NULL';
1280
    }
1281
1282
    /**
1283
     * Creates a SQL View.
1284
     *
1285
     * @param string $viewName the name of the view to be created.
1286
     * @param Query|string $subQuery the select statement which defines the view.
1287
     *
1288
     * This can be either a string or a {@see Query} object.
1289
     *
1290
     * @throws Exception|InvalidConfigException|NotSupportedException
1291
     *
1292
     * @return string the `CREATE VIEW` SQL statement.
1293
     */
1294 5
    public function createView(string $viewName, $subQuery): string
1295
    {
1296 5
        if ($subQuery instanceof Query) {
1297 5
            [$rawQuery, $params] = $this->build($subQuery);
1298 5
            array_walk(
1299
                $params,
1300 5
                function (&$param) {
1301 5
                    $param = $this->db->quoteValue($param);
1302 5
                }
1303
            );
1304 5
            $subQuery = strtr($rawQuery, $params);
1305
        }
1306
1307 5
        return 'CREATE VIEW ' . $this->db->quoteTableName($viewName) . ' AS ' . $subQuery;
1308
    }
1309
1310
    /**
1311
     * Drops a SQL View.
1312
     *
1313
     * @param string $viewName the name of the view to be dropped.
1314
     *
1315
     * @return string the `DROP VIEW` SQL statement.
1316
     */
1317 5
    public function dropView(string $viewName): string
1318
    {
1319 5
        return 'DROP VIEW ' . $this->db->quoteTableName($viewName);
1320
    }
1321
1322
    /**
1323
     * Converts an abstract column type into a physical column type.
1324
     *
1325
     * The conversion is done using the type map specified in {@see typeMap}.
1326
     * The following abstract column types are supported (using MySQL as an example to explain the corresponding
1327
     * physical types):
1328
     *
1329
     * - `pk`: an auto-incremental primary key type, will be converted into "int(11) NOT NULL AUTO_INCREMENT PRIMARY
1330
     *    KEY"
1331
     * - `bigpk`: an auto-incremental primary key type, will be converted into "bigint(20) NOT NULL AUTO_INCREMENT
1332
     *    PRIMARY KEY"
1333
     * - `upk`: an unsigned auto-incremental primary key type, will be converted into "int(10) UNSIGNED NOT NULL
1334
     *    AUTO_INCREMENT PRIMARY KEY"
1335
     * - `char`: char type, will be converted into "char(1)"
1336
     * - `string`: string type, will be converted into "varchar(255)"
1337
     * - `text`: a long string type, will be converted into "text"
1338
     * - `smallint`: a small integer type, will be converted into "smallint(6)"
1339
     * - `integer`: integer type, will be converted into "int(11)"
1340
     * - `bigint`: a big integer type, will be converted into "bigint(20)"
1341
     * - `boolean`: boolean type, will be converted into "tinyint(1)"
1342
     * - `float``: float number type, will be converted into "float"
1343
     * - `decimal`: decimal number type, will be converted into "decimal"
1344
     * - `datetime`: datetime type, will be converted into "datetime"
1345
     * - `timestamp`: timestamp type, will be converted into "timestamp"
1346
     * - `time`: time type, will be converted into "time"
1347
     * - `date`: date type, will be converted into "date"
1348
     * - `money`: money type, will be converted into "decimal(19,4)"
1349
     * - `binary`: binary data type, will be converted into "blob"
1350
     *
1351
     * If the abstract type contains two or more parts separated by spaces (e.g. "string NOT NULL"), then only the first
1352
     * part will be converted, and the rest of the parts will be appended to the converted result.
1353
     *
1354
     * For example, 'string NOT NULL' is converted to 'varchar(255) NOT NULL'.
1355
     *
1356
     * For some of the abstract types you can also specify a length or precision constraint by appending it in round
1357
     * brackets directly to the type.
1358
     *
1359
     * For example `string(32)` will be converted into "varchar(32)" on a MySQL database. If the underlying DBMS does
1360
     * not support these kind of constraints for a type it will be ignored.
1361
     *
1362
     * If a type cannot be found in {@see typeMap}, it will be returned without any change.
1363
     *
1364
     * @param ColumnSchemaBuilder|string $type abstract column type.
1365
     *
1366
     * @return string physical column type.
1367
     */
1368 65
    public function getColumnType($type): string
1369
    {
1370 65
        if ($type instanceof ColumnSchemaBuilder) {
1371 11
            $type = $type->__toString();
1372
        }
1373
1374 65
        if (isset($this->typeMap[$type])) {
1375 40
            return $this->typeMap[$type];
1376
        }
1377
1378 40
        if (preg_match('/^(\w+)\((.+?)\)(.*)$/', $type, $matches)) {
1379 20
            if (isset($this->typeMap[$matches[1]])) {
1380 17
                return preg_replace(
1381
                    '/\(.+\)/',
1382 17
                    '(' . $matches[2] . ')',
1383 17
                    $this->typeMap[$matches[1]]
1384 20
                ) . $matches[3];
1385
            }
1386 33
        } elseif (preg_match('/^(\w+)\s+/', $type, $matches)) {
1387 32
            if (isset($this->typeMap[$matches[1]])) {
1388 32
                return preg_replace('/^\w+/', $this->typeMap[$matches[1]], $type);
1389
            }
1390
        }
1391
1392 5
        return $type;
1393
    }
1394
1395
    /**
1396
     * @param array $columns
1397
     * @param array $params the binding parameters to be populated.
1398
     * @param bool|null $distinct
1399
     * @param string|null $selectOption
1400
     *
1401
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException
1402
     *
1403
     * @return string the SELECT clause built from {@see Query::$select}.
1404
     */
1405 1507
    public function buildSelect(
1406
        array $columns,
1407
        array &$params,
1408
        ?bool $distinct = false,
1409
        string $selectOption = null
1410
    ): string {
1411 1507
        $select = $distinct ? 'SELECT DISTINCT' : 'SELECT';
1412
1413 1507
        if ($selectOption !== null) {
1414
            $select .= ' ' . $selectOption;
1415
        }
1416
1417 1507
        if (empty($columns)) {
1418 1286
            return $select . ' *';
1419
        }
1420
1421 434
        foreach ($columns as $i => $column) {
1422 434
            if ($column instanceof ExpressionInterface) {
1423 73
                if (is_int($i)) {
1424 10
                    $columns[$i] = $this->buildExpression($column, $params);
1425
                } else {
1426 73
                    $columns[$i] = $this->buildExpression($column, $params) . ' AS ' . $this->db->quoteColumnName($i);
1427
                }
1428 416
            } elseif ($column instanceof Query) {
1429
                [$sql, $params] = $this->build($column, $params);
1430
                $columns[$i] = "($sql) AS " . $this->db->quoteColumnName($i);
1431 416
            } elseif (is_string($i) && $i !== $column) {
1432 19
                if (strpos($column, '(') === false) {
1433 14
                    $column = $this->db->quoteColumnName($column);
1434
                }
1435 19
                $columns[$i] = "$column AS " . $this->db->quoteColumnName($i);
1436 412
            } elseif (strpos($column, '(') === false) {
1437 317
                if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_.]+)$/', $column, $matches)) {
1438
                    $columns[$i] = $this->db->quoteColumnName(
1439
                        $matches[1]
1440
                    ) . ' AS ' . $this->db->quoteColumnName($matches[2]);
1441
                } else {
1442 317
                    $columns[$i] = $this->db->quoteColumnName($column);
1443
                }
1444
            }
1445
        }
1446
1447 434
        return $select . ' ' . implode(', ', $columns);
1448
    }
1449
1450
    /**
1451
     * @param array|null $tables
1452
     * @param array $params the binding parameters to be populated.
1453
     *
1454
     * @throws Exception|InvalidConfigException|NotSupportedException
1455
     *
1456
     * @return string the FROM clause built from {@see Query::$from}.
1457
     */
1458 1527
    public function buildFrom(?array $tables, array &$params): string
1459
    {
1460 1527
        if (empty($tables)) {
1461 668
            return '';
1462
        }
1463
1464 921
        $tables = $this->quoteTableNames($tables, $params);
1465
1466 921
        return 'FROM ' . implode(', ', $tables);
1467
    }
1468
1469
    /**
1470
     * @param array $joins
1471
     * @param array $params the binding parameters to be populated.
1472
     *
1473
     * @throws Exception if the $joins parameter is not in proper format.
1474
     *
1475
     * @return string the JOIN clause built from {@see Query::$join}.
1476
     */
1477 1507
    public function buildJoin(array $joins, array &$params): string
1478
    {
1479 1507
        if (empty($joins)) {
1480 1502
            return '';
1481
        }
1482
1483 110
        foreach ($joins as $i => $join) {
1484 110
            if (!is_array($join) || !isset($join[0], $join[1])) {
1485
                throw new Exception(
1486
                    'A join clause must be specified as an array of join type, join table, and optionally join '
1487
                    . 'condition.'
1488
                );
1489
            }
1490
1491
            /* 0:join type, 1:join table, 2:on-condition (optional) */
1492 110
            [$joinType, $table] = $join;
1493
1494 110
            $tables = $this->quoteTableNames((array) $table, $params);
1495 110
            $table = reset($tables);
1496 110
            $joins[$i] = "$joinType $table";
1497
1498 110
            if (isset($join[2])) {
1499 110
                $condition = $this->buildCondition($join[2], $params);
1500 110
                if ($condition !== '') {
1501 110
                    $joins[$i] .= ' ON ' . $condition;
1502
                }
1503
            }
1504
        }
1505
1506 110
        return implode($this->separator, $joins);
1507
    }
1508
1509
    /**
1510
     * Quotes table names passed.
1511
     *
1512
     * @param array $tables
1513
     * @param array $params
1514
     *
1515
     * @throws Exception|InvalidConfigException|NotSupportedException
1516
     *
1517
     * @return array
1518
     */
1519 921
    private function quoteTableNames(array $tables, array &$params): array
1520
    {
1521 921
        foreach ($tables as $i => $table) {
1522 921
            if ($table instanceof Query) {
1523 16
                [$sql, $params] = $this->build($table, $params);
1524 16
                $tables[$i] = "($sql) " . $this->db->quoteTableName((string) $i);
1525 921
            } elseif (is_string($i)) {
1526 58
                if (strpos($table, '(') === false) {
1527 40
                    $table = $this->db->quoteTableName($table);
1528
                }
1529 58
                $tables[$i] = "$table " . $this->db->quoteTableName($i);
1530 898
            } elseif (is_string($table)) {
1531 887
                if (strpos($table, '(') === false) {
1532 887
                    if ($tableWithAlias = $this->extractAlias($table)) { // with alias
1533 50
                        $tables[$i] = $this->db->quoteTableName($tableWithAlias[1]) . ' '
1534 50
                            . $this->db->quoteTableName($tableWithAlias[2]);
1535
                    } else {
1536 847
                        $tables[$i] = $this->db->quoteTableName($table);
1537
                    }
1538
                }
1539
            }
1540
        }
1541
1542 921
        return $tables;
1543
    }
1544
1545
    /**
1546
     * @param array|string $condition
1547
     * @param array $params the binding parameters to be populated.
1548
     *
1549
     * @throws InvalidArgumentException
1550
     *
1551
     * @return string the WHERE clause built from {@see Query::$where}.
1552
     */
1553 1533
    public function buildWhere($condition, array &$params = []): string
1554
    {
1555 1533
        $where = $this->buildCondition($condition, $params);
1556
1557 1533
        return ($where === '') ? '' : ('WHERE ' . $where);
1558
    }
1559
1560
    /**
1561
     * @param array $columns
1562
     * @param array $params the binding parameters to be populated
1563
     *
1564
     * @throws Exception|InvalidArgumentException
1565
     *
1566
     * @return string the GROUP BY clause
1567
     */
1568 1507
    public function buildGroupBy(array $columns, array &$params = []): string
1569
    {
1570 1507
        if (empty($columns)) {
1571 1497
            return '';
1572
        }
1573 15
        foreach ($columns as $i => $column) {
1574 15
            if ($column instanceof ExpressionInterface) {
1575 5
                $columns[$i] = $this->buildExpression($column);
1576 5
                $params = array_merge($params, $column->getParams());
0 ignored issues
show
Bug introduced by
The method getParams() does not exist on Yiisoft\Db\Expression\ExpressionInterface. It seems like you code against a sub-type of Yiisoft\Db\Expression\ExpressionInterface such as Yiisoft\Db\Expression\Expression or Yiisoft\Db\Query\Query. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1576
                $params = array_merge($params, $column->/** @scrutinizer ignore-call */ getParams());
Loading history...
1577 15
            } elseif (strpos($column, '(') === false) {
1578 15
                $columns[$i] = $this->db->quoteColumnName($column);
1579
            }
1580
        }
1581
1582 15
        return 'GROUP BY ' . implode(', ', $columns);
1583
    }
1584
1585
    /**
1586
     * @param array|string $condition
1587
     * @param array $params the binding parameters to be populated.
1588
     *
1589
     * @throws InvalidArgumentException
1590
     *
1591
     * @return string the HAVING clause built from {@see Query::$having}.
1592
     */
1593 1507
    public function buildHaving($condition, array &$params = []): string
1594
    {
1595 1507
        $having = $this->buildCondition($condition, $params);
1596
1597 1507
        return ($having === '') ? '' : ('HAVING ' . $having);
1598
    }
1599
1600
    /**
1601
     * Builds the ORDER BY and LIMIT/OFFSET clauses and appends them to the given SQL.
1602
     *
1603
     * @param string $sql the existing SQL (without ORDER BY/LIMIT/OFFSET).
1604
     * @param array $orderBy the order by columns. See {@see Query::orderBy} for more details on how to specify this
1605
     * parameter.
1606
     * @param int|object|null $limit the limit number. See {@see Query::limit} for more details.
1607
     * @param int|object|null $offset the offset number. See {@see Query::offset} for more details.
1608
     * @param array $params the binding parameters to be populated.
1609
     *
1610
     * @throws Exception|InvalidArgumentException
1611
     *
1612
     * @return string the SQL completed with ORDER BY/LIMIT/OFFSET (if any).
1613
     */
1614 940
    public function buildOrderByAndLimit(
1615
        string $sql,
1616
        array $orderBy,
1617
        $limit,
1618
        $offset,
1619
        array &$params = []
1620
    ): string {
1621 940
        $orderBy = $this->buildOrderBy($orderBy, $params);
1622 940
        if ($orderBy !== '') {
1623 138
            $sql .= $this->separator . $orderBy;
1624
        }
1625 940
        $limit = $this->buildLimit($limit, $offset);
1626 940
        if ($limit !== '') {
1627 36
            $sql .= $this->separator . $limit;
1628
        }
1629
1630 940
        return $sql;
1631
    }
1632
1633
    /**
1634
     * @param array $columns
1635
     * @param array $params the binding parameters to be populated
1636
     *
1637
     * @throws Exception|InvalidArgumentException
1638
     *
1639
     * @return string the ORDER BY clause built from {@see Query::$orderBy}.
1640
     */
1641 1519
    public function buildOrderBy(array $columns, array &$params = []): string
1642
    {
1643 1519
        if (empty($columns)) {
1644 1464
            return '';
1645
        }
1646
1647 229
        $orders = [];
1648
1649 229
        foreach ($columns as $name => $direction) {
1650 229
            if ($direction instanceof ExpressionInterface) {
1651 5
                $orders[] = $this->buildExpression($direction);
1652 5
                $params = array_merge($params, $direction->getParams());
1653
            } else {
1654 229
                $orders[] = $this->db->quoteColumnName($name) . ($direction === SORT_DESC ? ' DESC' : '');
1655
            }
1656
        }
1657
1658 229
        return 'ORDER BY ' . implode(', ', $orders);
1659
    }
1660
1661
    /**
1662
     * @param int|object|null $limit
1663
     * @param int|object|null $offset
1664
     *
1665
     * @return string the LIMIT and OFFSET clauses.
1666
     */
1667 346
    public function buildLimit($limit, $offset): string
1668
    {
1669 346
        $sql = '';
1670
1671 346
        if ($this->hasLimit($limit)) {
1672 11
            $sql = 'LIMIT ' . $limit;
0 ignored issues
show
Bug introduced by
Are you sure $limit of type integer|null|object can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1672
            $sql = 'LIMIT ' . /** @scrutinizer ignore-type */ $limit;
Loading history...
1673
        }
1674
1675 346
        if ($this->hasOffset($offset)) {
1676 3
            $sql .= ' OFFSET ' . $offset;
0 ignored issues
show
Bug introduced by
Are you sure $offset of type integer|null|object can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1676
            $sql .= ' OFFSET ' . /** @scrutinizer ignore-type */ $offset;
Loading history...
1677
        }
1678
1679 346
        return ltrim($sql);
1680
    }
1681
1682
    /**
1683
     * Checks to see if the given limit is effective.
1684
     *
1685
     * @param mixed $limit the given limit.
1686
     *
1687
     * @return bool whether the limit is effective.
1688
     */
1689 1216
    protected function hasLimit($limit): bool
1690
    {
1691 1216
        return ($limit instanceof ExpressionInterface) || ctype_digit((string) $limit);
1692
    }
1693
1694
    /**
1695
     * Checks to see if the given offset is effective.
1696
     *
1697
     * @param mixed $offset the given offset.
1698
     *
1699
     * @return bool whether the offset is effective.
1700
     */
1701 1216
    protected function hasOffset($offset): bool
1702
    {
1703 1216
        return ($offset instanceof ExpressionInterface) || (ctype_digit((string)$offset) && (string)$offset !== '0');
1704
    }
1705
1706
    /**
1707
     * @param array $unions
1708
     * @param array $params the binding parameters to be populated
1709
     *
1710
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException
1711
     *
1712
     * @return string the UNION clause built from {@see Query::$union}.
1713
     */
1714 1219
    public function buildUnion(array $unions, array &$params): string
1715
    {
1716 1219
        if (empty($unions)) {
1717 1219
            return '';
1718
        }
1719
1720 9
        $result = '';
1721
1722 9
        foreach ($unions as $i => $union) {
1723 9
            $query = $union['query'];
1724 9
            if ($query instanceof Query) {
1725 9
                [$unions[$i]['query'], $params] = $this->build($query, $params);
1726
            }
1727
1728 9
            $result .= 'UNION ' . ($union['all'] ? 'ALL ' : '') . '( ' . $unions[$i]['query'] . ' ) ';
1729
        }
1730
1731 9
        return trim($result);
1732
    }
1733
1734
    /**
1735
     * Processes columns and properly quotes them if necessary.
1736
     *
1737
     * It will join all columns into a string with comma as separators.
1738
     *
1739
     * @param array|string $columns the columns to be processed.
1740
     *
1741
     * @throws Exception|InvalidArgumentException
1742
     *
1743
     * @return string the processing result.
1744
     */
1745 41
    public function buildColumns($columns): string
1746
    {
1747 41
        if (!is_array($columns)) {
1748 31
            if (strpos($columns, '(') !== false) {
1749
                return $columns;
1750
            }
1751
1752 31
            $rawColumns = $columns;
1753 31
            $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
1754
1755 31
            if ($columns === false) {
1756
                throw new InvalidArgumentException("$rawColumns is not valid columns.");
1757
            }
1758
        }
1759 41
        foreach ($columns as $i => $column) {
1760 41
            if ($column instanceof ExpressionInterface) {
1761
                $columns[$i] = $this->buildExpression($column);
1762 41
            } elseif (strpos($column, '(') === false) {
1763 41
                $columns[$i] = $this->db->quoteColumnName($column);
1764
            }
1765
        }
1766
1767 41
        return implode(', ', $columns);
0 ignored issues
show
Bug introduced by
It seems like $columns can also be of type false and string; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1767
        return implode(', ', /** @scrutinizer ignore-type */ $columns);
Loading history...
1768
    }
1769
1770
    /**
1771
     * Parses the condition specification and generates the corresponding SQL expression.
1772
     *
1773
     * @param array|ExpressionInterface|string $condition the condition specification.
1774
     * Please refer to {@see Query::where()} on how to specify a condition.
1775
     * @param array $params the binding parameters to be populated.
1776
     *
1777
     * @throws InvalidArgumentException
1778
     *
1779
     * @return array|string the generated SQL expression.
1780
     */
1781 1537
    public function buildCondition($condition, array &$params = [])
1782
    {
1783 1537
        if (is_array($condition)) {
1784 1172
            if (empty($condition)) {
1785 5
                return '';
1786
            }
1787
1788 1172
            $condition = $this->createConditionFromArray($condition);
1789
        }
1790
1791 1537
        if ($condition instanceof ExpressionInterface) {
1792 1277
            return $this->buildExpression($condition, $params);
1793
        }
1794
1795 1513
        return (string) $condition;
1796
    }
1797
1798
    /**
1799
     * Transforms $condition defined in array format (as described in {@see Query::where()} to instance of
1800
     *
1801
     * @param array|string $condition.
1802
     *
1803
     * @throws InvalidArgumentException
1804
     *
1805
     * @return ConditionInterface
1806
     *
1807
     * {@see ConditionInterface|ConditionInterface} according to {@see conditionClasses} map.
1808
     */
1809 1172
    public function createConditionFromArray(array $condition): ConditionInterface
1810
    {
1811
        /** operator format: operator, operand 1, operand 2, ... */
1812 1172
        if (isset($condition[0])) {
1813 820
            $operator = strtoupper(array_shift($condition));
1814
1815 820
            $className = $this->conditionClasses[$operator] ?? SimpleCondition::class;
1816
1817
            /** @var ConditionInterface $className */
1818 820
            return $className::fromArrayDefinition($operator, $condition);
1819
        }
1820
1821
        /** hash format: 'column1' => 'value1', 'column2' => 'value2', ... */
1822 619
        return new HashCondition($condition);
1823
    }
1824
1825
    /**
1826
     * Creates a SELECT EXISTS() SQL statement.
1827
     *
1828
     * @param string $rawSql the subquery in a raw form to select from.
1829
     *
1830
     * @return string the SELECT EXISTS() SQL statement.
1831
     */
1832 9
    public function selectExists(string $rawSql): string
1833
    {
1834 9
        return 'SELECT EXISTS(' . $rawSql . ')';
1835
    }
1836
1837
    /**
1838
     * Helper method to add $value to $params array using {@see PARAM_PREFIX}.
1839
     *
1840
     * @param int|string|null $value
1841
     * @param array $params passed by reference.
1842
     *
1843
     * @return string the placeholder name in $params array.
1844
     */
1845 1185
    public function bindParam($value, array &$params = []): string
1846
    {
1847 1185
        $phName = self::PARAM_PREFIX . count($params);
1848 1185
        $params[$phName] = $value;
1849
1850 1185
        return $phName;
1851
    }
1852
1853
    /**
1854
     * Extracts table alias if there is one or returns false.
1855
     *
1856
     * @param $table
1857
     *
1858
     * @return array|bool
1859
     */
1860 887
    protected function extractAlias(string $table)
1861
    {
1862 887
        if (preg_match('/^(.*?)(?i:\s+as|)\s+([^ ]+)$/', $table, $matches)) {
1863 50
            return $matches;
1864
        }
1865
1866 847
        return false;
1867
    }
1868
1869
    public function buildWith($withs, &$params): string
1870
    {
1871
        if (empty($withs)) {
1872
            return '';
1873
        }
1874
1875
        $recursive = false;
1876
        $result = [];
1877
1878
        foreach ($withs as $i => $with) {
1879
            if ($with['recursive']) {
1880
                $recursive = true;
1881
            }
1882
1883
            $query = $with['query'];
1884
1885
            if ($query instanceof Query) {
1886
                [$with['query'], $params] = $this->build($query, $params);
1887
            }
1888
1889
            $result[] = $with['alias'] . ' AS (' . $with['query'] . ')';
1890
        }
1891
1892
        return 'WITH ' . ($recursive ? 'RECURSIVE ' : '') . implode(', ', $result);
1893
    }
1894
1895 1507
    public function buildWithQueries(array $withs, array &$params): string
1896
    {
1897 1507
        if (empty($withs)) {
1898 1507
            return '';
1899
        }
1900
1901 10
        $recursive = false;
1902 10
        $result = [];
1903
1904 10
        foreach ($withs as $i => $with) {
1905 10
            if ($with['recursive']) {
1906 5
                $recursive = true;
1907
            }
1908
1909 10
            $query = $with['query'];
1910 10
            if ($query instanceof Query) {
1911 10
                [$with['query'], $params] = $this->build($query, $params);
1912
            }
1913
1914 10
            $result[] = $with['alias'] . ' AS (' . $with['query'] . ')';
1915
        }
1916
1917 10
        return 'WITH ' . ($recursive ? 'RECURSIVE ' : '') . implode(', ', $result);
1918
    }
1919
1920 1331
    public function getDb(): Connection
1921
    {
1922 1331
        return $this->db;
1923
    }
1924
1925
    /**
1926
     * @param string the separator between different fragments of a SQL statement.
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Query\the was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
1927
     *
1928
     * Defaults to an empty space. This is mainly used by {@see build()} when generating a SQL statement.
1929
     */
1930 5
    public function setSeparator(string $separator): void
1931
    {
1932 5
        $this->separator = $separator;
1933 5
    }
1934
}
1935