Passed
Pull Request — master (#216)
by Wilmer
22:39 queued 07:40
created

QueryBuilder::defaultConditionClasses()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 16
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 14
nc 1
nop 0
dl 0
loc 16
ccs 2
cts 2
cp 1
crap 1
rs 9.7998
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Query;
6
7
use Generator;
8
use JsonException;
9
use Yiisoft\Db\Connection\Connection;
10
use Yiisoft\Db\Constraint\Constraint;
11
use Yiisoft\Db\Constraint\ConstraintFinderInterface;
12
use Yiisoft\Db\Exception\Exception;
13
use Yiisoft\Db\Exception\InvalidArgumentException;
14
use Yiisoft\Db\Exception\InvalidConfigException;
15
use Yiisoft\Db\Exception\NotSupportedException;
16
use Yiisoft\Db\Expression\Expression;
17
use Yiisoft\Db\Expression\ExpressionBuilder;
18
use Yiisoft\Db\Expression\ExpressionBuilderInterface;
19
use Yiisoft\Db\Expression\ExpressionInterface;
20
use Yiisoft\Db\Pdo\PdoValue;
21
use Yiisoft\Db\Pdo\PdoValueBuilder;
22
use Yiisoft\Db\Query\Conditions\ConditionInterface;
23
use Yiisoft\Db\Query\Conditions\HashCondition;
24
use Yiisoft\Db\Query\Conditions\SimpleCondition;
25
use Yiisoft\Db\Schema\ColumnSchemaBuilder;
26
use Yiisoft\Db\Schema\Schema;
27
use Yiisoft\Strings\NumericHelper;
28
29
use function array_combine;
30
use function array_diff;
31
use function array_filter;
32
use function array_keys;
33
use function array_map;
34
use function array_merge;
35
use function array_reverse;
36
use function array_shift;
37
use function array_unique;
38
use function array_values;
39
use function count;
40
use function ctype_digit;
41
use function get_class;
42
use function implode;
43
use function in_array;
44
use function is_array;
45
use function is_int;
46
use function is_object;
47
use function is_string;
48
use function is_subclass_of;
49
use function json_encode;
50
use function ltrim;
51
use function preg_match;
52
use function preg_replace;
53
use function preg_split;
54
use function reset;
55
use function strpos;
56
use function strtoupper;
57
use function strtr;
58
use function trim;
59
60
/**
61
 * QueryBuilder builds a SELECT SQL statement based on the specification given as a {@see Query} object.
62
 *
63
 * SQL statements are created from {@see Query} objects using the {@see build()}-method.
64
 *
65
 * QueryBuilder is also used by {@see Command} to build SQL statements such as INSERT, UPDATE, DELETE, CREATE TABLE.
66
 *
67
 * For more details and usage information on QueryBuilder:
68
 * {@see [guide article on query builders](guide:db-query-builder)}.
69
 *
70
 * @property string[] $conditionClasses Map of condition aliases to condition classes. This property is write-only.
71
 *
72
 * For example:
73
 * ```php
74
 *     ['LIKE' => \Yiisoft\Db\Condition\LikeCondition::class]
75
 * ```
76
 * @property string[] $expressionBuilders Array of builders that should be merged with the pre-defined ones in
77
 * {@see expressionBuilders} property. This property is write-only.
78
 */
79
class QueryBuilder
80
{
81
    /**
82
     * The prefix for automatically generated query binding parameters.
83
     */
84
    public const PARAM_PREFIX = ':qp';
85
86
    /**
87
     * @var array the abstract column types mapped to physical column types.
88
     * This is mainly used to support creating/modifying tables using DB-independent data type specifications.
89
     * Child classes should override this property to declare supported type mappings.
90
     */
91
    protected array $typeMap = [];
92
93
    /**
94
     * @var array map of condition aliases to condition classes. For example:
95
     *
96
     * ```php
97
     * return [
98
     *     'LIKE' => \Yiisoft\Db\Condition\LikeCondition::class,
99
     * ];
100
     * ```
101
     *
102
     * This property is used by {@see createConditionFromArray} method.
103
     * See default condition classes list in {@see defaultConditionClasses()} method.
104
     *
105
     * In case you want to add custom conditions support, use the {@see setConditionClasses()} method.
106
     *
107
     * @see setConditonClasses()
108
     * @see defaultConditionClasses()
109
     */
110
    protected array $conditionClasses = [];
111
112
    /**
113
     * @var ExpressionBuilderInterface[]|string[] maps expression class to expression builder class.
114
     * For example:
115
     *
116
     * ```php
117
     * [
118
     *    Expression::class => ExpressionBuilder::class
119
     * ]
120
     * ```
121
     * This property is mainly used by {@see buildExpression()} to build SQL expressions form expression objects.
122
     * See default values in {@see defaultExpressionBuilders()} method.
123
     *
124
     * {@see setExpressionBuilders()}
125
     * {@see defaultExpressionBuilders()}
126
     */
127
    protected array $expressionBuilders = [];
128
    protected string $separator = ' ';
129
    private Connection $db;
130
131
    public function __construct(Connection $db)
132 1931
    {
133
        $this->db = $db;
134 1931
        $this->expressionBuilders = $this->defaultExpressionBuilders();
135 1931
        $this->conditionClasses = $this->defaultConditionClasses();
136 1931
    }
137 1931
138
    /**
139
     * Contains array of default condition classes. Extend this method, if you want to change default condition classes
140
     * for the query builder.
141
     *
142
     * @return array
143
     *
144
     * See {@see conditionClasses} docs for details.
145
     */
146
    protected function defaultConditionClasses(): array
147 1931
    {
148
        return [
149
            'NOT' => Conditions\NotCondition::class,
150 1931
            'AND' => Conditions\AndCondition::class,
151
            'OR' => Conditions\OrCondition::class,
152
            'BETWEEN' => Conditions\BetweenCondition::class,
153
            'NOT BETWEEN' => Conditions\BetweenCondition::class,
154
            'IN' => Conditions\InCondition::class,
155
            'NOT IN' => Conditions\InCondition::class,
156
            'LIKE' => Conditions\LikeCondition::class,
157
            'NOT LIKE' => Conditions\LikeCondition::class,
158
            'OR LIKE' => Conditions\LikeCondition::class,
159
            'OR NOT LIKE' => Conditions\LikeCondition::class,
160
            'EXISTS' => Conditions\ExistsCondition::class,
161
            'NOT EXISTS' => Conditions\ExistsCondition::class,
162
        ];
163
    }
164
165
    /**
166
     * Contains array of default expression builders. Extend this method and override it, if you want to change default
167
     * expression builders for this query builder.
168
     *
169
     * @return array
170
     *
171
     * See {@see expressionBuilders} docs for details.
172
     */
173
    protected function defaultExpressionBuilders(): array
174 1931
    {
175
        return [
176
            Query::class => QueryExpressionBuilder::class,
177 1931
            PdoValue::class => PdoValueBuilder::class,
178
            Expression::class => ExpressionBuilder::class,
179
            Conditions\ConjunctionCondition::class => Conditions\ConjunctionConditionBuilder::class,
180
            Conditions\NotCondition::class => Conditions\NotConditionBuilder::class,
181
            Conditions\AndCondition::class => Conditions\ConjunctionConditionBuilder::class,
182
            Conditions\OrCondition::class => Conditions\ConjunctionConditionBuilder::class,
183
            Conditions\BetweenCondition::class => Conditions\BetweenConditionBuilder::class,
184
            Conditions\InCondition::class => Conditions\InConditionBuilder::class,
185
            Conditions\LikeCondition::class => Conditions\LikeConditionBuilder::class,
186
            Conditions\ExistsCondition::class => Conditions\ExistsConditionBuilder::class,
187
            Conditions\SimpleCondition::class => Conditions\SimpleConditionBuilder::class,
188
            Conditions\HashCondition::class => Conditions\HashConditionBuilder::class,
189
            Conditions\BetweenColumnsCondition::class => Conditions\BetweenColumnsConditionBuilder::class,
190
        ];
191
    }
192
193
    /**
194
     * Setter for {@see expressionBuilders property.
195
     *
196
     * @param string[] $builders array of builders that should be merged with the pre-defined ones in property.
197
     *
198
     * See {@see expressionBuilders} docs for details.
199
     */
200
    public function setExpressionBuilders(array $builders): void
201
    {
202
        $this->expressionBuilders = array_merge($this->expressionBuilders, $builders);
203
    }
204
205
    /**
206
     * Setter for {@see conditionClasses} property.
207
     *
208
     * @param string[] $classes map of condition aliases to condition classes. For example:
209
     *
210
     * ```php
211
     * ['LIKE' => \Yiisoft\Db\Condition\LikeCondition::class]
212
     * ```
213
     *
214
     * See {@see conditionClasses} docs for details.
215
     */
216
    public function setConditionClasses(array $classes): void
217
    {
218
        $this->conditionClasses = array_merge($this->conditionClasses, $classes);
219
    }
220
221
    /**
222
     * Generates a SELECT SQL statement from a {@see Query} object.
223
     *
224
     * @param Query $query the {@see Query} object from which the SQL statement will be generated.
225
     * @param array $params the parameters to be bound to the generated SQL statement. These parameters will be included
226
     * in the result with the additional parameters generated during the query building process.
227
     *
228
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException
229
     *
230
     * @return array the generated SQL statement (the first array element) and the corresponding parameters to be bound
231
     * to the SQL statement (the second array element). The parameters returned include those provided in `$params`.
232
     * @psalm-return array{string,array<array-key, mixed>}
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|JsonException|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|JsonException|NotSupportedException
393
     *
394
     * @return array array of column names, placeholders, values and params.
395
     */
396 282
    protected function prepareInsertValues(string $table, $columns, array $params = []): array
397
    {
398 282
        $schema = $this->db->getSchema();
399 282
        $tableSchema = $schema->getTableSchema($table);
400 282
        $columnSchemas = $tableSchema !== null ? $tableSchema->getColumns() : [];
401 282
        $names = [];
402 282
        $placeholders = [];
403 282
        $values = ' DEFAULT VALUES';
404
405 282
        if ($columns instanceof Query) {
406 69
            [$names, $values, $params] = $this->prepareInsertSelectSubQuery($columns, $schema, $params);
407
        } else {
408 222
            foreach ($columns as $name => $value) {
409 217
                $names[] = $schema->quoteColumnName($name);
410 217
                $value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
411
412 217
                if ($value instanceof ExpressionInterface) {
413 43
                    $placeholders[] = $this->buildExpression($value, $params);
414 211
                } elseif ($value instanceof Query) {
415
                    [$sql, $params] = $this->build($value, $params);
416
                    $placeholders[] = "($sql)";
417
                } else {
418 211
                    $placeholders[] = $this->bindParam($value, $params);
419
                }
420
            }
421
        }
422
423 267
        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|JsonException
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,
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|JsonException
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|JsonException
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 60
    public function createTable(string $table, array $columns, ?string $options = null): string
812
    {
813 60
        $cols = [];
814 60
        foreach ($columns as $name => $type) {
815 60
            if (is_string($name)) {
816 60
                $cols[] = "\t" . $this->db->quoteColumnName($name) . ' ' . $this->getColumnType($type);
817
            } else {
818 5
                $cols[] = "\t" . $type;
819
            }
820
        }
821
822 60
        $sql = 'CREATE TABLE ' . $this->db->quoteTableName($table) . " (\n" . implode(",\n", $cols) . "\n)";
823
824 60
        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) . ')';
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
     * @psalm-param array<array-key, ExpressionInterface|string>|string $columns
1047
     *
1048
     * @throws Exception|InvalidArgumentException
1049
     *
1050 11
     * @return string the SQL statement for creating a new index.
1051
     */
1052 11
    public function createIndex(string $name, string $table, $columns, bool $unique = false): string
1053 11
    {
1054 11
        return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
1055 11
            . $this->db->quoteTableName($name) . ' ON '
1056
            . $this->db->quoteTableName($table)
1057
            . ' (' . $this->buildColumns($columns) . ')';
1058
    }
1059
1060
    /**
1061
     * Builds a SQL statement for dropping an index.
1062
     *
1063
     * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
1064
     * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
1065
     *
1066 6
     * @return string the SQL statement for dropping an index.
1067
     */
1068 6
    public function dropIndex(string $name, string $table): string
1069
    {
1070
        return 'DROP INDEX ' . $this->db->quoteTableName($name) . ' ON ' . $this->db->quoteTableName($table);
1071
    }
1072
1073
    /**
1074
     * Creates a SQL command for adding an unique constraint to an existing table.
1075
     *
1076
     * @param string $name the name of the unique constraint. The name will be properly quoted by the method.
1077
     * @param string $table the table that the unique constraint will be added to. The name will be properly quoted by
1078
     * the method.
1079
     * @param array|string $columns the name of the column to that the constraint will be added on. If there are
1080
     * multiple columns, separate them with commas. The name will be properly quoted by the method.
1081
     *
1082 12
     * @return string the SQL statement for adding an unique constraint to an existing table.
1083
     */
1084 12
    public function addUnique(string $name, string $table, $columns): string
1085 8
    {
1086
        if (is_string($columns)) {
1087 12
            $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
1088 12
        }
1089
        foreach ($columns as $i => $col) {
1090
            $columns[$i] = $this->db->quoteColumnName($col);
1091 12
        }
1092 12
1093 12
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
1094
            . $this->db->quoteColumnName($name) . ' UNIQUE ('
1095
            . implode(', ', $columns) . ')';
1096
    }
1097
1098
    /**
1099
     * Creates a SQL command for dropping an unique constraint.
1100
     *
1101
     * @param string $name the name of the unique constraint to be dropped. The name will be properly quoted by the
1102
     * method.
1103
     * @param string $table the table whose unique constraint is to be dropped. The name will be properly quoted by the
1104
     * method.
1105
     *
1106 6
     * @return string the SQL statement for dropping an unique constraint.
1107
     */
1108 6
    public function dropUnique(string $name, string $table): string
1109 6
    {
1110
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
1111
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
1112
    }
1113
1114
    /**
1115
     * Creates a SQL command for adding a check constraint to an existing table.
1116
     *
1117
     * @param string $name the name of the check constraint. The name will be properly quoted by the method.
1118
     * @param string $table the table that the check constraint will be added to. The name will be properly quoted by
1119
     * the method.
1120
     * @param string $expression the SQL of the `CHECK` constraint.
1121
     *
1122 6
     * @return string the SQL statement for adding a check constraint to an existing table.
1123
     */
1124 6
    public function addCheck(string $name, string $table, string $expression): string
1125 6
    {
1126
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
1127
            . $this->db->quoteColumnName($name) . ' CHECK (' . $this->db->quoteSql($expression) . ')';
1128
    }
1129
1130
    /**
1131
     * Creates a SQL command for dropping a check constraint.
1132
     *
1133
     * @param string $name the name of the check constraint to be dropped. The name will be properly quoted by the
1134
     * method.
1135
     * @param string $table the table whose check constraint is to be dropped. The name will be properly quoted by the
1136
     * method.
1137
     *
1138 6
     * @return string the SQL statement for dropping a check constraint.
1139
     */
1140 6
    public function dropCheck(string $name, string $table): string
1141 6
    {
1142
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
1143
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
1144
    }
1145
1146
    /**
1147
     * Creates a SQL command for adding a default value constraint to an existing table.
1148
     *
1149
     * @param string $name the name of the default value constraint.
1150
     * The name will be properly quoted by the method.
1151
     * @param string $table the table that the default value constraint will be added to.
1152
     * The name will be properly quoted by the method.
1153
     * @param string $column the name of the column to that the constraint will be added on.
1154
     * The name will be properly quoted by the method.
1155
     * @param mixed $value default value.
1156
     *
1157
     * @throws Exception|NotSupportedException if this is not supported by the underlying DBMS.
1158
     *
1159
     * @return string the SQL statement for adding a default value constraint to an existing table.
1160
     */
1161
    public function addDefaultValue(string $name, string $table, string $column, $value): string
1162
    {
1163
        throw new NotSupportedException(
1164
            $this->db->getDriverName() . ' does not support adding default value constraints.'
1165
        );
1166
    }
1167
1168
    /**
1169
     * Creates a SQL command for dropping a default value constraint.
1170
     *
1171
     * @param string $name the name of the default value constraint to be dropped.
1172
     * The name will be properly quoted by the method.
1173
     * @param string $table the table whose default value constraint is to be dropped.
1174
     * The name will be properly quoted by the method.
1175
     *
1176
     * @throws Exception|NotSupportedException if this is not supported by the underlying DBMS.
1177
     *
1178
     * @return string the SQL statement for dropping a default value constraint.
1179
     */
1180
    public function dropDefaultValue(string $name, string $table): string
1181
    {
1182
        throw new NotSupportedException(
1183
            $this->db->getDriverName() . ' does not support dropping default value constraints.'
1184
        );
1185
    }
1186
1187
    /**
1188
     * Creates a SQL statement for resetting the sequence value of a table's primary key.
1189
     *
1190
     * The sequence will be reset such that the primary key of the next new row inserted will have the specified value
1191
     * or 1.
1192
     *
1193
     * @param string $tableName the name of the table whose primary key sequence will be reset.
1194
     * @param array|string|null $value the value for the primary key of the next new row inserted. If this is not set,
1195
     * the next new row's primary key will have a value 1.
1196
     *
1197
     * @throws Exception|NotSupportedException if this is not supported by the underlying DBMS.
1198
     *
1199
     * @return string the SQL statement for resetting sequence.
1200
     */
1201
    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

1201
    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...
1202
    {
1203
        throw new NotSupportedException($this->db->getDriverName() . ' does not support resetting sequence.');
1204
    }
1205
1206
    /**
1207
     * Builds a SQL statement for enabling or disabling integrity check.
1208
     *
1209
     * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
1210
     * @param string $table the table name. Defaults to empty string, meaning that no table will be changed.
1211
     * @param bool $check whether to turn on or off the integrity check.
1212
     *
1213
     * @throws Exception|NotSupportedException if this is not supported by the underlying DBMS.
1214
     *
1215
     * @return string the SQL statement for checking integrity.
1216
     */
1217
    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

1217
    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...
1218
    {
1219
        throw new NotSupportedException(
1220
            $this->db->getDriverName() . ' does not support enabling/disabling integrity check.'
1221
        );
1222
    }
1223
1224
    /**
1225
     * Builds a SQL command for adding comment to column.
1226
     *
1227
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the
1228
     * method.
1229
     * @param string $column the name of the column to be commented. The column name will be properly quoted by the
1230
     * method.
1231
     * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
1232
     *
1233
     * @throws Exception|InvalidConfigException
1234
     *
1235 3
     * @return string the SQL statement for adding comment on column.
1236
     */
1237 3
    public function addCommentOnColumn(string $table, string $column, string $comment): string
1238 3
    {
1239
        return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column)
1240
            . ' IS ' . $this->db->quoteValue($comment);
1241
    }
1242
1243
    /**
1244
     * Builds a SQL command for adding comment to table.
1245
     *
1246
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the
1247
     * method.
1248
     * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
1249
     *
1250
     * @throws Exception|InvalidConfigException
1251
     *
1252 2
     * @return string the SQL statement for adding comment on table.
1253
     */
1254 2
    public function addCommentOnTable(string $table, string $comment): string
1255
    {
1256
        return 'COMMENT ON TABLE ' . $this->db->quoteTableName($table) . ' IS ' . $this->db->quoteValue($comment);
1257
    }
1258
1259
    /**
1260
     * Builds a SQL command for adding comment to column.
1261
     *
1262
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the
1263
     * method.
1264
     * @param string $column the name of the column to be commented. The column name will be properly quoted by the
1265
     * method.
1266
     *
1267 1
     * @return string the SQL statement for adding comment on column.
1268
     */
1269 1
    public function dropCommentFromColumn(string $table, string $column): string
1270 1
    {
1271
        return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column)
1272
            . ' IS NULL';
1273
    }
1274
1275
    /**
1276
     * Builds a SQL command for adding comment to table.
1277
     *
1278
     * @param string $table the table whose column is to be commented. The table name will be properly quoted by the
1279
     * method.
1280
     *
1281 1
     * @return string the SQL statement for adding comment on column.
1282
     */
1283 1
    public function dropCommentFromTable(string $table): string
1284
    {
1285
        return 'COMMENT ON TABLE ' . $this->db->quoteTableName($table) . ' IS NULL';
1286
    }
1287
1288
    /**
1289
     * Creates a SQL View.
1290
     *
1291
     * @param string $viewName the name of the view to be created.
1292
     * @param Query|string $subQuery the select statement which defines the view.
1293
     *
1294
     * This can be either a string or a {@see Query} object.
1295
     *
1296
     * @throws Exception|InvalidConfigException|NotSupportedException
1297
     *
1298 5
     * @return string the `CREATE VIEW` SQL statement.
1299
     */
1300 5
    public function createView(string $viewName, $subQuery): string
1301 5
    {
1302 5
        if ($subQuery instanceof Query) {
1303
            [$rawQuery, $params] = $this->build($subQuery);
1304 5
1305 5
            foreach ($params as $key => $value) {
1306 5
                $params[$key] = $this->db->quoteValue($value);
1307
            }
1308 5
            $subQuery = strtr($rawQuery, $params);
1309
        }
1310
1311 5
        return 'CREATE VIEW ' . $this->db->quoteTableName($viewName) . ' AS ' . $subQuery;
1312
    }
1313
1314
    /**
1315
     * Drops a SQL View.
1316
     *
1317
     * @param string $viewName the name of the view to be dropped.
1318
     *
1319
     * @return string the `DROP VIEW` SQL statement.
1320
     */
1321 5
    public function dropView(string $viewName): string
1322
    {
1323 5
        return 'DROP VIEW ' . $this->db->quoteTableName($viewName);
1324
    }
1325
1326
    /**
1327
     * Converts an abstract column type into a physical column type.
1328
     *
1329
     * The conversion is done using the type map specified in {@see typeMap}.
1330
     * The following abstract column types are supported (using MySQL as an example to explain the corresponding
1331
     * physical types):
1332
     *
1333
     * - `pk`: an auto-incremental primary key type, will be converted into "int(11) NOT NULL AUTO_INCREMENT PRIMARY
1334
     *    KEY"
1335
     * - `bigpk`: an auto-incremental primary key type, will be converted into "bigint(20) NOT NULL AUTO_INCREMENT
1336
     *    PRIMARY KEY"
1337
     * - `upk`: an unsigned auto-incremental primary key type, will be converted into "int(10) UNSIGNED NOT NULL
1338
     *    AUTO_INCREMENT PRIMARY KEY"
1339
     * - `char`: char type, will be converted into "char(1)"
1340
     * - `string`: string type, will be converted into "varchar(255)"
1341
     * - `text`: a long string type, will be converted into "text"
1342
     * - `smallint`: a small integer type, will be converted into "smallint(6)"
1343
     * - `integer`: integer type, will be converted into "int(11)"
1344
     * - `bigint`: a big integer type, will be converted into "bigint(20)"
1345
     * - `boolean`: boolean type, will be converted into "tinyint(1)"
1346
     * - `float``: float number type, will be converted into "float"
1347
     * - `decimal`: decimal number type, will be converted into "decimal"
1348
     * - `datetime`: datetime type, will be converted into "datetime"
1349
     * - `timestamp`: timestamp type, will be converted into "timestamp"
1350
     * - `time`: time type, will be converted into "time"
1351
     * - `date`: date type, will be converted into "date"
1352
     * - `money`: money type, will be converted into "decimal(19,4)"
1353
     * - `binary`: binary data type, will be converted into "blob"
1354
     *
1355
     * If the abstract type contains two or more parts separated by spaces (e.g. "string NOT NULL"), then only the first
1356
     * part will be converted, and the rest of the parts will be appended to the converted result.
1357
     *
1358
     * For example, 'string NOT NULL' is converted to 'varchar(255) NOT NULL'.
1359
     *
1360
     * For some of the abstract types you can also specify a length or precision constraint by appending it in round
1361
     * brackets directly to the type.
1362
     *
1363
     * For example `string(32)` will be converted into "varchar(32)" on a MySQL database. If the underlying DBMS does
1364
     * not support these kind of constraints for a type it will be ignored.
1365
     *
1366
     * If a type cannot be found in {@see typeMap}, it will be returned without any change.
1367
     *
1368
     * @param ColumnSchemaBuilder|string $type abstract column type.
1369
     *
1370
     * @return string physical column type.
1371
     */
1372 66
    public function getColumnType($type): string
1373
    {
1374 66
        if ($type instanceof ColumnSchemaBuilder) {
1375 11
            $type = $type->__toString();
1376
        }
1377
1378 66
        if (isset($this->typeMap[$type])) {
1379 41
            return $this->typeMap[$type];
1380
        }
1381
1382 40
        if (preg_match('/^(\w+)\((.+?)\)(.*)$/', $type, $matches)) {
1383 20
            if (isset($this->typeMap[$matches[1]])) {
1384 17
                return preg_replace(
1385
                    '/\(.+\)/',
1386 17
                    '(' . $matches[2] . ')',
1387 17
                    $this->typeMap[$matches[1]]
1388 20
                ) . $matches[3];
1389
            }
1390 33
        } elseif (preg_match('/^(\w+)\s+/', $type, $matches)) {
1391 32
            if (isset($this->typeMap[$matches[1]])) {
1392 32
                return preg_replace('/^\w+/', $this->typeMap[$matches[1]], $type);
1393
            }
1394
        }
1395
1396 5
        return $type;
1397
    }
1398
1399
    /**
1400
     * @param array $columns
1401
     * @param array $params the binding parameters to be populated.
1402
     * @param bool|null $distinct
1403
     * @param string|null $selectOption
1404
     *
1405
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException
1406
     *
1407
     * @return string the SELECT clause built from {@see Query::$select}.
1408
     */
1409 1507
    public function buildSelect(
1410
        array $columns,
1411
        array &$params,
1412
        ?bool $distinct = false,
1413
        string $selectOption = null
1414
    ): string {
1415 1507
        $select = $distinct ? 'SELECT DISTINCT' : 'SELECT';
1416
1417 1507
        if ($selectOption !== null) {
1418
            $select .= ' ' . $selectOption;
1419
        }
1420
1421 1507
        if (empty($columns)) {
1422 1286
            return $select . ' *';
1423
        }
1424
1425 434
        foreach ($columns as $i => $column) {
1426 434
            if ($column instanceof ExpressionInterface) {
1427 73
                if (is_int($i)) {
1428 10
                    $columns[$i] = $this->buildExpression($column, $params);
1429
                } else {
1430 73
                    $columns[$i] = $this->buildExpression($column, $params) . ' AS ' . $this->db->quoteColumnName($i);
1431
                }
1432 416
            } elseif ($column instanceof Query) {
1433
                [$sql, $params] = $this->build($column, $params);
1434
                $columns[$i] = "($sql) AS " . $this->db->quoteColumnName($i);
1435 416
            } elseif (is_string($i) && $i !== $column) {
1436 19
                if (strpos($column, '(') === false) {
1437 14
                    $column = $this->db->quoteColumnName($column);
1438
                }
1439 19
                $columns[$i] = "$column AS " . $this->db->quoteColumnName($i);
1440 412
            } elseif (strpos($column, '(') === false) {
1441 317
                if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_.]+)$/', $column, $matches)) {
1442
                    $columns[$i] = $this->db->quoteColumnName(
1443
                        $matches[1]
1444
                    ) . ' AS ' . $this->db->quoteColumnName($matches[2]);
1445
                } else {
1446 317
                    $columns[$i] = $this->db->quoteColumnName($column);
1447
                }
1448
            }
