Passed
Push — master ( 2a9aa3...e9c192 )
by Alexander
01:53
created

QueryBuilder   F

Complexity

Total Complexity 76

Size/Duplication

Total Lines 703
Duplicated Lines 0 %

Test Coverage

Coverage 61.63%

Importance

Changes 0
Metric Value
eloc 246
c 0
b 0
f 0
dl 0
loc 703
ccs 135
cts 219
cp 0.6163
rs 2.32
wmc 76

16 Methods

Rating   Name   Duplication   Size   Complexity  
A createIndex() 0 15 5
A insert() 0 3 1
A defaultExpressionBuilders() 0 5 1
A defaultConditionClasses() 0 7 1
B normalizeTableRowData() 0 21 7
A resetSequence() 0 25 5
A checkIntegrity() 0 21 5
C batchInsert() 0 52 14
A newUpsert() 0 29 6
A update() 0 3 1
A dropIndex() 0 18 5
A truncateTable() 0 3 1
A upsert() 0 12 3
C oldUpsert() 0 102 14
A renameTable() 0 4 1
B alterColumn() 0 52 6

How to fix   Complexity   

Complex Class

Complex classes like QueryBuilder often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use QueryBuilder, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Pgsql;
6
7
use JsonException;
8
use PDO;
9
use Generator;
10
use Yiisoft\Db\Connection\ConnectionInterface;
11
use Yiisoft\Db\Constraint\Constraint;
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\ArrayExpression;
17
use Yiisoft\Db\Expression\Expression;
18
use Yiisoft\Db\Expression\ExpressionInterface;
19
use Yiisoft\Db\Expression\JsonExpression;
20
use Yiisoft\Db\Pdo\PdoValue;
21
use Yiisoft\Db\Query\Conditions\LikeCondition;
22
use Yiisoft\Db\Query\Query;
23
use Yiisoft\Db\Query\QueryBuilder as AbstractQueryBuilder;
24
use Yiisoft\Strings\NumericHelper;
25
26
use function array_diff;
27
use function array_merge;
28
use function array_unshift;
29
use function count;
30
use function explode;
31
use function implode;
32
use function is_bool;
33
use function is_float;
34
use function is_string;
35
use function preg_match;
36
use function preg_replace;
37
use function reset;
38
use function strpos;
39
use function strrpos;
40
use function version_compare;
41
42
final class QueryBuilder extends AbstractQueryBuilder
43
{
44
    /**
45
     * Defines a UNIQUE index for {@see createIndex()}.
46
     */
47
    public const INDEX_UNIQUE = 'unique';
48
49
    /**
50
     * Defines a B-tree index for {@see createIndex()}.
51
     */
52
    public const INDEX_B_TREE = 'btree';
53
54
    /**
55
     * Defines a hash index for {@see createIndex()}.
56
     */
57
    public const INDEX_HASH = 'hash';
58
59
    /**
60
     * Defines a GiST index for {@see createIndex()}.
61
     */
62
    public const INDEX_GIST = 'gist';
63
64
    /**
65
     * Defines a GIN index for {@see createIndex()}.
66
     */
67
    public const INDEX_GIN = 'gin';
68
69
    /**
70
     * @var array mapping from abstract column types (keys) to physical column types (values).
71
     */
72
    protected array $typeMap = [
73
        Schema::TYPE_PK => 'serial NOT NULL PRIMARY KEY',
74
        Schema::TYPE_UPK => 'serial NOT NULL PRIMARY KEY',
75
        Schema::TYPE_BIGPK => 'bigserial NOT NULL PRIMARY KEY',
76
        Schema::TYPE_UBIGPK => 'bigserial NOT NULL PRIMARY KEY',
77
        Schema::TYPE_CHAR => 'char(1)',
78
        Schema::TYPE_STRING => 'varchar(255)',
79
        Schema::TYPE_TEXT => 'text',
80
        Schema::TYPE_TINYINT => 'smallint',
81
        Schema::TYPE_SMALLINT => 'smallint',
82
        Schema::TYPE_INTEGER => 'integer',
83
        Schema::TYPE_BIGINT => 'bigint',
84
        Schema::TYPE_FLOAT => 'double precision',
85
        Schema::TYPE_DOUBLE => 'double precision',
86
        Schema::TYPE_DECIMAL => 'numeric(10,0)',
87
        Schema::TYPE_DATETIME => 'timestamp(0)',
88
        Schema::TYPE_TIMESTAMP => 'timestamp(0)',
89
        Schema::TYPE_TIME => 'time(0)',
90
        Schema::TYPE_DATE => 'date',
91
        Schema::TYPE_BINARY => 'bytea',
92
        Schema::TYPE_BOOLEAN => 'boolean',
93
        Schema::TYPE_MONEY => 'numeric(19,4)',
94
        Schema::TYPE_JSON => 'jsonb',
95
    ];
96
97
    /**
98
     * Contains array of default condition classes. Extend this method, if you want to change default condition classes
99
     * for the query builder.
100
     *
101
     * @return array
102
     *
103
     * See {@see conditionClasses} docs for details.
104
     */
105 306
    protected function defaultConditionClasses(): array
106
    {
107 306
        return array_merge(parent::defaultConditionClasses(), [
108 306
            'ILIKE' => LikeCondition::class,
109
            'NOT ILIKE' => LikeCondition::class,
110
            'OR ILIKE' => LikeCondition::class,
111
            'OR NOT ILIKE' => LikeCondition::class,
112
        ]);
113
    }
114
115
    /**
116
     * Contains array of default expression builders. Extend this method and override it, if you want to change default
117
     * expression builders for this query builder.
118
     *
119
     * @return array
120
     *
121
     * See {@see ExpressionBuilder} docs for details.
122
     */
123 306
    protected function defaultExpressionBuilders(): array
124
    {
125 306
        return array_merge(parent::defaultExpressionBuilders(), [
126 306
            ArrayExpression::class => ArrayExpressionBuilder::class,
127
            JsonExpression::class => JsonExpressionBuilder::class,
128
        ]);
129
    }
130
131
    /**
132
     * Builds a SQL statement for creating a new index.
133
     *
134
     * @param string $name the name of the index. The name will be properly quoted by the method.
135
     * @param string $table the table that the new index will be created for. The table name will be properly quoted by
136
     * the method.
137
     * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns,
138
     * separate them with commas or use an array to represent them. Each column name will be properly quoted by the
139
     * method, unless a parenthesis is found in the name.
140
     * @param bool|string $unique whether to make this a UNIQUE index constraint. You can pass `true` or
141
     * {@see INDEX_UNIQUE} to create a unique index, `false` to make a non-unique index using the default index type, or
142
     * one of the following constants to specify the index method to use: {@see INDEX_B_TREE}, {@see INDEX_HASH},
143
     * {@see INDEX_GIST}, {@see INDEX_GIN}.
144
     *
145
     * @throws Exception|InvalidArgumentException
146
     *
147
     * @return string the SQL statement for creating a new index.
148
     *
149
     * {@see http://www.postgresql.org/docs/8.2/static/sql-createindex.html}
150
     */
151 5
    public function createIndex(string $name, string $table, $columns, $unique = false): string
152
    {
153 5
        if ($unique === self::INDEX_UNIQUE || $unique === true) {
154 3
            $index = false;
155 3
            $unique = true;
156
        } else {
157 3
            $index = $unique;
158 3
            $unique = false;
159
        }
160
161 5
        return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
162 5
            . $this->getDb()->quoteTableName($name) . ' ON '
163 5
            . $this->getDb()->quoteTableName($table)
164 5
            . ($index !== false ? " USING $index" : '')
165 5
            . ' (' . $this->buildColumns($columns) . ')';
166
    }
167
168
    /**
169
     * Builds a SQL statement for dropping an index.
170
     *
171
     * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
172
     * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
173
     *
174
     * @return string the SQL statement for dropping an index.
175
     */
176 3
    public function dropIndex(string $name, string $table): string
177
    {
178 3
        if (strpos($table, '.') !== false && strpos($name, '.') === false) {
179 1
            if (strpos($table, '{{') !== false) {
180 1
                $table = preg_replace('/{{(.*?)}}/', '\1', $table);
181 1
                [$schema, $table] = explode('.', $table);
182 1
                if (strpos($schema, '%') === false) {
183 1
                    $name = $schema . '.' . $name;
184
                } else {
185 1
                    $name = '{{' . $schema . '.' . $name . '}}';
186
                }
187
            } else {
188
                [$schema] = explode('.', $table);
189
                $name = $schema . '.' . $name;
190
            }
191
        }
192
193 3
        return 'DROP INDEX ' . $this->getDb()->quoteTableName($name);
194
    }
195
196
    /**
197
     * Builds a SQL statement for renaming a DB table.
198
     *
199
     * @param string $oldName the table to be renamed. The name will be properly quoted by the method.
200
     * @param string $newName the new table name. The name will be properly quoted by the method.
201
     *
202
     * @return string the SQL statement for renaming a DB table.
203
     */
204 2
    public function renameTable(string $oldName, string $newName): string
205
    {
206 2
        return 'ALTER TABLE ' . $this->getDb()->quoteTableName($oldName) . ' RENAME TO '
207 2
            . $this->getDb()->quoteTableName($newName);
208
    }
209
210
    /**
211
     * Creates a SQL statement for resetting the sequence value of a table's primary key.
212
     *
213
     * The sequence will be reset such that the primary key of the next new row inserted will have the specified value
214
     * or 1.
215
     *
216
     * @param string $tableName the name of the table whose primary key sequence will be reset.
217
     * @param mixed $value the value for the primary key of the next new row inserted. If this is not set, the next new
218
     * row's primary key will have a value 1.
219
     *
220
     * @throws Exception|InvalidArgumentException if the table does not exist or there is no sequence associated with
221
     * the table.
222
     *
223
     * @return string the SQL statement for resetting sequence.
224
     */
225 2
    public function resetSequence(string $tableName, $value = null): string
226
    {
227 2
        $table = $this->getDb()->getTableSchema($tableName);
228 2
        if ($table !== null && $table->getSequenceName() !== null) {
229
            /**
230
             * {@see http://www.postgresql.org/docs/8.1/static/functions-sequence.html}
231
             */
232 2
            $sequence = $this->getDb()->quoteTableName($table->getSequenceName());
233 2
            $tableName = $this->getDb()->quoteTableName($tableName);
234 2
            if ($value === null) {
235 2
                $pk = $table->getPrimaryKey();
236 2
                $key = $this->getDb()->quoteColumnName(reset($pk));
237 2
                $value = "(SELECT COALESCE(MAX({$key}),0) FROM {$tableName})+1";
238
            } else {
239 2
                $value = (int) $value;
240
            }
241
242 2
            return "SELECT SETVAL('$sequence',$value,false)";
243
        }
244
245
        if ($table === null) {
246
            throw new InvalidArgumentException("Table not found: $tableName");
247
        }
248
249
        throw new InvalidArgumentException("There is not sequence associated with table '$tableName'.");
250
    }
251
252
    /**
253
     * Builds a SQL statement for enabling or disabling integrity check.
254
     *
255
     * @param string $schema the schema of the tables.
256
     * @param string $table the table name.
257
     * @param bool $check whether to turn on or off the integrity check.
258
     *
259
     * @return string the SQL statement for checking integrity.
260
     */
261
    public function checkIntegrity(string $schema = '', string $table = '', bool $check = true): string
262
    {
263
        /** @psalm-var Connection $db */
264
        $db = $this->getDb();
265
266
        $enable = $check ? 'ENABLE' : 'DISABLE';
267
        $schema = $schema ?: $db->getSchema()->getDefaultSchema();
268
        $tableNames = $table ? [$table] : $db->getSchema()->getTableNames($schema);
0 ignored issues
show
Bug introduced by
It seems like $schema can also be of type null; however, parameter $schema of Yiisoft\Db\Schema\Schema::getTableNames() does only seem to accept string, 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

268
        $tableNames = $table ? [$table] : $db->getSchema()->getTableNames(/** @scrutinizer ignore-type */ $schema);
Loading history...
269
        $viewNames = $db->getSchema()->getViewNames($schema);
270
        $tableNames = array_diff($tableNames, $viewNames);
271
        $command = '';
272
273
        foreach ($tableNames as $tableName) {
274
            $tableName = $db->quoteTableName("{$schema}.{$tableName}");
275
            $command .= "ALTER TABLE $tableName $enable TRIGGER ALL; ";
276
        }
277
278
        /** enable to have ability to alter several tables */
279
        $db->getMasterPdo()->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
280
281
        return $command;
282
    }
283
284
    /**
285
     * Builds a SQL statement for truncating a DB table.
286
     *
287
     * Explicitly restarts identity for PGSQL to be consistent with other databases which all do this by default.
288
     *
289
     * @param string $table the table to be truncated. The name will be properly quoted by the method.
290
     *
291
     * @return string the SQL statement for truncating a DB table.
292
     */
293 1
    public function truncateTable(string $table): string
294
    {
295 1
        return 'TRUNCATE TABLE ' . $this->getDb()->quoteTableName($table) . ' RESTART IDENTITY';
296
    }
297
298
    /**
299
     * Builds a SQL statement for changing the definition of a column.
300
     *
301
     * @param string $table the table whose column is to be changed. The table name will be properly quoted by the
302
     * method.
303
     * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
304
     * @param object|string $type the new column type. The {@see getColumnType()} method will be invoked to convert abstract
305
     * column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept in the
306
     * generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become
307
     * 'varchar(255) not null'. You can also use PostgreSQL-specific syntax such as `SET NOT NULL`.
308
     *
309
     * @return string the SQL statement for changing the definition of a column.
310
     */
311 1
    public function alterColumn(string $table, string $column, $type): string
312
    {
313 1
        $columnName = $this->getDb()->quoteColumnName($column);
314 1
        $tableName = $this->getDb()->quoteTableName($table);
315
316
        /**
317
         * {@see https://github.com/yiisoft/yii2/issues/4492}
318
         * {@see http://www.postgresql.org/docs/9.1/static/sql-altertable.html}
319
         */
320 1
        if (preg_match('/^(DROP|SET|RESET)\s+/i', (string) $type)) {
321 1
            return "ALTER TABLE {$tableName} ALTER COLUMN {$columnName} {$type}";
322
        }
323
324 1
        $type = 'TYPE ' . $this->getColumnType($type);
325 1
        $multiAlterStatement = [];
326 1
        $constraintPrefix = preg_replace('/[^a-z0-9_]/i', '', $table . '_' . $column);
327
328 1
        if (preg_match('/\s+DEFAULT\s+(["\']?\w*["\']?)/i', $type, $matches)) {
329 1
            $type = preg_replace('/\s+DEFAULT\s+(["\']?\w*["\']?)/i', '', $type);
330 1
            $multiAlterStatement[] = "ALTER COLUMN {$columnName} SET DEFAULT {$matches[1]}";
331
        } else {
332
            /** safe to drop default even if there was none in the first place */
333 1
            $multiAlterStatement[] = "ALTER COLUMN {$columnName} DROP DEFAULT";
334
        }
335
336 1
        $type = preg_replace('/\s+NOT\s+NULL/i', '', $type, -1, $count);
337
338 1
        if ($count) {
339 1
            $multiAlterStatement[] = "ALTER COLUMN {$columnName} SET NOT NULL";
340
        } else {
341
            /** remove additional null if any */
342 1
            $type = preg_replace('/\s+NULL/i', '', $type);
343
344
            /** safe to drop not null even if there was none in the first place */
345 1
            $multiAlterStatement[] = "ALTER COLUMN {$columnName} DROP NOT NULL";
346
        }
347
348 1
        if (preg_match('/\s+CHECK\s+\((.+)\)/i', $type, $matches)) {
349 1
            $type = preg_replace('/\s+CHECK\s+\((.+)\)/i', '', $type);
350 1
            $multiAlterStatement[] = "ADD CONSTRAINT {$constraintPrefix}_check CHECK ({$matches[1]})";
351
        }
352
353 1
        $type = preg_replace('/\s+UNIQUE/i', '', $type, -1, $count);
354
355 1
        if ($count) {
356 1
            $multiAlterStatement[] = "ADD UNIQUE ({$columnName})";
357
        }
358
359
        /** add what's left at the beginning */
360 1
        array_unshift($multiAlterStatement, "ALTER COLUMN {$columnName} {$type}");
361
362 1
        return 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $multiAlterStatement);
363
    }
