Passed
Pull Request — master (#70)
by Wilmer
01:43
created

QueryBuilder   F

Complexity

Total Complexity 63

Size/Duplication

Total Lines 627
Duplicated Lines 0 %

Test Coverage

Coverage 55.38%

Importance

Changes 0
Metric Value
eloc 183
c 0
b 0
f 0
dl 0
loc 627
ccs 103
cts 186
cp 0.5538
rs 3.36
wmc 63

15 Methods

Rating   Name   Duplication   Size   Complexity  
A createIndex() 0 15 5
A defaultExpressionBuilders() 0 5 1
A defaultConditionClasses() 0 7 1
A dropIndex() 0 18 5
A renameTable() 0 4 1
A insert() 0 3 1
B normalizeTableRowData() 0 22 7
A resetSequence() 0 27 5
A checkIntegrity() 0 27 6
C batchInsert() 0 68 14
A newUpsert() 0 34 6
A update() 0 3 1
A truncateTable() 0 3 1
A upsert() 0 9 2
B alterColumn() 0 56 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 Generator;
8
use JsonException;
9
use PDO;
10
use Yiisoft\Db\Constraint\Constraint;
11
use Yiisoft\Db\Exception\Exception;
12
use Yiisoft\Db\Exception\InvalidArgumentException;
13
use Yiisoft\Db\Exception\InvalidConfigException;
14
use Yiisoft\Db\Exception\NotSupportedException;
15
use Yiisoft\Db\Expression\ArrayExpression;
16
use Yiisoft\Db\Expression\Expression;
17
use Yiisoft\Db\Expression\ExpressionInterface;
18
use Yiisoft\Db\Expression\JsonExpression;
19
use Yiisoft\Db\Pdo\PdoValue;
20
use Yiisoft\Db\Query\Conditions\LikeCondition;
21
use Yiisoft\Db\Query\Query;
22
use Yiisoft\Db\Query\QueryBuilder as AbstractQueryBuilder;
23
use Yiisoft\Db\Schema\ColumnSchemaBuilder;
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 305
    protected function defaultConditionClasses(): array
106
    {
107 305
        return array_merge(parent::defaultConditionClasses(), [
108 305
            '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 305
    protected function defaultExpressionBuilders(): array
124
    {
125 305
        return array_merge(parent::defaultExpressionBuilders(), [
126 305
            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 array|string $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|JsonException if the table does not exist or there is no sequence
221
     * associated with the table.
222
     *
223
     * @return string the SQL statement for resetting sequence.
224
     *
225 1
     * @psalm-suppress MixedArgument
226
     */
227 1
    public function resetSequence(string $tableName, $value = null): string
228 1
    {
229
        $table = $this->getDb()->getTableSchema($tableName);
230
231
        if ($table !== null && ($sequence = $table->getSequenceName()) !== null) {
232 1
            /**
233 1
             * {@see http://www.postgresql.org/docs/8.1/static/functions-sequence.html}
234 1
             */
235 1
            $sequence = $this->getDb()->quoteTableName($sequence);
236 1
            $tableName = $this->getDb()->quoteTableName($tableName);
237 1
238
            if ($value === null) {
239 1
                $pk = $table->getPrimaryKey();
240
                $key = $this->getDb()->quoteColumnName(reset($pk));
241
                $value = "(SELECT COALESCE(MAX({$key}),0) FROM {$tableName})+1";
242 1
            } else {
243
                $value = (int) $value;
244
            }
245
246
            return "SELECT SETVAL('$sequence',$value,false)";
247
        }
248
249
        if ($table === null) {
250
            throw new InvalidArgumentException("Table not found: $tableName");
251
        }
252
253
        throw new InvalidArgumentException("There is not sequence associated with table '$tableName'.");
254
    }
255
256
    /**
257
     * Builds a SQL statement for enabling or disabling integrity check.
258
     *
259
     * @param string $schema the schema of the tables.
260
     * @param string $table the table name.
261
     * @param bool $check whether to turn on or off the integrity check.
262
     *
263
     * @throws Exception|NotSupportedException
264
     *
265
     * @return string the SQL statement for checking integrity.
266
     */
267
    public function checkIntegrity(string $schema = '', string $table = '', bool $check = true): string
268
    {
269
        /** @psalm-var Connection $db */
270
        $db = $this->getDb();
271
272
        $enable = $check ? 'ENABLE' : 'DISABLE';
273
        $schema = $schema ?: $db->getSchema()->getDefaultSchema();
274
        $tableNames = [];
275
        $viewNames = [];
276
277
        if ($schema !== null) {
278
            $tableNames = $table ? [$table] : $db->getSchema()->getTableNames($schema);
279
            $viewNames = $db->getSchema()->getViewNames($schema);
280
        }
281
282
        $tableNames = array_diff($tableNames, $viewNames);
283
        $command = '';
284
285
        foreach ($tableNames as $tableName) {
286
            $tableName = $db->quoteTableName("{$schema}.{$tableName}");
287
            $command .= "ALTER TABLE $tableName $enable TRIGGER ALL; ";
288
        }
289
290
        /** enable to have ability to alter several tables */
291
        $db->getMasterPdo()->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
292
293 1
        return $command;
294
    }
295 1
296
    /**
297
     * Builds a SQL statement for truncating a DB table.
298
     *
299
     * Explicitly restarts identity for PGSQL to be consistent with other databases which all do this by default.
300
     *
301
     * @param string $table the table to be truncated. The name will be properly quoted by the method.
302
     *
303
     * @return string the SQL statement for truncating a DB table.
304
     */
305
    public function truncateTable(string $table): string
306
    {
307
        return 'TRUNCATE TABLE ' . $this->getDb()->quoteTableName($table) . ' RESTART IDENTITY';
308
    }
309
310
    /**
311 1
     * Builds a SQL statement for changing the definition of a column.
312
     *
313 1
     * @param string $table the table whose column is to be changed. The table name will be properly quoted by the
314 1
     * method.
315
     * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
316
     * @param string|ColumnSchemaBuilder $type the new column type. The {@see getColumnType()} method will be invoked to
317
     * convert abstract column type (if any) into the physical one. Anything that is not recognized as abstract type
318
     * will be kept in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while
319
     * 'string not null' will become 'varchar(255) not null'. You can also use PostgreSQL-specific syntax such as
320 1
     * `SET NOT NULL`.
321 1
     *
322
     * @return string the SQL statement for changing the definition of a column.
323
     */
324 1
    public function alterColumn(string $table, string $column, $type): string
325 1
    {
326 1
        $columnName = $this->getDb()->quoteColumnName($column);
327
        $tableName = $this->getDb()->quoteTableName($table);
328 1
329 1
        if (is_object($type)) {
330 1
            /** @var string $type */
331
            $type = $type->__toString();
332
        }
333 1
334
        /**
335 1
         * {@see https://github.com/yiisoft/yii2/issues/4492}
336 1
         * {@see http://www.postgresql.org/docs/9.1/static/sql-altertable.html}
337
         */
338
        if (preg_match('/^(DROP|SET|RESET)\s+/i', $type)) {
339 1
            return "ALTER TABLE {$tableName} ALTER COLUMN {$columnName} {$type}";
340 1
        }
341 1
342
        $type = 'TYPE ' . $this->getColumnType($type);
343
344
        $multiAlterStatement = [];
345 1
        $constraintPrefix = preg_replace('/[^a-z0-9_]/i', '', $table . '_' . $column);
346 1
347 1
        if (preg_match('/\s+DEFAULT\s+(["\']?\w*["\']?)/i', $type, $matches)) {
348
            $type = preg_replace('/\s+DEFAULT\s+(["\']?\w*["\']?)/i', '', $type);
349
            $multiAlterStatement[] = "ALTER COLUMN {$columnName} SET DEFAULT {$matches[1]}";
350 1
        } else {
351
            // safe to drop default even if there was none in the first place
352 1
            $multiAlterStatement[] = "ALTER COLUMN {$columnName} DROP DEFAULT";
353 1
        }
354
355
        $type = preg_replace('/\s+NOT\s+NULL/i', '', $type, -1, $count);
356
357 1
        if ($count) {
358
            $multiAlterStatement[] = "ALTER COLUMN {$columnName} SET NOT NULL";
359 1
        } else {
360
            // remove additional null if any
361
            $type = preg_replace('/\s+NULL/i', '', $type);
362
            // safe to drop not null even if there was none in the first place
363
            $multiAlterStatement[] = "ALTER COLUMN {$columnName} DROP NOT NULL";
364
        }
365
366
        if (preg_match('/\s+CHECK\s+\((.+)\)/i', $type, $matches)) {
367
            $type = preg_replace('/\s+CHECK\s+\((.+)\)/i', '', $type);
368
            $multiAlterStatement[] = "ADD CONSTRAINT {$constraintPrefix}_check CHECK ({$matches[1]})";
369
        }
370
371
        $type = preg_replace('/\s+UNIQUE/i', '', $type, -1, $count);
372
        if ($count) {
373
            $multiAlterStatement[] = "ADD UNIQUE ({$columnName})";
374
        }
375
376
        // add what's left at the beginning
377
        array_unshift($multiAlterStatement, "ALTER COLUMN {$columnName} {$type}");
378
379
        return 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $multiAlterStatement);
380
    }
381
382
    /**
383
     * Creates an INSERT SQL statement.
384
     *
385
     * For example,.
386
     *
387
     * ```php
388
     * $sql = $queryBuilder->insert('user', [
389
     *     'name' => 'Sam',
390 43
     *     'age' => 30,
391
     * ], $params);
392 43
     * ```
393
     *
394
     * The method will properly escape the table and column names.
395
     *
396
     * @param string $table the table that new rows will be inserted into.
397
     * @param array|Query $columns the column data (name => value) to be inserted into the table or instance of
398
     * {@see Query|Query} to perform INSERT INTO ... SELECT SQL statement. Passing of
399
     * {@see Query|Query}.
400
     * @param array $params the binding parameters that will be generated by this method. They should be bound to the
401
     * DB command later.
402
     *
403
     * @throws Exception|InvalidArgumentException|InvalidConfigException|JsonException|NotSupportedException
404
     *
405
     * @return string the INSERT SQL
406
     *
407
     * @psalm-suppress MixedArgument
408
     */
409
    public function insert(string $table, $columns, array &$params = []): string
410
    {
411
        return parent::insert($table, $this->normalizeTableRowData($table, $columns), $params);
412
    }
413
414
    /**
415
     * Creates an SQL statement to insert rows into a database table if they do not already exist (matching unique
416
     * constraints), or update them if they do.
417
     *
418
     * For example,
419
     *
420
     * ```php
421
     * $sql = $queryBuilder->upsert('pages', [
422
     *     'name' => 'Front page',
423
     *     'url' => 'http://example.com/', // url is unique
424
     *     'visits' => 0,
425
     * ], [
426
     *     'visits' => new \Yiisoft\Db\Expression('visits + 1'),
427
     * ], $params);
428
     * ```
429
     *
430 18
     * The method will properly escape the table and column names.
431
     *
432 18
     * @param string $table the table that new rows will be inserted into/updated in.
433
     * @param array|Query $insertColumns the column data (name => value) to be inserted into the table or instance of
434 18
     * {@see Query} to perform `INSERT INTO ... SELECT` SQL statement.
435 7
     * @param array|bool $updateColumns the column data (name => value) to be updated if they already exist.
436
     * If `true` is passed, the column data will be updated to match the insert column data.
437 18
     * If `false` is passed, no update will be performed if the column data already exists.
438
     * @param array $params the binding parameters that will be generated by this method.
439
     * They should be bound to the DB command later.
440
     *
441 18
     * @throws Exception|InvalidConfigException|JsonException|NotSupportedException if this is not supported by the
442
     * underlying DBMS.
443
     *
444
     * @return string the resulting SQL.
445
     *
446
     * {@see https://www.postgresql.org/docs/9.5/static/sql-insert.html#SQL-ON-CONFLICT}
447
     * {@see https://stackoverflow.com/questions/1109061/insert-on-duplicate-update-in-postgresql/8702291#8702291}
448
     *
449
     * @psalm-suppress MixedArgument
450
     * @psalm-suppress MixedAssignment
451
     */
452
    public function upsert(string $table, $insertColumns, $updateColumns, array &$params = []): string
453
    {
454
        $insertColumns = $this->normalizeTableRowData($table, $insertColumns);
455
456 18
        if (!is_bool($updateColumns)) {
457
            $updateColumns = $this->normalizeTableRowData($table, $updateColumns);
458 18
        }
459 18
460
        return $this->newUpsert($table, $insertColumns, $updateColumns, $params);
461 18
    }
462 3
463
    /**
464
     * {@see upsert()} implementation for PostgreSQL 9.5 or higher.
465 15
     *
466
     * @param string $table
467
     * @param array|Query $insertColumns
468
     * @param array|bool $updateColumns
469
     * @param array $params
470 15
     *
471 5
     * @throws Exception|InvalidArgumentException|InvalidConfigException|JsonException|NotSupportedException
472
     *
473
     * @return string
474 10
     */
475 4
    private function newUpsert(string $table, $insertColumns, $updateColumns, array &$params = []): string
476 4
    {
477 4
        $insertSql = $this->insert($table, $insertColumns, $params);
478
479
        /** @var array<array-key, mixed> $uniqueNames */
480
        [$uniqueNames, , $updateNames] = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns);
481 10
482
        if (empty($uniqueNames)) {
483 10
            return $insertSql;
484 10
        }
485
486
        if ($updateNames === []) {
487
            /** there are no columns to update */
488
            $updateColumns = false;
489
        }
490
491
        if ($updateColumns === false) {
492
            return "$insertSql ON CONFLICT DO NOTHING";
493
        }
494
495
        if ($updateColumns === true) {
496
            $updateColumns = [];
497
498
            /** @var string $name */
499
            foreach ($updateNames as $name) {
500
                $updateColumns[$name] = new Expression('EXCLUDED.' . $this->getDb()->quoteColumnName($name));
501
            }
502
        }
503
504
        /** @var array<array-key, mixed> $updates */
505
        [$updates, $params] = $this->prepareUpdateSets($table, $updateColumns, $params);
506
507
        return $insertSql . ' ON CONFLICT (' . implode(', ', $uniqueNames) . ') DO UPDATE SET '
508
            . implode(', ', $updates);
509
    }
510
511
    /**
512
     * Creates an UPDATE SQL statement.
513
     *
514
     * For example,
515
     *
516
     * ```php
517
     * $params = [];
518
     * $sql = $queryBuilder->update('user', ['status' => 1], 'age > 30', $params);
519
     * ```
520
     *
521
     * The method will properly escape the table and column names.
522
     *
523
     * @param string $table the table to be updated.
524
     * @param array $columns the column data (name => value) to be updated.
525
     * @param array|string $condition the condition that will be put in the WHERE part. Please refer to
526
     * {@see Query::where()} on how to specify condition.
527
     * @param array $params the binding parameters that will be modified by this method so that they can be bound to the
528
     * DB command later.
529
     *
530
     * @throws Exception|InvalidArgumentException|JsonException
531
     *
532
     * @return string the UPDATE SQL.
533
     * @psalm-suppress MixedArgument
534
     */
535
    public function update(string $table, array $columns, $condition, array &$params = []): string
536
    {
537
        return parent::update($table, $this->normalizeTableRowData($table, $columns), $condition, $params);
538
    }
539
540
    /**
541
     * Normalizes data to be saved into the table, performing extra preparations and type converting, if necessary.
542
     *
543
     * @param string $table the table that data will be saved into.
544
     * @param array|Query $columns the column data (name => value) to be saved into the table or instance of
545
     * {@see Query} to perform INSERT INTO ... SELECT SQL statement. Passing of
546
     * {@see Query}.
547
     *
548
     * @return mixed normalized columns.
549
     */
550
    private function normalizeTableRowData(string $table, $columns)
551
    {
552
        if ($columns instanceof Query) {
553
            return $columns;
554
        }
555
556
        if (($tableSchema = $this->getDb()->getSchema()->getTableSchema($table)) !== null) {
557
            $columnSchemas = $tableSchema->getColumns();
558
            /** @var mixed $value */
559
            foreach ($columns as $name => $value) {
560
                if (
561
                    isset($columnSchemas[$name]) &&
562
                    $columnSchemas[$name]->getType() === Schema::TYPE_BINARY &&
563
                    is_string($value)
564
                ) {
565
                    /** explicitly setup PDO param type for binary column */
566
                    $columns[$name] = new PdoValue($value, PDO::PARAM_LOB);
567
                }
568
            }
569
        }
570
571
        return $columns;
572
    }
573
574
    /**
575
     * Generates a batch INSERT SQL statement.
576
     *
577
     * For example,
578
     *
579
     * ```php
580
     * $sql = $queryBuilder->batchInsert('user', ['name', 'age'], [
581
     *     ['Tom', 30],
582
     *     ['Jane', 20],
583
     *     ['Linda', 25],
584
     * ]);
585
     * ```
586
     *
587
     * Note that the values in each row must match the corresponding column names.
588
     *
589
     * The method will properly escape the column names, and quote the values to be inserted.
590
     *
591
     * @param string $table the table that new rows will be inserted into.
592
     * @param array<array-key, string> $columns the column names.
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<array-key, string> at position 2 could not be parsed: Unknown type name 'array-key' at position 2 in array<array-key, string>.
Loading history...
593
     * @param array|Generator $rows the rows to be batch inserted into the table.
594
     * @param array $params the binding parameters. This parameter exists.
595
     *
596
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException
597
     *
598
     * @return string the batch INSERT SQL statement.
599
     * @psalm-suppress MoreSpecificImplementedParamType
600
     */
601
    public function batchInsert(string $table, array $columns, $rows, array &$params = []): string
602
    {
603
        if (empty($rows)) {
604
            return '';
605
        }
606
607
        /**
608
         * @var array<array-key, object> $columnSchemas
609
         */
610
        $columnSchemas = [];
611
        $schema = $this->getDb()->getSchema();
612
613
        if (($tableSchema = $schema->getTableSchema($table)) !== null) {
614
            $columnSchemas = $tableSchema->getColumns();
615
        }
616
617
        $values = [];
618
619
        /**
620
         * @var array<array-key, mixed> $row
621
         */
622
        foreach ($rows as $row) {
623
            $vs = [];
624
            /**
625
             *  @var int $i
626 4
             *  @var mixed $value
627
             */
628 4
            foreach ($row as $i => $value) {
629
                if (isset($columns[$i], $columnSchemas[$columns[$i]])) {
630
                    /**
631
                     * @var string|int|float|bool|ExpressionInterface|null $value
632
                     * @psalm-suppress MixedMethodCall
633
                     */
634
                    $value = $columnSchemas[$columns[$i]]->dbTypecast($value);
635
                }
636
637
                if (is_string($value)) {
638
                    $value = $schema->quoteValue($value);
639
                } elseif (is_float($value)) {
640
                    /** ensure type cast always has . as decimal separator in all locales */
641 45
                    $value = NumericHelper::normalize((string) $value);
642
                } elseif ($value === true) {
643 45
                    $value = 'TRUE';
644 14
                } elseif ($value === false) {
645
                    $value = 'FALSE';
646
                } elseif ($value === null) {
647 37
                    $value = 'NULL';
648 37
                } elseif ($value instanceof ExpressionInterface) {
649 37
                    $value = $this->buildExpression($value, $params);
650
                }
651 37
652 37
                /** @var string|int|float|bool|ExpressionInterface|null $value */
653 37
                $vs[] = $value;
654
            }
655
            $values[] = '(' . implode(', ', $vs) . ')';
656 1
        }
657
658
        if (empty($values)) {
659
            return '';
660
        }
661 37
662
        /** @var string name */
663
        foreach ($columns as $i => $name) {
664
            $columns[$i] = $schema->quoteColumnName($name);
665
        }
666
667
        return 'INSERT INTO ' . $schema->quoteTableName($table)
668
            . ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values);
669
    }
670
}
671