Passed
Pull Request — master (#216)
by Wilmer
16:23
created

QueryBuilder::addCommentOnColumn()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 3
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Query;
6
7
use 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 array_walk;
40
use function count;
41
use function ctype_digit;
42
use function get_class;
43
use function implode;
44
use function in_array;
45
use function is_array;
46
use function is_int;
47
use function is_object;
48
use function is_string;
49
use function is_subclass_of;
50
use function json_encode;
51
use function ltrim;
52
use function preg_match;
53
use function preg_replace;
54
use function preg_split;
55
use function reset;
56
use function strpos;
57
use function strtoupper;
58
use function strtr;
59
use function trim;
60
61
/**
62
 * QueryBuilder builds a SELECT SQL statement based on the specification given as a {@see Query} object.
63
 *
64
 * SQL statements are created from {@see Query} objects using the {@see build()}-method.
65
 *
66
 * QueryBuilder is also used by {@see Command} to build SQL statements such as INSERT, UPDATE, DELETE, CREATE TABLE.
67
 *
68
 * For more details and usage information on QueryBuilder:
69
 * {@see [guide article on query builders](guide:db-query-builder)}.
70
 *
71
 * @property string[] $conditionClasses Map of condition aliases to condition classes. This property is write-only.
72
 *
73
 * For example:
74
 * ```php
75
 *     ['LIKE' => \Yiisoft\Db\Condition\LikeCondition::class]
76
 * ```
77
 * @property string[] $expressionBuilders Array of builders that should be merged with the pre-defined ones in
78
 * {@see expressionBuilders} property. This property is write-only.
79
 */
80
class QueryBuilder
81
{
82
    /**
83
     * The prefix for automatically generated query binding parameters.
84
     */
85
    public const PARAM_PREFIX = ':qp';
86
87
    /**
88
     * @var array the abstract column types mapped to physical column types.
89
     * This is mainly used to support creating/modifying tables using DB-independent data type specifications.
90
     * Child classes should override this property to declare supported type mappings.
91
     */
92
    protected array $typeMap = [];
93
94
    /**
95
     * @var array map of condition aliases to condition classes. For example:
96
     *
97
     * ```php
98
     * return [
99
     *     'LIKE' => \Yiisoft\Db\Condition\LikeCondition::class,
100
     * ];
101
     * ```
102
     *
103
     * This property is used by {@see createConditionFromArray} method.
104
     * See default condition classes list in {@see defaultConditionClasses()} method.
105
     *
106
     * In case you want to add custom conditions support, use the {@see setConditionClasses()} method.
107
     *
108
     * @see setConditonClasses()
109
     * @see defaultConditionClasses()
110
     */
111
    protected array $conditionClasses = [];
112
113
    /**
114
     * @var ExpressionBuilderInterface[]|string[] maps expression class to expression builder class.
115
     * For example:
116
     *
117
     * ```php
118
     * [
119
     *    Expression::class => ExpressionBuilder::class
120
     * ]
121
     * ```
122
     * This property is mainly used by {@see buildExpression()} to build SQL expressions form expression objects.
123
     * See default values in {@see defaultExpressionBuilders()} method.
124
     *
125
     * {@see setExpressionBuilders()}
126
     * {@see defaultExpressionBuilders()}
127
     */
128
    protected array $expressionBuilders = [];
129
    protected string $separator = ' ';
130
    private Connection $db;
131
132 1931
    public function __construct(Connection $db)
133
    {
134 1931
        $this->db = $db;
135 1931
        $this->expressionBuilders = $this->defaultExpressionBuilders();
136 1931
        $this->conditionClasses = $this->defaultConditionClasses();
137 1931
    }
138
139
    /**
140
     * Contains array of default condition classes. Extend this method, if you want to change default condition classes
141
     * for the query builder.
142
     *
143
     * @return array
144
     *
145
     * See {@see conditionClasses} docs for details.
146
     */
147 1931
    protected function defaultConditionClasses(): array
148
    {
149
        return [
150 1931
            'NOT' => Conditions\NotCondition::class,
151
            'AND' => Conditions\AndCondition::class,
152
            'OR' => Conditions\OrCondition::class,
153
            'BETWEEN' => Conditions\BetweenCondition::class,
154
            'NOT BETWEEN' => Conditions\BetweenCondition::class,
155
            'IN' => Conditions\InCondition::class,
156
            'NOT IN' => Conditions\InCondition::class,
157
            'LIKE' => Conditions\LikeCondition::class,
158
            'NOT LIKE' => Conditions\LikeCondition::class,
159
            'OR LIKE' => Conditions\LikeCondition::class,
160
            'OR NOT LIKE' => Conditions\LikeCondition::class,
161
            'EXISTS' => Conditions\ExistsCondition::class,
162
            'NOT EXISTS' => Conditions\ExistsCondition::class,
163
        ];
164
    }
165
166
    /**
167
     * Contains array of default expression builders. Extend this method and override it, if you want to change default
168
     * expression builders for this query builder.
169
     *
170
     * @return array
171
     *
172
     * See {@see expressionBuilders} docs for details.
173
     */
174 1931
    protected function defaultExpressionBuilders(): array
175
    {
176
        return [
177 1931
            Query::class => QueryExpressionBuilder::class,
178
            PdoValue::class => PdoValueBuilder::class,
179
            Expression::class => ExpressionBuilder::class,
180
            Conditions\ConjunctionCondition::class => Conditions\ConjunctionConditionBuilder::class,
181
            Conditions\NotCondition::class => Conditions\NotConditionBuilder::class,
182
            Conditions\AndCondition::class => Conditions\ConjunctionConditionBuilder::class,
183
            Conditions\OrCondition::class => Conditions\ConjunctionConditionBuilder::class,
184
            Conditions\BetweenCondition::class => Conditions\BetweenConditionBuilder::class,
185
            Conditions\InCondition::class => Conditions\InConditionBuilder::class,
186
            Conditions\LikeCondition::class => Conditions\LikeConditionBuilder::class,
187
            Conditions\ExistsCondition::class => Conditions\ExistsConditionBuilder::class,
188
            Conditions\SimpleCondition::class => Conditions\SimpleConditionBuilder::class,
189
            Conditions\HashCondition::class => Conditions\HashConditionBuilder::class,
190
            Conditions\BetweenColumnsCondition::class => Conditions\BetweenColumnsConditionBuilder::class,
191
        ];
192
    }
193
194
    /**
195
     * Setter for {@see expressionBuilders property.
196
     *
197
     * @param string[] $builders array of builders that should be merged with the pre-defined ones in property.
198
     *
199
     * See {@see expressionBuilders} docs for details.
200
     */
201
    public function setExpressionBuilders(array $builders): void
202
    {
203
        $this->expressionBuilders = array_merge($this->expressionBuilders, $builders);
204
    }
205
206
    /**
207
     * Setter for {@see conditionClasses} property.
208
     *
209
     * @param string[] $classes map of condition aliases to condition classes. For example:
210
     *
211
     * ```php
212
     * ['LIKE' => \Yiisoft\Db\Condition\LikeCondition::class]
213
     * ```
214
     *
215
     * See {@see conditionClasses} docs for details.
216
     */
217
    public function setConditionClasses(array $classes): void
218
    {
219
        $this->conditionClasses = array_merge($this->conditionClasses, $classes);
220
    }
221
222
    /**
223
     * Generates a SELECT SQL statement from a {@see Query} object.
224
     *
225
     * @param Query $query the {@see Query} object from which the SQL statement will be generated.
226
     * @param array $params the parameters to be bound to the generated SQL statement. These parameters will be included
227
     * in the result with the additional parameters generated during the query building process.
228
     *
229
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException
230
     *
231
     * @return array the generated SQL statement (the first array element) and the corresponding parameters to be bound
232
     * to the SQL statement (the second array element). The parameters returned include those provided in `$params`.
233
     * @psalm-return array{string,array<array-key, mixed>}
234 1219
     */
235
    public function build(Query $query, array $params = []): array
236 1219
    {
237
        $query = $query->prepare($this);
238 1219
239
        $params = empty($params) ? $query->getParams() : array_merge($params, $query->getParams());
240
241 1219
        $clauses = [
242 1219
            $this->buildSelect($query->getSelect(), $params, $query->getDistinct(), $query->getSelectOption()),
243 1219
            $this->buildFrom($query->getFrom(), $params),
244 1219
            $this->buildJoin($query->getJoin(), $params),
245 1219
            $this->buildWhere($query->getWhere(), $params),
246 1219
            $this->buildGroupBy($query->getGroupBy(), $params),
247
            $this->buildHaving($query->getHaving(), $params),
248
        ];
249 1219
250
        $sql = implode($this->separator, array_filter($clauses));
251 1219
252
        $sql = $this->buildOrderByAndLimit($sql, $query->getOrderBy(), $query->getLimit(), $query->getOffset());
253 1219
254 180
        if (!empty($query->getOrderBy())) {
255 180
            foreach ($query->getOrderBy() as $expression) {
256 4
                if ($expression instanceof ExpressionInterface) {
257
                    $this->buildExpression($expression, $params);
258
                }
259
            }
260
        }
261 1219
262 12
        if (!empty($query->getGroupBy())) {
263 12
            foreach ($query->getGroupBy() as $expression) {
264 4
                if ($expression instanceof ExpressionInterface) {
265
                    $this->buildExpression($expression, $params);
266
                }
267
            }
268
        }
269 1219
270
        $union = $this->buildUnion($query->getUnion(), $params);
271 1219
272 9
        if ($union !== '') {
273
            $sql = "($sql){$this->separator}$union";
274
        }
275 1219
276
        $with = $this->buildWithQueries($query->getWithQueries(), $params);
277 1219
278 8
        if ($with !== '') {
279
            $sql = "$with{$this->separator}$sql";
280
        }
281 1219
282
        return [$sql, $params];
283
    }
284
285
    /**
286
     * Builds given $expression.
287
     *
288
     * @param ExpressionInterface $expression the expression to be built
289
     * @param array $params the parameters to be bound to the generated SQL statement. These parameters will be included
290
     * in the result with the additional parameters generated during the expression building process.
291
     *
292
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException when $expression building
293
     * is not supported by this QueryBuilder.
294
     *
295
     * @return string the SQL statement that will not be neither quoted nor encoded before passing to DBMS.
296
     *
297
     * {@see ExpressionInterface}
298
     * {@see ExpressionBuilderInterface}
299
     * {@see expressionBuilders}
300 1368
     */
301
    public function buildExpression(ExpressionInterface $expression, array &$params = []): string
302 1368
    {
303
        $builder = $this->getExpressionBuilder($expression);
304 1368
305
        return (string) $builder->build($expression, $params);
306
    }
307
308
    /**
309
     * Gets object of {@see ExpressionBuilderInterface} that is suitable for $expression.
310
     *
311
     * Uses {@see expressionBuilders} array to find a suitable builder class.
312
     *
313
     * @param ExpressionInterface $expression
314
     *
315
     * @throws InvalidArgumentException when $expression building is not supported by this QueryBuilder.
316
     *
317
     * @return ExpressionBuilderInterface|QueryBuilder|string
318
     *
319
     * {@see expressionBuilders}
320 1368
     */
321
    public function getExpressionBuilder(ExpressionInterface $expression)
322 1368
    {
323
        $className = get_class($expression);
324 1368
325
        if (!isset($this->expressionBuilders[$className])) {
326
            foreach (array_reverse($this->expressionBuilders) as $expressionClass => $builderClass) {
327
                if (is_subclass_of($expression, $expressionClass)) {
328
                    $this->expressionBuilders[$className] = $builderClass;
329
                    break;
330
                }
331
            }
332
333
            if (!isset($this->expressionBuilders[$className])) {
334
                throw new InvalidArgumentException(
335
                    'Expression of class ' . $className . ' can not be built in ' . static::class
336
                );
337
            }
338
        }
339 1368
340
        if ($this->expressionBuilders[$className] === __CLASS__) {
341
            return $this;
342
        }
343 1368
344 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...
345
            $this->expressionBuilders[$className] = new $this->expressionBuilders[$className]($this);
346
        }
347 1368
348
        return $this->expressionBuilders[$className];
349
    }
350
351
    /**
352
     * Creates an INSERT SQL statement.
353
     *
354
     * For example,.
355
     *
356
     * ```php
357
     * $sql = $queryBuilder->insert('user', [
358
     *     'name' => 'Sam',
359
     *     'age' => 30,
360
     * ], $params);
361
     * ```
362
     *
363
     * The method will properly escape the table and column names.
364
     *
365
     * @param string $table the table that new rows will be inserted into.
366
     * @param array|Query $columns the column data (name => value) to be inserted into the table or instance of
367
     * {@see Query} to perform INSERT INTO ... SELECT SQL statement. Passing of {@see Query}.
368
     * @param array $params the binding parameters that will be generated by this method. They should be bound to the
369
     * DB command later.
370
     *
371
     * @throws Exception|InvalidArgumentException|InvalidConfigException|JsonException|NotSupportedException
372
     *
373
     * @return string the INSERT SQL.
374 197
     */
375
    public function insert(string $table, $columns, array &$params = []): string
376 197
    {
377
        [$names, $placeholders, $values, $params] = $this->prepareInsertValues($table, $columns, $params);
378 185
379 185
        return 'INSERT INTO ' . $this->db->quoteTableName($table)
380 185
            . (!empty($names) ? ' (' . implode(', ', $names) . ')' : '')
381
            . (!empty($placeholders) ? ' VALUES (' . implode(', ', $placeholders) . ')' : $values);
382
    }
383
384
    /**
385
     * Prepares a `VALUES` part for an `INSERT` SQL statement.
386
     *
387
     * @param string $table the table that new rows will be inserted into.
388
     * @param array|Query $columns the column data (name => value) to be inserted into the table or instance of
389
     * {@see Query} to perform INSERT INTO ... SELECT SQL statement.
390
     * @param array $params the binding parameters that will be generated by this method.
391
     * They should be bound to the DB command later.
392
     *
393
     * @throws Exception|InvalidArgumentException|InvalidConfigException|JsonException|NotSupportedException
394
     *
395
     * @return array array of column names, placeholders, values and params.
396 282
     */
397
    protected function prepareInsertValues(string $table, $columns, array $params = []): array
398 282
    {
399 282
        $schema = $this->db->getSchema();
400 282
        $tableSchema = $schema->getTableSchema($table);
401 282
        $columnSchemas = $tableSchema !== null ? $tableSchema->getColumns() : [];
402 282
        $names = [];
403 282
        $placeholders = [];
404
        $values = ' DEFAULT VALUES';
405 282
406 69
        if ($columns instanceof Query) {
407
            [$names, $values, $params] = $this->prepareInsertSelectSubQuery($columns, $schema, $params);
408 222
        } else {
409 217
            foreach ($columns as $name => $value) {
410 217
                $names[] = $schema->quoteColumnName($name);
411
                $value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
412 217
413 43
                if ($value instanceof ExpressionInterface) {
414 211
                    $placeholders[] = $this->buildExpression($value, $params);
415
                } elseif ($value instanceof Query) {
416
                    [$sql, $params] = $this->build($value, $params);
417
                    $placeholders[] = "($sql)";
418 211
                } else {
419
                    $placeholders[] = $this->bindParam($value, $params);
420
                }
421
            }
422
        }
423 267
424
        return [$names, $placeholders, $values, $params];
425
    }
426
427
    /**
428
     * Prepare select-subquery and field names for INSERT INTO ... SELECT SQL statement.
429
     *
430
     * @param Query $columns Object, which represents select query.
431
     * @param Schema $schema Schema object to quote column name.
432
     * @param array $params the parameters to be bound to the generated SQL statement. These parameters will be included
433
     * in the result with the additional parameters generated during the query building process.
434
     *
435
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException
436
     *
437
     * @return array array of column names, values and params.
438 69
     */
439
    protected function prepareInsertSelectSubQuery(Query $columns, Schema $schema, array $params = []): array
440
    {
441 69
        if (
442 69
            !is_array($columns->getSelect())
0 ignored issues
show
introduced by
The condition is_array($columns->getSelect()) is always true.
Loading history...
443 69
            || empty($columns->getSelect())
444
            || in_array('*', $columns->getSelect(), true)
445 15
        ) {
446
            throw new InvalidArgumentException('Expected select query object with enumerated (named) parameters');
447
        }
448 54
449
        [$values, $params] = $this->build($columns, $params);
450 54
451 54
        $names = [];
452
        $values = ' ' . $values;
453 54
454 54
        foreach ($columns->getSelect() as $title => $field) {
455 54
            if (is_string($title)) {
456
                $names[] = $schema->quoteColumnName($title);
457
            } elseif (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_.]+)$/', $field, $matches)) {
458
                $names[] = $schema->quoteColumnName($matches[2]);
459
            } else {
460
                $names[] = $schema->quoteColumnName($field);
461
            }
462
        }