364
365
    /**
366
     * Creates an INSERT SQL statement.
367
     *
368
     * For example,.
369
     *
370
     * ```php
371
     * $sql = $queryBuilder->insert('user', [
372
     *     'name' => 'Sam',
373
     *     'age' => 30,
374
     * ], $params);
375
     * ```
376
     *
377
     * The method will properly escape the table and column names.
378
     *
379
     * @param string $table the table that new rows will be inserted into.
380
     * @param array|Query $columns the column data (name => value) to be inserted into the table or instance of
381
     * {@see Query|Query} to perform INSERT INTO ... SELECT SQL statement. Passing of
382
     * {@see Query|Query}.
383
     * @param array $params the binding parameters that will be generated by this method. They should be bound to the
384
     * DB command later.
385
     *
386
     * @throws Exception
387
     * @throws InvalidArgumentException
388
     * @throws InvalidConfigException
389
     * @throws NotSupportedException
390
     *
391
     * @return string the INSERT SQL
392
     */
393 43
    public function insert(string $table, $columns, array &$params = []): string
394
    {
395 43
        return parent::insert($table, $this->normalizeTableRowData($table, $columns), $params);
396
    }
397
398
    /**
399
     * Creates an SQL statement to insert rows into a database table if they do not already exist (matching unique
400
     * constraints), or update them if they do.
401
     *
402
     * For example,
403
     *
404
     * ```php
405
     * $sql = $queryBuilder->upsert('pages', [
406
     *     'name' => 'Front page',
407
     *     'url' => 'http://example.com/', // url is unique
408
     *     'visits' => 0,
409
     * ], [
410
     *     'visits' => new \Yiisoft\Db\Expression('visits + 1'),
411
     * ], $params);
412
     * ```
413
     *
414
     * The method will properly escape the table and column names.
415
     *
416
     * @param string $table the table that new rows will be inserted into/updated in.
417
     * @param array|Query $insertColumns the column data (name => value) to be inserted into the table or instance of
418
     * {@see Query} to perform `INSERT INTO ... SELECT` SQL statement.
419
     * @param array|bool $updateColumns the column data (name => value) to be updated if they already exist.
420
     * If `true` is passed, the column data will be updated to match the insert column data.
421
     * If `false` is passed, no update will be performed if the column data already exists.
422
     * @param array $params the binding parameters that will be generated by this method.
423
     * They should be bound to the DB command later.
424
     *
425
     * @throws Exception|JsonException|InvalidConfigException|NotSupportedException if this is not supported by the
426
     * underlying DBMS.
427
     *
428
     * @return string the resulting SQL.
429
     *
430
     * {@see https://www.postgresql.org/docs/9.5/static/sql-insert.html#SQL-ON-CONFLICT}
431
     * {@see https://stackoverflow.com/questions/1109061/insert-on-duplicate-update-in-postgresql/8702291#8702291}
432
     */
