Passed
Pull Request — master (#216)
by Wilmer
29:38 queued 14:54
created

QueryBuilder::prepareInsertSelectSubQuery()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 7.392

Importance

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

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