463 54
464
        return [$names, $values, $params];
465
    }
466
467
    /**
468
     * Generates a batch INSERT SQL statement.
469
     *
470
     * For example,
471
     *
472
     * ```php
473
     * $sql = $queryBuilder->batchInsert('user', ['name', 'age'], [
474
     *     ['Tom', 30],
475
     *     ['Jane', 20],
476
     *     ['Linda', 25],
477
     * ]);
478
     * ```
479
     *
480
     * Note that the values in each row must match the corresponding column names.
481
     *
482
     * The method will properly escape the column names, and quote the values to be inserted.
483
     *
484
     * @param string $table the table that new rows will be inserted into.
485
     * @param array $columns the column names.
486
     * @param array|Generator $rows the rows to be batch inserted into the table.
487
     * @param array $params the binding parameters. This parameter exists.
488
     *
489
     * @throws Exception|InvalidArgumentException|JsonException
490
     *
491
     * @return string the batch INSERT SQL statement.
492 40
     */
493
    public function batchInsert(string $table, array $columns, $rows, array &$params = []): string
494 40
    {
495 4
        if (empty($rows)) {
496
            return '';
497
        }
498 38
499
        $schema = $this->db->getSchema();
500
501 38
502 38
        if (($tableSchema = $schema->getTableSchema($table)) !== null) {
503
            $columnSchemas = $tableSchema->getColumns();
504
        } else {
505
            $columnSchemas = [];
506
        }
507 38
508
        $values = [];
509 38
510 35
        foreach ($rows as $row) {
511 35
            $vs = [];
512 35
            foreach ($row as $i => $value) {
513 26
                if (isset($columns[$i], $columnSchemas[$columns[$i]])) {
514
                    $value = $columnSchemas[$columns[$i]]->dbTypecast($value);
515 35
                }
516 23
                if (is_string($value)) {
517 21
                    $value = $schema->quoteValue($value);
518
                } elseif (is_float($value)) {
519 2
                    /* ensure type cast always has . as decimal separator in all locales */
520 21
                    $value = NumericHelper::normalize((string) $value);
521 7
                } elseif ($value === false) {
522 21
                    $value = 0;
523 12
                } elseif ($value === null) {
524 13
                    $value = 'NULL';
525 9
                } elseif ($value instanceof ExpressionInterface) {
526
                    $value = $this->buildExpression($value, $params);
527 35
                }
528
                $vs[] = $value;
529 35
            }
530
            $values[] = '(' . implode(', ', $vs) . ')';
531
        }
532 38
533 3
        if (empty($values)) {
534
            return '';
535
        }
536 35
537 32
        foreach ($columns as $i => $name) {
538
            $columns[$i] = $schema->quoteColumnName($name);
539
        }
540 35
541 35
        return 'INSERT INTO ' . $schema->quoteTableName($table)
542
            . ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values);