433 18
    public function upsert(string $table, $insertColumns, $updateColumns, array &$params = []): string
434
    {
435 18
        $insertColumns = $this->normalizeTableRowData($table, $insertColumns);
436
437 18
        if (!is_bool($updateColumns)) {
438 7
            $updateColumns = $this->normalizeTableRowData($table, $updateColumns);
439
        }
440 18
        if (version_compare($this->getDb()->getServerVersion(), '9.5', '<')) {
441
            return $this->oldUpsert($table, $insertColumns, $updateColumns, $params);
442
        }
443
444 18
        return $this->newUpsert($table, $insertColumns, $updateColumns, $params);
445
    }
446
447
    /**
448
     * {@see upsert()} implementation for PostgreSQL 9.5 or higher.
449
     *
450
     * @param string $table
451
     * @param array|Query $insertColumns
452
     * @param array|bool $updateColumns
453
     * @param array $params
454
     *
455
     * @throws Exception|JsonException|InvalidArgumentException|InvalidConfigException|NotSupportedException
456
     *
457
     * @return string
458
     */
459 18
    private function newUpsert(string $table, $insertColumns, $updateColumns, array &$params = []): string
460
    {
461 18
        $insertSql = $this->insert($table, $insertColumns, $params);
462 18
        [$uniqueNames, , $updateNames] = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns);