1449
        }
1450
1451 434
        return $select . ' ' . implode(', ', $columns);
1452
    }
1453
1454
    /**
1455
     * @param array|null $tables
1456
     * @param array $params the binding parameters to be populated.
1457
     *
1458
     * @throws Exception|InvalidConfigException|NotSupportedException
1459
     *
1460
     * @return string the FROM clause built from {@see Query::$from}.
1461
     */
1462 1527
    public function buildFrom(?array $tables, array &$params): string
1463
    {
1464 1527
        if (empty($tables)) {
1465 668
            return '';
1466
        }
1467
1468 921
        $tables = $this->quoteTableNames($tables, $params);
1469
1470 921
        return 'FROM ' . implode(', ', $tables);
1471
    }
1472
1473
    /**
1474
     * @param array $joins
1475
     * @param array $params the binding parameters to be populated.
1476
     *
1477
     * @throws Exception if the $joins parameter is not in proper format.
1478
     *
1479
     * @return string the JOIN clause built from {@see Query::$join}.
1480
     */
1481 1507
    public function buildJoin(array $joins, array &$params): string
1482
    {
1483 1507
        if (empty($joins)) {
1484 1502
            return '';
1485
        }
1486
1487 110
        foreach ($joins as $i => $join) {
1488 110
            if (!is_array($join) || !isset($join[0], $join[1])) {
1489
                throw new Exception(
1490
                    'A join clause must be specified as an array of join type, join table, and optionally join '
1491
                    . 'condition.'
1492
                );
1493
            }
1494
1495
            /* 0:join type, 1:join table, 2:on-condition (optional) */
1496 110
            [$joinType, $table] = $join;
1497
1498 110
            $tables = $this->quoteTableNames((array) $table, $params);
1499 110
            $table = reset($tables);
1500 110
            $joins[$i] = "$joinType $table";
1501
1502 110
            if (isset($join[2])) {
1503 110
                $condition = $this->buildCondition($join[2], $params);
1504 110
                if ($condition !== '') {
1505 110
                    $joins[$i] .= ' ON ' . $condition;
1506
                }
1507
            }
1508
        }
1509
1510 110
        return implode($this->separator, $joins);
1511
    }