543
    }
544
545
    /**
546
     * Creates an SQL statement to insert rows into a database table if they do not already exist (matching unique
547
     * constraints), or update them if they do.
548
     *
549
     * For example,
550
     *
551
     * ```php
552
     * $sql = $queryBuilder->upsert('pages', [
553
     *     'name' => 'Front page',
554
     *     'url' => 'http://example.com/', // url is unique
555
     *     'visits' => 0,
556
     * ], [
557
     *     'visits' => new \Yiisoft\Db\Expression('visits + 1'),
558
     * ], $params);
559
     * ```
560
     *
561
     * The method will properly escape the table and column names.
562
     *
563
     * @param string $table the table that new rows will be inserted into/updated in.
564
     * @param array|Query $insertColumns the column data (name => value) to be inserted into the table or instance
565
     * of {@see Query} to perform `INSERT INTO ... SELECT` SQL statement.
566
     * @param array|bool $updateColumns the column data (name => value) to be updated if they already exist.
567
     * If `true` is passed, the column data will be updated to match the insert column data.
568
     * If `false` is passed, no update will be performed if the column data already exists.
569
     * @param array $params the binding parameters that will be generated by this method. They should be bound to the DB
570
     * command later.
571
     *
572
     * @throws Exception|NotSupportedException if this is not supported by the underlying DBMS.
573
     *
574
     * @return string the resulting SQL.
575
     */