463
464 18
        if (empty($uniqueNames)) {
465 3
            return $insertSql;
466
        }
467
468 15
        if ($updateNames === []) {
469
            /** there are no columns to update */
470
            $updateColumns = false;
471
        }
472
473 15
        if ($updateColumns === false) {
474 5
            return "$insertSql ON CONFLICT DO NOTHING";
475
        }
476
477 10
        if ($updateColumns === true) {
478 4
            $updateColumns = [];
479 4
            foreach ($updateNames as $name) {
480 4
                $updateColumns[$name] = new Expression('EXCLUDED.' . $this->getDb()->quoteColumnName($name));
481
            }
482
        }
483
484 10
        [$updates, $params] = $this->prepareUpdateSets($table, $updateColumns, $params);
485
486 10
        return $insertSql . ' ON CONFLICT (' . implode(', ', $uniqueNames) . ') DO UPDATE SET '
487 10
            . implode(', ', $updates);
488
    }
489
490
    /**
491
     * {@see upsert()} implementation for PostgreSQL older than 9.5.
492
     *
493
     * @param string $table
494
     * @param array|Query $insertColumns
495
     * @param array|bool $updateColumns
496
     * @param array $params
497
     *
498
     * @throws Exception|InvalidArgumentException|InvalidConfigException|JsonException|NotSupportedException
499
     *
500
     * @return string
501
     */