1512
1513
    /**
1514
     * Quotes table names passed.
1515
     *
1516
     * @param array $tables
1517
     * @param array $params
1518
     *
1519
     * @throws Exception|InvalidConfigException|NotSupportedException
1520
     *
1521
     * @return array
1522
     */
1523 921
    private function quoteTableNames(array $tables, array &$params): array
1524
    {
1525 921
        foreach ($tables as $i => $table) {
1526 921
            if ($table instanceof Query) {
1527 16
                [$sql, $params] = $this->build($table, $params);
1528 16
                $tables[$i] = "($sql) " . $this->db->quoteTableName((string) $i);
1529 921
            } elseif (is_string($i)) {
1530 58
                if (strpos($table, '(') === false) {
1531 40
                    $table = $this->db->quoteTableName($table);
1532
                }
1533 58
                $tables[$i] = "$table " . $this->db->quoteTableName($i);
1534 898
            } elseif (is_string($table)) {
1535 887
                if (strpos($table, '(') === false) {
1536 887
                    if ($tableWithAlias = $this->extractAlias($table)) { // with alias
1537 50
                        $tables[$i] = $this->db->quoteTableName($tableWithAlias[1]) . ' '
1538 50
                            . $this->db->quoteTableName($tableWithAlias[2]);
1539
                    } else {
1540 847
                        $tables[$i] = $this->db->quoteTableName($table);
1541
                    }
1542
                }
1543
            }
1544
        }
1545
1546 921
        return $tables;
1547
    }