576
    public function upsert(string $table, $insertColumns, $updateColumns, array &$params): string
577
    {
578
        throw new NotSupportedException($this->db->getDriverName() . ' does not support upsert statements.');
579
    }
580
581
    /**
582
     * @param string $table
583
     * @param array|Query $insertColumns
584
     * @param array|bool $updateColumns
585
     * @param Constraint[] $constraints this parameter recieves a matched constraint list.
586
     * The constraints will be unique by their column names.
587
     *
588
     * @throws Exception|JsonException
589
     *
590
     * @return array
591 89
     */
592
    protected function prepareUpsertColumns(string $table, $insertColumns, $updateColumns, array &$constraints = []): array
593 89
    {
594 40
        if ($insertColumns instanceof Query) {
595
            [$insertNames] = $this->prepareInsertSelectSubQuery($insertColumns, $this->db->getSchema());
596
        } else {
597 49
            /** @psalm-suppress UndefinedMethod */
598
            $insertNames = array_map([$this->db, 'quoteColumnName'], array_keys($insertColumns));
599
        }
600 89
601
        $uniqueNames = $this->getTableUniqueColumnNames($table, $insertNames, $constraints);
602
603 89
        /** @psalm-suppress UndefinedMethod */
604
        $uniqueNames = array_map([$this->db, 'quoteColumnName'], $uniqueNames);
605 89
606 64
        if ($updateColumns !== true) {
607
            return [$uniqueNames, $insertNames, null];
608
        }
609 25
610
        return [$uniqueNames, $insertNames, array_diff($insertNames, $uniqueNames)];
611
    }
