Passed
Push — master ( 50bf2d...769a3d )
by Alexander
01:38
created

QueryBuilder   F

Complexity

Total Complexity 77

Size/Duplication

Total Lines 700
Duplicated Lines 0 %

Test Coverage

Coverage 61.63%

Importance

Changes 0
Metric Value
eloc 245
dl 0
loc 700
ccs 135
cts 219
cp 0.6163
rs 2.24
c 0
b 0
f 0
wmc 77

16 Methods

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

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