1548
1549
    /**
1550
     * @param array|string $condition
1551
     * @param array $params the binding parameters to be populated.
1552
     *
1553
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException
1554
     *
1555
     * @return string the WHERE clause built from {@see Query::$where}.
1556
     */
1557 1533
    public function buildWhere($condition, array &$params = []): string
1558
    {
1559 1533
        $where = $this->buildCondition($condition, $params);
1560
1561 1533
        return ($where === '') ? '' : ('WHERE ' . $where);
1562
    }
1563
1564
    /**
1565
     * @param array $columns
1566
     * @psalm-param array<string, Expression|string> $columns
1567
     *
1568
     * @param array $params the binding parameters to be populated
1569
     *
1570
     * @throws Exception|InvalidArgumentException
1571
     *
1572 1507
     * @return string the GROUP BY clause
1573
     */
1574 1507
    public function buildGroupBy(array $columns, array &$params = []): string
1575 1497
    {
1576
        if (empty($columns)) {
1577 15
            return '';
1578 15
        }
1579 5
1580 5
        foreach ($columns as $i => $column) {
1581 15
            if ($column instanceof Expression) {
1582 15
                $columns[$i] = $this->buildExpression($column);
1583
                $params = array_merge($params, $column->getParams());
1584
            } elseif (strpos($column, '(') === false) {
1585
                $columns[$i] = $this->db->quoteColumnName($column);
1586 15
            }
1587
        }
1588
1589
        return 'GROUP BY ' . implode(', ', $columns);
1590
    }