612
613
    /**
614
     * Returns all column names belonging to constraints enforcing uniqueness (`PRIMARY KEY`, `UNIQUE INDEX`, etc.)
615
     * for the named table removing constraints which did not cover the specified column list.
616
     *
617
     * The column list will be unique by column names.
618
     *
619
     * @param string $name table name. The table name may contain schema name if any. Do not quote the table name.
620
     * @param string[] $columns source column list.
621
     * @param Constraint[] $constraints this parameter optionally recieves a matched constraint list. The constraints
622
     * will be unique by their column names.
623
     *
624
     * @throws JsonException
625
     *
626
     * @return array column list.
627 89
     */
628
    private function getTableUniqueColumnNames(string $name, array $columns, array &$constraints = []): array
629 89
    {
630
        $schema = $this->db->getSchema();
631 89
632
        if (!$schema instanceof ConstraintFinderInterface) {
633
            return [];
634
        }
635 89
636 89
        $constraints = [];
637
        $primaryKey = $schema->getTablePrimaryKey($name);
638 89
639 88
        if ($primaryKey !== null) {
640
            $constraints[] = $primaryKey;
641
        }
642 89
643 88
        foreach ($schema->getTableIndexes($name) as $constraint) {
644 88
            if ($constraint->isUnique()) {
645
                $constraints[] = $constraint;
646
            }
647
        }
648 89
649
        $constraints = array_merge($constraints, $schema->getTableUniques($name));
650
651 89
        /** Remove duplicates */
652 89
        $constraints = array_combine(
653 89
            array_map(
654 89
                static function ($constraint) {
655 89
                    $columns = $constraint->getColumnNames();
656
                    sort($columns, SORT_STRING);
657 89
658
                    return json_encode($columns, JSON_THROW_ON_ERROR);
659 89
                },
660
                $constraints
661 89
            ),
662
            $constraints
663
        );
664 89
665
        $columnNames = [];
666
667 89
        /** Remove all constraints which do not cover the specified column list */
668 89
        $constraints = array_values(
669 89
            array_filter(
670 89
                $constraints,
671
                static function ($constraint) use ($schema, $columns, &$columnNames) {
672 89
                    /** @psalm-suppress UndefinedClass, UndefinedMethod */
673 89
                    $constraintColumnNames = array_map([$schema, 'quoteColumnName'], $constraint->getColumnNames());
674
                    $result = !array_diff($constraintColumnNames, $columns);
675 89
676 74
                    if ($result) {
677
                        $columnNames = array_merge($columnNames, $constraintColumnNames);
678
                    }
679 89
680 89
                    return $result;
681
                }
682
            )
683
        );
684 89
685
        return array_unique($columnNames);
686
    }
687
688
    /**
689
     * Creates an UPDATE SQL statement.
690
     *
691
     * For example,
692
     *
693
     * ```php
694
     * $params = [];
695
     * $sql = $queryBuilder->update('user', ['status' => 1], 'age > 30', $params);
696
     * ```
697
     *
698
     * The method will properly escape the table and column names.
699
     *
700
     * @param string $table the table to be updated.
701
     * @param array $columns the column data (name => value) to be updated.
702
     * @param array|string $condition the condition that will be put in the WHERE part. Please refer to
703
     * {@see Query::where()} on how to specify condition.
704
     * @param array $params the binding parameters that will be modified by this method so that they can be bound to the
705
     * DB command later.
706
     *
707
     * @throws Exception|InvalidArgumentException|JsonException
708
     *
709
     * @return string the UPDATE SQL.
710 94
     */
711
    public function update(string $table, array $columns, $condition, array &$params = []): string
712 94
    {
713 94
        [$lines, $params] = $this->prepareUpdateSets($table, $columns, $params);
714 94
        $sql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $lines);
715
        $where = $this->buildWhere($condition, $params);
716 94
717
        return ($where === '') ? $sql : ($sql . ' ' . $where);
718
    }
719
720
    /**
721
     * Prepares a `SET` parts for an `UPDATE` SQL statement.
722
     *
723
     * @param string $table the table to be updated.
724
     * @param array $columns the column data (name => value) to be updated.
725
     * @param array $params the binding parameters that will be modified by this method so that they can be bound to the
726
     * DB command later.
727
     *
728
     * @throws Exception|InvalidArgumentException|JsonException
729
     *
730
     * @return array an array `SET` parts for an `UPDATE` SQL statement (the first array element) and params (the second
731
     * array element).
732 139
     */
733
    protected function prepareUpdateSets(string $table, array $columns, array $params = []): array
734 139
    {
735
        $tableSchema = $this->db->getTableSchema($table);
736 139
737
        $columnSchemas = $tableSchema !== null ? $tableSchema->getColumns() : [];
738 139
739
        $sets = [];
740 139
741 139
        foreach ($columns as $name => $value) {
742 139
            $value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
743 69
            if ($value instanceof ExpressionInterface) {
744
                $placeholder = $this->buildExpression($value, $params);
745 96
            } else {
746
                $placeholder = $this->bindParam($value, $params);
747
            }
748 139
749
            $sets[] = $this->db->quoteColumnName($name) . '=' . $placeholder;
750
        }
751 139
752
        return [$sets, $params];
753
    }