502
    private function oldUpsert(string $table, $insertColumns, $updateColumns, array &$params = []): string
503
    {
504
        /** @var Constraint[] $constraints */
505
        [$uniqueNames, $insertNames, $updateNames] = $this->prepareUpsertColumns(
506
            $table,
507
            $insertColumns,
508
            $updateColumns,
509
            $constraints
510
        );
511
512
        if (empty($uniqueNames)) {
513
            return $this->insert($table, $insertColumns, $params);
514
        }
515
516
        if ($updateNames === []) {
517
            /** there are no columns to update */
518
            $updateColumns = false;
519
        }
520
521
        /** @var Schema $schema */
522
        $schema = $this->getDb()->getSchema();
523
524
        if (!$insertColumns instanceof Query) {
525
            $tableSchema = $schema->getTableSchema($table);
526
            $columnSchemas = $tableSchema !== null ? $tableSchema->getColumns() : [];
527
            foreach ($insertColumns as $name => $value) {
528
                /**
529
                 * NULLs and numeric values must be type hinted in order to be used in SET assigments NVM, let's cast
530
                 * them all
531
                 */
532
                if (isset($columnSchemas[$name])) {
533
                    $phName = self::PARAM_PREFIX . count($params);
534
                    $params[$phName] = $value;
535
                    $insertColumns[$name] = new Expression("CAST($phName AS {$columnSchemas[$name]->getDbType()})");
536
                }
537
            }
538
        }
539
540
        [, $placeholders, $values, $params] = $this->prepareInsertValues($table, $insertColumns, $params);
541
        $updateCondition = ['or'];
542
        $insertCondition = ['or'];
543
        $quotedTableName = $schema->quoteTableName($table);
544
545
        foreach ($constraints as $constraint) {
546
            $constraintUpdateCondition = ['and'];
547
            $constraintInsertCondition = ['and'];
548
            foreach ($constraint->getColumnNames() as $name) {
549
                $quotedName = $schema->quoteColumnName($name);
550
                $constraintUpdateCondition[] = "$quotedTableName.$quotedName=\"EXCLUDED\".$quotedName";
551
                $constraintInsertCondition[] = "\"upsert\".$quotedName=\"EXCLUDED\".$quotedName";
552
            }
553
            $updateCondition[] = $constraintUpdateCondition;
554
            $insertCondition[] = $constraintInsertCondition;
555
        }
556
557
        $withSql = 'WITH "EXCLUDED" (' . implode(', ', $insertNames) . ') AS ('
558
            . (!empty($placeholders) ? 'VALUES (' . implode(', ', $placeholders) . ')' : ltrim($values, ' ')) . ')';
559
560
        if ($updateColumns === false) {
561
            $selectSubQuery = (new Query($this->getDb()))
562
                ->select(new Expression('1'))
563
                ->from($table)
564
                ->where($updateCondition);
565
            $insertSelectSubQuery = (new Query($this->getDb()))
566
                ->select($insertNames)
567
                ->from('EXCLUDED')
568
                ->where(['not exists', $selectSubQuery]);
569
            $insertSql = $this->insert($table, $insertSelectSubQuery, $params);
570
571
            return "$withSql $insertSql";
572
        }
573
574
        if ($updateColumns === true) {
575
            $updateColumns = [];
576
            foreach ($updateNames as $name) {
577
                $quotedName = $this->getDb()->quoteColumnName($name);
578
                if (strrpos($quotedName, '.') === false) {
579
                    $quotedName = '"EXCLUDED".' . $quotedName;
580
                }
581
                $updateColumns[$name] = new Expression($quotedName);
582
            }
583
        }
584
585
        [$updates, $params] = $this->prepareUpdateSets($table, $updateColumns, $params);
586
587
        $updateSql = 'UPDATE ' . $this->getDb()->quoteTableName($table) . ' SET ' . implode(', ', $updates)
588
            . ' FROM "EXCLUDED" ' . $this->buildWhere($updateCondition, $params)
589
            . ' RETURNING ' . $this->getDb()->quoteTableName($table) . '.*';
590
591
        $selectUpsertSubQuery = (new Query($this->getDb()))
592
            ->select(new Expression('1'))
593
            ->from('upsert')
594
            ->where($insertCondition);
595
596
        $insertSelectSubQuery = (new Query($this->getDb()))
597
            ->select($insertNames)
598
            ->from('EXCLUDED')
599
            ->where(['not exists', $selectUpsertSubQuery]);
600
601
        $insertSql = $this->insert($table, $insertSelectSubQuery, $params);
602
603
        return "$withSql, \"upsert\" AS ($updateSql) $insertSql";
604
    }