1591
1592
    /**
1593
     * @param array|string $condition
1594
     * @param array $params the binding parameters to be populated.
1595
     *
1596
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException
1597 1507
     *
1598
     * @return string the HAVING clause built from {@see Query::$having}.
1599 1507
     */
1600
    public function buildHaving($condition, array &$params = []): string
1601 1507
    {
1602
        $having = $this->buildCondition($condition, $params);
1603
1604
        return ($having === '') ? '' : ('HAVING ' . $having);
1605
    }
1606
1607
    /**
1608
     * Builds the ORDER BY and LIMIT/OFFSET clauses and appends them to the given SQL.
1609
     *
1610
     * @param string $sql the existing SQL (without ORDER BY/LIMIT/OFFSET).
1611
     * @param array $orderBy the order by columns. See {@see Query::orderBy} for more details on how to specify this
1612
     * parameter.
1613
     * @psalm-param array<string, Expression|int|string> $orderBy
1614
     *
1615
     * @param Expression|int|null $limit the limit number. See {@see Query::limit} for more details.
1616
     * @param Expression|int|null $offset the offset number. See {@see Query::offset} for more details.
1617
     * @param array $params the binding parameters to be populated.
1618 940
     *
1619
     * @throws Exception|InvalidArgumentException
1620
     *
1621
     * @return string the SQL completed with ORDER BY/LIMIT/OFFSET (if any).
1622
     */