754
755
    /**
756
     * Creates a DELETE SQL statement.
757
     *
758
     * For example,
759
     *
760
     * ```php
761
     * $sql = $queryBuilder->delete('user', 'status = 0');
762
     * ```
763
     *
764
     * The method will properly escape the table and column names.
765
     *
766
     * @param string $table the table where the data will be deleted from.
767
     * @param array|string $condition the condition that will be put in the WHERE part. Please refer to
768
     * {@see Query::where()} on how to specify condition.
769
     * @param array $params the binding parameters that will be modified by this method so that they can be bound to the
770
     * DB command later.
771
     *
772
     * @throws Exception|InvalidArgumentException
773
     *
774
     * @return string the DELETE SQL.
775 41
     */
776
    public function delete(string $table, $condition, array &$params): string
777 41
    {
778 41
        $sql = 'DELETE FROM ' . $this->db->quoteTableName($table);
779
        $where = $this->buildWhere($condition, $params);
780 41
781
        return ($where === '') ? $sql : ($sql . ' ' . $where);
782
    }
783
784
    /**
785
     * Builds a SQL statement for creating a new DB table.
786
     *
787
     * The columns in the new  table should be specified as name-definition pairs (e.g. 'name' => 'string'), where name
788
     * stands for a column name which will be properly quoted by the method, and definition stands for the column type
789
     * which can contain an abstract DB type.
790
     *
791
     * The {@see getColumnType()} method will be invoked to convert any abstract type into a physical one.
792
     *
793
     * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly inserted
794
     * into the generated SQL.
795
     *
796
     * For example,
797
     *
798
     * ```php
799
     * $sql = $queryBuilder->createTable('user', [
800
     *  'id' => 'pk',
801
     *  'name' => 'string',
802
     *  'age' => 'integer',
803
     * ]);
804
     * ```
805
     *
806
     * @param string $table the name of the table to be created. The name will be properly quoted by the method.
807
     * @param array $columns the columns (name => definition) in the new table.
808
     * @param string|null $options additional SQL fragment that will be appended to the generated SQL.
809
     *
810
     * @return string the SQL statement for creating a new DB table.
811 60
     */
812
    public function createTable(string $table, array $columns, ?string $options = null): string
813 60
    {
814 60
        $cols = [];
815 60
        foreach ($columns as $name => $type) {
816 60
            if (is_string($name)) {
817
                $cols[] = "\t" . $this->db->quoteColumnName($name) . ' ' . $this->getColumnType($type);
818 5
            } else {
819
                $cols[] = "\t" . $type;
820
            }
821
        }
822 60
823
        $sql = 'CREATE TABLE ' . $this->db->quoteTableName($table) . " (\n" . implode(",\n", $cols) . "\n)";
824 60
825
        return ($options === null) ? $sql : ($sql . ' ' . $options);
826
    }
827
828
    /**
829
     * Builds a SQL statement for renaming a DB table.
830
     *
831
     * @param string $oldName the table to be renamed. The name will be properly quoted by the method.
832
     * @param string $newName the new table name. The name will be properly quoted by the method.
833
     *
834
     * @return string the SQL statement for renaming a DB table.
835 2
     */
836
    public function renameTable(string $oldName, string $newName): string
837 2
    {
838
        return 'RENAME TABLE ' . $this->db->quoteTableName($oldName) . ' TO ' . $this->db->quoteTableName($newName);
839
    }
840
841
    /**
842
     * Builds a SQL statement for dropping a DB table.
843
     *
844
     * @param string $table the table to be dropped. The name will be properly quoted by the method.
845
     *
846
     * @return string the SQL statement for dropping a DB table.
847 9
     */
848
    public function dropTable(string $table): string
849 9
    {
850
        return 'DROP TABLE ' . $this->db->quoteTableName($table);
851
    }
852
853
    /**
854
     * Builds a SQL statement for adding a primary key constraint to an existing table.
855
     *
856
     * @param string $name the name of the primary key constraint.
857
     * @param string $table the table that the primary key constraint will be added to.
858
     * @param array|string $columns comma separated string or array of columns that the primary key will consist of.
859
     *
860
     * @return string the SQL statement for adding a primary key constraint to an existing table.
861 11
     */
862
    public function addPrimaryKey(string $name, string $table, $columns): string
863 11
    {
864 8
        if (is_string($columns)) {
865
            $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
866
        }
867 11
868 11
        foreach ($columns as $i => $col) {
869
            $columns[$i] = $this->db->quoteColumnName($col);
870
        }
871 11
872 11
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
873 11
            . $this->db->quoteColumnName($name) . ' PRIMARY KEY ('
874
            . implode(', ', $columns) . ')';
875
    }
876
877
    /**
878
     * Builds a SQL statement for removing a primary key constraint to an existing table.
879
     *
880
     * @param string $name the name of the primary key constraint to be removed.
881
     * @param string $table the table that the primary key constraint will be removed from.
882
     *
883
     * @return string the SQL statement for removing a primary key constraint from an existing table.
884 5
     */
885
    public function dropPrimaryKey(string $name, string $table): string
886 5
    {
887 5
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
888
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
889
    }
890
891
    /**
892
     * Builds a SQL statement for truncating a DB table.
893
     *
894
     * @param string $table the table to be truncated. The name will be properly quoted by the method.
895
     *
896
     * @return string the SQL statement for truncating a DB table.
897 3
     */
898
    public function truncateTable(string $table): string
899 3
    {
900
        return 'TRUNCATE TABLE ' . $this->db->quoteTableName($table);
901
    }
902
903
    /**
904
     * Builds a SQL statement for adding a new DB column.
905
     *
906
     * @param string $table the table that the new column will be added to. The table name will be properly quoted by
907
     * the method.
908
     * @param string $column the name of the new column. The name will be properly quoted by the method.
909
     * @param string $type the column type. The {@see getColumnType()} method will be invoked to convert abstract column
910
     * type (if any) into the physical one. Anything that is not recognized as abstract type will be kept in the
911
     * generated SQL.
912
     * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become
913
     * 'varchar(255) not null'.
914
     *
915
     * @return string the SQL statement for adding a new column.
916 2
     */