605
606
    /**
607
     * Creates an UPDATE SQL statement.
608
     *
609
     * For example,
610
     *
611
     * ```php
612
     * $params = [];
613
     * $sql = $queryBuilder->update('user', ['status' => 1], 'age > 30', $params);
614
     * ```
615
     *
616
     * The method will properly escape the table and column names.
617
     *
618
     * @param string $table the table to be updated.
619
     * @param array $columns the column data (name => value) to be updated.
620
     * @param array|string $condition the condition that will be put in the WHERE part. Please refer to
621
     * {@see Query::where()} on how to specify condition.
622
     * @param array $params the binding parameters that will be modified by this method so that they can be bound to the
623
     * DB command later.
624
     *
625
     * @throws Exception|InvalidArgumentException
626
     *
627
     * @return string the UPDATE SQL.
628
     */
629 4
    public function update(string $table, array $columns, $condition, array &$params = []): string
630
    {
631 4
        return parent::update($table, $this->normalizeTableRowData($table, $columns), $condition, $params);
632
    }
633
634
    /**
635
     * Normalizes data to be saved into the table, performing extra preparations and type converting, if necessary.
636
     *
637
     * @param string $table the table that data will be saved into.
638
     * @param array|Query $columns the column data (name => value) to be saved into the table or instance of
639
     * {@see Query} to perform INSERT INTO ... SELECT SQL statement. Passing of
640
     * {@see Query}.
641
     *
642
     * @return array|object normalized columns
643
     */