1623
    public function buildOrderByAndLimit(
1624
        string $sql,
1625 940
        array $orderBy,
1626 940
        $limit,
1627 138
        $offset,
1628
        array &$params = []
1629 940
    ): string {
1630 940
        $orderBy = $this->buildOrderBy($orderBy, $params);
1631 36
        if ($orderBy !== '') {
1632
            $sql .= $this->separator . $orderBy;
1633
        }
1634 940
        $limit = $this->buildLimit($limit, $offset);
1635
        if ($limit !== '') {
1636
            $sql .= $this->separator . $limit;
1637
        }
1638
1639
        return $sql;
1640
    }
1641
1642
    /**
1643
     * @param array $columns
1644
     * @psalm-param array<string, Expression|int|string> $columns
1645 1519
     *
1646
     * @param array $params the binding parameters to be populated
1647 1519
     *
1648 1464
     * @throws Exception|InvalidArgumentException
1649
     *
1650
     * @return string the ORDER BY clause built from {@see Query::$orderBy}.
1651 229
     */
1652
    public function buildOrderBy(array $columns, array &$params = []): string
1653 229
    {
1654 229
        if (empty($columns)) {
1655 5
            return '';
1656 5
        }
1657
1658 229
        $orders = [];
1659
1660
        foreach ($columns as $name => $direction) {
1661
            if ($direction instanceof Expression) {
1662 229
                $orders[] = $this->buildExpression($direction);
1663
                $params = array_merge($params, $direction->getParams());
1664
            } else {
1665
                $orders[] = $this->db->quoteColumnName($name) . ($direction === SORT_DESC ? ' DESC' : '');
1666
            }
1667
        }
1668
1669
        return 'ORDER BY ' . implode(', ', $orders);
1670
    }