917
    public function addColumn(string $table, string $column, string $type): string
918 2
    {
919 2
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
920 2
            . ' ADD ' . $this->db->quoteColumnName($column) . ' '
921
            . $this->getColumnType($type);
922
    }
923
924
    /**
925
     * Builds a SQL statement for dropping a DB column.
926
     *
927
     * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
928
     * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
929
     *
930
     * @return string the SQL statement for dropping a DB column.
931
     */
932
    public function dropColumn(string $table, string $column): string
933
    {
934
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
935
            . ' DROP COLUMN ' . $this->db->quoteColumnName($column);
936
    }
937
938
    /**
939
     * Builds a SQL statement for renaming a column.
940
     *
941
     * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
942
     * @param string $oldName the old name of the column. The name will be properly quoted by the method.
943
     * @param string $newName the new name of the column. The name will be properly quoted by the method.
944
     *
945
     * @return string the SQL statement for renaming a DB column.
946
     */
947
    public function renameColumn(string $table, string $oldName, string $newName): string
948
    {
949
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
950
            . ' RENAME COLUMN ' . $this->db->quoteColumnName($oldName)
951
            . ' TO ' . $this->db->quoteColumnName($newName);
952
    }
953
954
    /**
955
     * Builds a SQL statement for changing the definition of a column.
956
     *
957
     * @param string $table the table whose column is to be changed. The table name will be properly quoted by the
958
     * method.
959
     * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
960
     * @param string $type the new column type. The {@see getColumnType()} method will be invoked to convert abstract
961
     * column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept
962
     * in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null'
963
     * will become 'varchar(255) not null'.
964
     *
965
     * @return string the SQL statement for changing the definition of a column.
966 1
     */
967
    public function alterColumn(string $table, string $column, string $type): string
968 1
    {
969 1
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
970 1
            . $this->db->quoteColumnName($column) . ' '
971 1
            . $this->db->quoteColumnName($column) . ' '
972
            . $this->getColumnType($type);
973
    }
974
975
    /**
976
     * Builds a SQL statement for adding a foreign key constraint to an existing table. The method will properly quote
977
     * the table and column names.
978
     *
979
     * @param string $name the name of the foreign key constraint.
980
     * @param string $table the table that the foreign key constraint will be added to.
981
     * @param array|string $columns the name of the column to that the constraint will be added on. If there are
982
     * multiple columns, separate them with commas or use an array to represent them.
983
     * @param string $refTable the table that the foreign key references to.
984
     * @param array|string $refColumns the name of the column that the foreign key references to. If there are multiple
985
     * columns, separate them with commas or use an array to represent them.
986
     * @param string|null $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION,
987
     * SET DEFAULT, SET NULL.
988
     * @param string|null $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION,
989
     * SET DEFAULT, SET NULL.
990
     *
991
     * @throws Exception|InvalidArgumentException
992
     *
993
     * @return string the SQL statement for adding a foreign key constraint to an existing table.
994 9
     */
995
    public function addForeignKey(
996
        string $name,
997
        string $table,
998
        $columns,
999
        string $refTable,
1000
        $refColumns,
1001
        ?string $delete = null,
1002
        ?string $update = null
1003 9
    ): string {
1004 9
        $sql = 'ALTER TABLE ' . $this->db->quoteTableName($table)
1005 9
            . ' ADD CONSTRAINT ' . $this->db->quoteColumnName($name)
1006 9
            . ' FOREIGN KEY (' . $this->buildColumns($columns) . ')'
1007 9
            . ' REFERENCES ' . $this->db->quoteTableName($refTable)
1008
            . ' (' . $this->buildColumns($refColumns) . ')';
1009 9
1010 6
        if ($delete !== null) {
1011
            $sql .= ' ON DELETE ' . $delete;
1012
        }
1013 9
1014 6
        if ($update !== null) {
1015
            $sql .= ' ON UPDATE ' . $update;
1016
        }
1017 9
1018
        return $sql;
1019
    }
1020
1021
    /**
1022
     * Builds a SQL statement for dropping a foreign key constraint.
1023
     *
1024
     * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by
1025
     * the method.
1026
     * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
1027
     *
1028
     * @return string the SQL statement for dropping a foreign key constraint.
1029 7
     */
1030
    public function dropForeignKey(string $name, string $table): string
1031 7
    {
1032 7
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
1033
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
1034
    }
1035
1036
    /**
1037
     * Builds a SQL statement for creating a new index.
1038
     *
1039
     * @param string $name the name of the index. The name will be properly quoted by the method.
1040
     * @param string $table the table that the new index will be created for. The table name will be properly quoted by
1041
     * the method.
1042
     * @param array|string $columns the column(s) that should be included in the index. If there are multiple columns,
1043
     * separate them with commas or use an array to represent them. Each column name will be properly quoted by the
1044
     * method, unless a parenthesis is found in the name.
1045
     * @param bool $unique whether to add UNIQUE constraint on the created index.
1046
     *
1047
     * @throws Exception|InvalidArgumentException
1048
     *
1049
     * @return string the SQL statement for creating a new index.
1050 11
     */
1051
    public function createIndex(string $name, string $table, $columns, bool $unique = false): string
1052 11
    {
1053 11
        return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
1054 11
            . $this->db->quoteTableName($name) . ' ON '
1055 11
            . $this->db->quoteTableName($table)
1056
            . ' (' . $this->buildColumns($columns) . ')';
1057
    }