644 45
    private function normalizeTableRowData(string $table, $columns)
645
    {
646 45
        if ($columns instanceof Query) {
647 14
            return $columns;
648
        }
649
650 37
        if (($tableSchema = $this->getDb()->getSchema()->getTableSchema($table)) !== null) {
651 37
            $columnSchemas = $tableSchema->getColumns();
652 37
            foreach ($columns as $name => $value) {
653
                if (
654 37
                    isset($columnSchemas[$name]) &&
655 37
                    $columnSchemas[$name]->getType() === Schema::TYPE_BINARY &&
656 37
                    is_string($value)
657
                ) {
658
                    /** explicitly setup PDO param type for binary column */
659 1
                    $columns[$name] = new PdoValue($value, PDO::PARAM_LOB);
660
                }
661
            }
662
        }
663
664 37
        return $columns;
665
    }
666
667
    /**
668
     * Generates a batch INSERT SQL statement.
669
     *
670
     * For example,
671
     *
672
     * ```php
673
     * $sql = $queryBuilder->batchInsert('user', ['name', 'age'], [
674
     *     ['Tom', 30],
675
     *     ['Jane', 20],
676
     *     ['Linda', 25],
677
     * ]);
678
     * ```
679
     *
680
     * Note that the values in each row must match the corresponding column names.
681
     *
682
     * The method will properly escape the column names, and quote the values to be inserted.
683
     *
684
     * @param string $table the table that new rows will be inserted into.
685
     * @param array $columns the column names.
686
     * @param array|Generator $rows the rows to be batch inserted into the table.
687
     * @param array $params the binding parameters. This parameter exists.
688
     *
689
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException
690
     *
691
     * @return string the batch INSERT SQL statement.
692
     */