1671 346
1672
    /**
1673 346
     * @param Expression|int|null $limit
1674
     * @param Expression|int|null $offset
1675 346
     *
1676 11
     * @return string the LIMIT and OFFSET clauses.
1677
     */
1678
    public function buildLimit($limit, $offset): string
1679 346
    {
1680 3
        $sql = '';
1681
1682
        if ($this->hasLimit($limit)) {
1683 346
            $sql = 'LIMIT ' . (string) $limit;
1684
        }
1685
1686
        if ($this->hasOffset($offset)) {
1687
            $sql .= ' OFFSET ' . (string) $offset;
1688
        }
1689
1690
        return ltrim($sql);
1691
    }
1692
1693 1216
    /**
1694
     * Checks to see if the given limit is effective.
1695 1216
     *
1696
     * @param mixed $limit the given limit.
1697
     *
1698
     * @return bool whether the limit is effective.
1699
     */
1700
    protected function hasLimit($limit): bool
1701
    {
1702
        return ($limit instanceof ExpressionInterface) || ctype_digit((string) $limit);
1703
    }
1704
1705 1216
    /**
1706
     * Checks to see if the given offset is effective.
1707 1216
     *
1708
     * @param mixed $offset the given offset.
1709
     *
1710
     * @return bool whether the offset is effective.
1711
     */