1058
1059
    /**
1060
     * Builds a SQL statement for dropping an index.
1061
     *
1062
     * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
1063
     * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
1064
     *
1065
     * @return string the SQL statement for dropping an index.
1066 6
     */
1067
    public function dropIndex(string $name, string $table): string
1068 6
    {
1069
        return 'DROP INDEX ' . $this->db->quoteTableName($name) . ' ON ' . $this->db->quoteTableName($table);
1070
    }
1071
1072
    /**
1073
     * Creates a SQL command for adding an unique constraint to an existing table.
1074
     *
1075
     * @param string $name the name of the unique constraint. The name will be properly quoted by the method.
1076
     * @param string $table the table that the unique constraint will be added to. The name will be properly quoted by
1077
     * the method.
1078
     * @param array|string $columns the name of the column to that the constraint will be added on. If there are
1079
     * multiple columns, separate them with commas. The name will be properly quoted by the method.
1080
     *
1081
     * @return string the SQL statement for adding an unique constraint to an existing table.
1082 12
     */
1083
    public function addUnique(string $name, string $table, $columns): string
1084 12
    {
1085 8
        if (is_string($columns)) {
1086
            $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
1087 12
        }
1088 12
        foreach ($columns as $i => $col) {
1089
            $columns[$i] = $this->db->quoteColumnName($col);
1090
        }
1091 12
1092 12
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
1093 12
            . $this->db->quoteColumnName($name) . ' UNIQUE ('
1094
            . implode(', ', $columns) . ')';
1095
    }
1096
1097
    /**
1098
     * Creates a SQL command for dropping an unique constraint.
1099
     *
1100
     * @param string $name the name of the unique constraint to be dropped. The name will be properly quoted by the
1101
     * method.
1102
     * @param string $table the table whose unique constraint is to be dropped. The name will be properly quoted by the
1103
     * method.
1104
     *
1105
     * @return string the SQL statement for dropping an unique constraint.
1106 6
     */
1107
    public function dropUnique(string $name, string $table): string
1108 6
    {
1109 6
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
1110
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
1111
    }
1112
1113
    /**
1114
     * Creates a SQL command for adding a check constraint to an existing table.
1115
     *
1116
     * @param string $name the name of the check constraint. The name will be properly quoted by the method.
1117
     * @param string $table the table that the check constraint will be added to. The name will be properly quoted by
1118
     * the method.
1119
     * @param string $expression the SQL of the `CHECK` constraint.
1120
     *
1121
     * @return string the SQL statement for adding a check constraint to an existing table.
1122 6
     */
1123
    public function addCheck(string $name, string $table, string $expression): string
1124 6
    {
1125 6
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
1126
            . $this->db->quoteColumnName($name) . ' CHECK (' . $this->db->quoteSql($expression) . ')';
1127
    }
1128
1129
    /**
1130
     * Creates a SQL command for dropping a check constraint.
1131
     *
1132
     * @param string $name the name of the check constraint to be dropped. The name will be properly quoted by the
1133
     * method.
1134
     * @param string $table the table whose check constraint is to be dropped. The name will be properly quoted by the
1135
     * method.
1136
     *
1137
     * @return string the SQL statement for dropping a check constraint.
1138 6
     */
1139
    public function dropCheck(string $name, string $table): string
1140 6
    {
1141 6
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
1142
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
1143
    }
1144
1145
    /**
1146
     * Creates a SQL command for adding a default value constraint to an existing table.
1147
     *
1148
     * @param string $name the name of the default value constraint.
1149
     * The name will be properly quoted by the method.
1150
     * @param string $table the table that the default value constraint will be added to.
1151
     * The name will be properly quoted by the method.
1152
     * @param string $column the name of the column to that the constraint will be added on.
1153
     * The name will be properly quoted by the method.
1154
     * @param mixed $value default value.
1155
     *
1156
     * @throws Exception|NotSupportedException if this is not supported by the underlying DBMS.
1157
     *
1158
     * @return string the SQL statement for adding a default value constraint to an existing table.
1159
     */
1160
    public function addDefaultValue(string $name, string $table, string $column, $value): string
1161
    {
1162
        throw new NotSupportedException(
1163
            $this->db->getDriverName() . ' does not support adding default value constraints.'
1164
        );
1165
    }
1166
1167
    /**
1168
     * Creates a SQL command for dropping a default value constraint.
1169
     *
1170
     * @param string $name the name of the default value constraint to be dropped.
1171
     * The name will be properly quoted by the method.
1172
     * @param string $table the table whose default value constraint is to be dropped.
1173
     * The name will be properly quoted by the method.
1174
     *
1175
     * @throws Exception|NotSupportedException if this is not supported by the underlying DBMS.
1176
     *
1177
     * @return string the SQL statement for dropping a default value constraint.
1178
     */
1179
    public function dropDefaultValue(string $name, string $table): string
1180
    {
1181
        throw new NotSupportedException(
1182
            $this->db->getDriverName() . ' does not support dropping default value constraints.'
1183
        );
1184
    }
1185
1186
    /**
1187
     * Creates a SQL statement for resetting the sequence value of a table's primary key.
1188
     *
1189
     * The sequence will be reset such that the primary key of the next new row inserted will have the specified value
1190
     * or 1.
1191
     *
1192
     * @param string $tableName the name of the table whose primary key sequence will be reset.
1193
     * @param array|string|null $value the value for the primary key of the next new row inserted. If this is not set,
1194
     * the next new row's primary key will have a value 1.
1195
     *
1196
     * @throws Exception|NotSupportedException if this is not supported by the underlying DBMS.
1197
     *
1198
     * @return string the SQL statement for resetting sequence.
1199
     */
1200
    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

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

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

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