693 20
    public function batchInsert(string $table, array $columns, $rows, array &$params = []): string
694
    {
695 20
        if (empty($rows)) {
696 2
            return '';
697
        }
698
699 19
        $schema = $this->getDb()->getSchema();
700
701 19
        if (($tableSchema = $schema->getTableSchema($table)) !== null) {
702 19
            $columnSchemas = $tableSchema->getColumns();
703
        } else {
704
            $columnSchemas = [];
705
        }
706
707 19
        $values = [];
708 19
        foreach ($rows as $row) {
709 18
            $vs = [];
710 18
            foreach ($row as $i => $value) {
711 18
                if (isset($columns[$i], $columnSchemas[$columns[$i]])) {
712 15
                    $value = $columnSchemas[$columns[$i]]->dbTypecast($value);
713
                }
714
715 18
                if (is_string($value)) {
716 8
                    $value = $schema->quoteValue($value);
717 13
                } elseif (is_float($value)) {
718
                    /** ensure type cast always has . as decimal separator in all locales */
719 1
                    $value = NumericHelper::normalize((string) $value);
720 13
                } elseif ($value === true) {
721 3
                    $value = 'TRUE';
722 13
                } elseif ($value === false) {
723 5
                    $value = 'FALSE';
724 11
                } elseif ($value === null) {
725 4
                    $value = 'NULL';
726 8
                } elseif ($value instanceof ExpressionInterface) {
727 6
                    $value = $this->buildExpression($value, $params);
728
                }
729
730 18
                $vs[] = $value;
731
            }
732 18
            $values[] = '(' . implode(', ', $vs) . ')';
733
        }
734
735 19
        if (empty($values)) {
736 1
            return '';
737
        }
738
739 18
        foreach ($columns as $i => $name) {
740 17
            $columns[$i] = $schema->quoteColumnName($name);
741
        }
742
743 18
        return 'INSERT INTO ' . $schema->quoteTableName($table)
744 18
            . ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values);
745
    }
746
}
747