1712
    protected function hasOffset($offset): bool
1713
    {
1714
        return ($offset instanceof ExpressionInterface) || (ctype_digit((string)$offset) && (string)$offset !== '0');
1715
    }
1716
1717
    /**
1718 1219
     * @param array $unions
1719
     * @psalm-param array<array{query:Query|string,all:bool}> $unions
1720 1219
     *
1721 1219
     * @param array $params the binding parameters to be populated
1722
     *
1723
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException
1724 9
     *
1725
     * @return string the UNION clause built from {@see Query::$union}.
1726 9
     */
1727 9
    public function buildUnion(array $unions, array &$params): string
1728 9
    {
1729 9
        if (empty($unions)) {
1730
            return '';
1731
        }
1732 9
1733
        $result = '';
1734
1735 9
        foreach ($unions as $i => $union) {
1736
            $query = $union['query'];
1737
            if ($query instanceof Query) {
1738
                [$unions[$i]['query'], $params] = $this->build($query, $params);
1739
            }
1740
1741
            $result .= 'UNION ' . ($union['all'] ? 'ALL ' : '') . '( ' . $unions[$i]['query'] . ' ) ';
1742
        }
1743
1744
        return trim($result);
1745
    }
1746
1747
    /**
1748
     * Processes columns and properly quotes them if necessary.
1749 41
     *
1750
     * It will join all columns into a string with comma as separators.
1751 41
     *
1752 31
     * @param array|string $columns the columns to be processed.
1753
     * @psalm-param array<array-key, ExpressionInterface|string>|string $columns
1754
     *
1755
     * @throws Exception|InvalidArgumentException
1756 31
     *
1757 31
     * @return string the processing result.
1758
     */
1759 31
    public function buildColumns($columns): string
1760
    {
1761
        if (!is_array($columns)) {
1762
            if (strpos($columns, '(') !== false) {
1763 41
                return $columns;
1764 41
            }
1765
1766 41
            $rawColumns = $columns;
1767 41
            $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
1768
1769
            if ($columns === false) {
1770
                throw new InvalidArgumentException("$rawColumns is not valid columns.");
1771 41
            }
1772
        }
1773
        foreach ($columns as $i => $column) {
1774
            if ($column instanceof ExpressionInterface) {
1775
                $columns[$i] = $this->buildExpression($column);
1776
            } elseif (strpos($column, '(') === false) {
1777
                $columns[$i] = $this->db->quoteColumnName($column);
1778
            }
1779
        }
1780
1781
        return implode(', ', $columns);
0 ignored issues
show
Bug introduced by
It seems like $columns can also be of type 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

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