Passed
Pull Request — 2.2 (#20357)
by Wilmer
13:33 queued 05:55
created

QueryBuilder::defaultConditionClasses()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 0
dl 0
loc 7
ccs 0
cts 6
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * @link https://www.yiiframework.com/
5
 * @copyright Copyright (c) 2008 Yii Software LLC
6
 * @license https://www.yiiframework.com/license/
7
 */
8
9
namespace yii\db\pgsql;
10
11
use yii\base\InvalidArgumentException;
12
use yii\db\Constraint;
13
use yii\db\Expression;
14
use yii\db\ExpressionInterface;
15
use yii\db\Query;
16
use yii\db\PdoValue;
17
use yii\helpers\StringHelper;
18
19
/**
20
 * QueryBuilder is the query builder for PostgreSQL databases.
21
 *
22
 * @author Gevik Babakhani <[email protected]>
23
 * @since 2.0
24
 */
25
class QueryBuilder extends \yii\db\QueryBuilder
26
{
27
    /**
28
     * Defines a UNIQUE index for [[createIndex()]].
29
     * @since 2.0.6
30
     */
31
    const INDEX_UNIQUE = 'unique';
32
    /**
33
     * Defines a B-tree index for [[createIndex()]].
34
     * @since 2.0.6
35
     */
36
    const INDEX_B_TREE = 'btree';
37
    /**
38
     * Defines a hash index for [[createIndex()]].
39
     * @since 2.0.6
40
     */
41
    const INDEX_HASH = 'hash';
42
    /**
43
     * Defines a GiST index for [[createIndex()]].
44
     * @since 2.0.6
45
     */
46
    const INDEX_GIST = 'gist';
47
    /**
48
     * Defines a GIN index for [[createIndex()]].
49
     * @since 2.0.6
50
     */
51
    const INDEX_GIN = 'gin';
52
53
    /**
54
     * @var array mapping from abstract column types (keys) to physical column types (values).
55
     */
56
    public $typeMap = [
57
        Schema::TYPE_PK => 'serial NOT NULL PRIMARY KEY',
0 ignored issues
show
Bug introduced by
The type yii\db\pgsql\Schema was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
58
        Schema::TYPE_UPK => 'serial NOT NULL PRIMARY KEY',
59
        Schema::TYPE_BIGPK => 'bigserial NOT NULL PRIMARY KEY',
60
        Schema::TYPE_UBIGPK => 'bigserial NOT NULL PRIMARY KEY',
61
        Schema::TYPE_CHAR => 'char(1)',
62
        Schema::TYPE_STRING => 'varchar(255)',
63
        Schema::TYPE_TEXT => 'text',
64
        Schema::TYPE_TINYINT => 'smallint',
65
        Schema::TYPE_SMALLINT => 'smallint',
66
        Schema::TYPE_INTEGER => 'integer',
67
        Schema::TYPE_BIGINT => 'bigint',
68
        Schema::TYPE_FLOAT => 'double precision',
69
        Schema::TYPE_DOUBLE => 'double precision',
70
        Schema::TYPE_DECIMAL => 'numeric(10,0)',
71
        Schema::TYPE_DATETIME => 'timestamp(0)',
72
        Schema::TYPE_TIMESTAMP => 'timestamp(0)',
73
        Schema::TYPE_TIME => 'time(0)',
74
        Schema::TYPE_DATE => 'date',
75
        Schema::TYPE_BINARY => 'bytea',
76
        Schema::TYPE_BOOLEAN => 'boolean',
77
        Schema::TYPE_MONEY => 'numeric(19,4)',
78
        Schema::TYPE_JSON => 'jsonb',
79
    ];
80
81
82
    /**
83
     * {@inheritdoc}
84
     */
85
    protected function defaultConditionClasses()
86
    {
87
        return array_merge(parent::defaultConditionClasses(), [
88
            'ILIKE' => 'yii\db\conditions\LikeCondition',
89
            'NOT ILIKE' => 'yii\db\conditions\LikeCondition',
90
            'OR ILIKE' => 'yii\db\conditions\LikeCondition',
91
            'OR NOT ILIKE' => 'yii\db\conditions\LikeCondition',
92
        ]);
93
    }
94
95
    /**
96
     * {@inheritdoc}
97
     */
98
    protected function defaultExpressionBuilders()
99
    {
100
        return array_merge(parent::defaultExpressionBuilders(), [
101
            'yii\db\ArrayExpression' => 'yii\db\pgsql\ArrayExpressionBuilder',
102
            'yii\db\JsonExpression' => 'yii\db\pgsql\JsonExpressionBuilder',
103
        ]);
104
    }
105
106
    /**
107
     * Builds a SQL statement for creating a new index.
108
     * @param string $name the name of the index. The name will be properly quoted by the method.
109
     * @param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
110
     * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns,
111
     * separate them with commas or use an array to represent them. Each column name will be properly quoted
112
     * by the method, unless a parenthesis is found in the name.
113
     * @param bool|string $unique whether to make this a UNIQUE index constraint. You can pass `true` or [[INDEX_UNIQUE]] to create
114
     * a unique index, `false` to make a non-unique index using the default index type, or one of the following constants to specify
115
     * the index method to use: [[INDEX_B_TREE]], [[INDEX_HASH]], [[INDEX_GIST]], [[INDEX_GIN]].
116
     * @return string the SQL statement for creating a new index.
117
     * @see https://www.postgresql.org/docs/8.2/sql-createindex.html
118
     */
119
    public function createIndex($name, $table, $columns, $unique = false)
120
    {
121
        if ($unique === self::INDEX_UNIQUE || $unique === true) {
122
            $index = false;
123
            $unique = true;
124
        } else {
125
            $index = $unique;
126
            $unique = false;
127
        }
128
129
        return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ') .
130
        $this->db->quoteTableName($name) . ' ON ' .
131
        $this->db->quoteTableName($table) .
132
        ($index !== false ? " USING $index" : '') .
133
        ' (' . $this->buildColumns($columns) . ')';
134
    }
135
136
    /**
137
     * Builds a SQL statement for dropping an index.
138
     * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
139
     * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
140
     * @return string the SQL statement for dropping an index.
141
     */
142
    public function dropIndex($name, $table)
143
    {
144
        if (strpos($table, '.') !== false && strpos($name, '.') === false) {
145
            if (strpos($table, '{{') !== false) {
146
                $table = preg_replace('/\\{\\{(.*?)\\}\\}/', '\1', $table);
147
                list($schema, $table) = explode('.', $table);
148
                if (strpos($schema, '%') === false) {
149
                    $name = $schema . '.' . $name;
150
                } else {
151
                    $name = '{{' . $schema . '.' . $name . '}}';
152
                }
153
            } else {
154
                list($schema) = explode('.', $table);
155
                $name = $schema . '.' . $name;
156
            }
157
        }
158
        return 'DROP INDEX ' . $this->db->quoteTableName($name);
159
    }
160
161
    /**
162
     * Builds a SQL statement for renaming a DB table.
163
     * @param string $oldName the table to be renamed. The name will be properly quoted by the method.
164
     * @param string $newName the new table name. The name will be properly quoted by the method.
165
     * @return string the SQL statement for renaming a DB table.
166
     */
167
    public function renameTable($oldName, $newName)
168
    {
169
        return 'ALTER TABLE ' . $this->db->quoteTableName($oldName) . ' RENAME TO ' . $this->db->quoteTableName($newName);
170
    }
171
172
    /**
173
     * Creates a SQL statement for resetting the sequence value of a table's primary key.
174
     * The sequence will be reset such that the primary key of the next new row inserted
175
     * will have the specified value or 1.
176
     * @param string $tableName the name of the table whose primary key sequence will be reset
177
     * @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
178
     * the next new row's primary key will have a value 1.
179
     * @return string the SQL statement for resetting sequence
180
     * @throws InvalidArgumentException if the table does not exist or there is no sequence associated with the table.
181
     */
182
    public function resetSequence($tableName, $value = null)
183
    {
184
        $table = $this->db->getTableSchema($tableName);
185
        if ($table !== null && $table->sequenceName !== null) {
186
            // c.f. https://www.postgresql.org/docs/8.1/functions-sequence.html
187
            $sequence = $this->db->quoteTableName($table->sequenceName);
188
            $tableName = $this->db->quoteTableName($tableName);
189
            if ($value === null) {
190
                $key = $this->db->quoteColumnName(reset($table->primaryKey));
191
                $value = "(SELECT COALESCE(MAX({$key}),0) FROM {$tableName})+1";
192
            } else {
193
                $value = (int) $value;
194
            }
195
196
            return "SELECT SETVAL('$sequence',$value,false)";
197
        } elseif ($table === null) {
198
            throw new InvalidArgumentException("Table not found: $tableName");
199
        }
200
201
        throw new InvalidArgumentException("There is not sequence associated with table '$tableName'.");
202
    }
203
204
    /**
205
     * Builds a SQL statement for enabling or disabling integrity check.
206
     * @param bool $check whether to turn on or off the integrity check.
207
     * @param string $schema the schema of the tables.
208
     * @param string $table the table name.
209
     * @return string the SQL statement for checking integrity
210
     */
211
    public function checkIntegrity($check = true, $schema = '', $table = '')
212
    {
213
        $enable = $check ? 'ENABLE' : 'DISABLE';
214
        $schema = $schema ?: $this->db->getSchema()->defaultSchema;
215
        $tableNames = $table ? [$table] : $this->db->getSchema()->getTableNames($schema);
216
        $viewNames = $this->db->getSchema()->getViewNames($schema);
0 ignored issues
show
Bug introduced by
The method getViewNames() does not exist on yii\db\Schema. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

216
        $viewNames = $this->db->getSchema()->/** @scrutinizer ignore-call */ getViewNames($schema);
Loading history...
217
        $tableNames = array_diff($tableNames, $viewNames);
218
        $command = '';
219
220
        foreach ($tableNames as $tableName) {
221
            $tableName = $this->db->quoteTableName("{$schema}.{$tableName}");
222
            $command .= "ALTER TABLE $tableName $enable TRIGGER ALL; ";
223
        }
224
225
        // enable to have ability to alter several tables
226
        $this->db->getMasterPdo()->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
227
228
        return $command;
229
    }
230
231
    /**
232
     * Builds a SQL statement for truncating a DB table.
233
     * Explicitly restarts identity for PGSQL to be consistent with other databases which all do this by default.
234
     * @param string $table the table to be truncated. The name will be properly quoted by the method.
235
     * @return string the SQL statement for truncating a DB table.
236
     */
237
    public function truncateTable($table)
238
    {
239
        return 'TRUNCATE TABLE ' . $this->db->quoteTableName($table) . ' RESTART IDENTITY';
240
    }
241
242
    /**
243
     * Builds a SQL statement for changing the definition of a column.
244
     * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
245
     * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
246
     * @param string $type the new column type. The [[getColumnType()]] method will be invoked to convert abstract
247
     * column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept
248
     * in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null'
249
     * will become 'varchar(255) not null'. You can also use PostgreSQL-specific syntax such as `SET NOT NULL`.
250
     * @return string the SQL statement for changing the definition of a column.
251
     */
252
    public function alterColumn($table, $column, $type)
253
    {
254
        $columnName = $this->db->quoteColumnName($column);
255
        $tableName = $this->db->quoteTableName($table);
256
257
        // https://github.com/yiisoft/yii2/issues/4492
258
        // https://www.postgresql.org/docs/9.1/sql-altertable.html
259
        if (preg_match('/^(DROP|SET|RESET)\s+/i', $type)) {
260
            return "ALTER TABLE {$tableName} ALTER COLUMN {$columnName} {$type}";
261
        }
262
263
        $type = 'TYPE ' . $this->getColumnType($type);
264
265
        $multiAlterStatement = [];
266
        $constraintPrefix = preg_replace('/[^a-z0-9_]/i', '', $table . '_' . $column);
267
268
        if (preg_match('/\s+DEFAULT\s+(["\']?\w*["\']?)/i', $type, $matches)) {
269
            $type = preg_replace('/\s+DEFAULT\s+(["\']?\w*["\']?)/i', '', $type);
270
            $multiAlterStatement[] = "ALTER COLUMN {$columnName} SET DEFAULT {$matches[1]}";
271
        } else {
272
            // safe to drop default even if there was none in the first place
273
            $multiAlterStatement[] = "ALTER COLUMN {$columnName} DROP DEFAULT";
274
        }
275
276
        $type = preg_replace('/\s+NOT\s+NULL/i', '', $type, -1, $count);
277
        if ($count) {
278
            $multiAlterStatement[] = "ALTER COLUMN {$columnName} SET NOT NULL";
279
        } else {
280
            // remove additional null if any
281
            $type = preg_replace('/\s+NULL/i', '', $type);
282
            // safe to drop not null even if there was none in the first place
283
            $multiAlterStatement[] = "ALTER COLUMN {$columnName} DROP NOT NULL";
284
        }
285
286
        if (preg_match('/\s+CHECK\s+\((.+)\)/i', $type, $matches)) {
287
            $type = preg_replace('/\s+CHECK\s+\((.+)\)/i', '', $type);
288
            $multiAlterStatement[] = "ADD CONSTRAINT {$constraintPrefix}_check CHECK ({$matches[1]})";
289
        }
290
291
        $type = preg_replace('/\s+UNIQUE/i', '', $type, -1, $count);
292
        if ($count) {
293
            $multiAlterStatement[] = "ADD UNIQUE ({$columnName})";
294
        }
295
296
        // add what's left at the beginning
297
        array_unshift($multiAlterStatement, "ALTER COLUMN {$columnName} {$type}");
298
299
        return 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $multiAlterStatement);
300
    }
301
302
    /**
303
     * {@inheritdoc}
304
     */
305
    public function insert($table, $columns, &$params)
306
    {
307
        return parent::insert($table, $this->normalizeTableRowData($table, $columns), $params);
308
    }
309
310
    /**
311
     * {@inheritdoc}
312
     * @see https://www.postgresql.org/docs/9.5/static/sql-insert.html#SQL-ON-CONFLICT
313
     * @see https://stackoverflow.com/questions/1109061/insert-on-duplicate-update-in-postgresql/8702291#8702291
314
     */
315
    public function upsert($table, $insertColumns, $updateColumns, &$params)
316
    {
317
        $insertColumns = $this->normalizeTableRowData($table, $insertColumns);
318
        if (!is_bool($updateColumns)) {
319
            $updateColumns = $this->normalizeTableRowData($table, $updateColumns);
320
        }
321
        if (version_compare($this->db->getServerVersion(), '9.5', '<')) {
322
            return $this->oldUpsert($table, $insertColumns, $updateColumns, $params);
0 ignored issues
show
Bug introduced by
It seems like $updateColumns can also be of type yii\db\Query; however, parameter $updateColumns of yii\db\pgsql\QueryBuilder::oldUpsert() does only seem to accept array|boolean, 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

322
            return $this->oldUpsert($table, $insertColumns, /** @scrutinizer ignore-type */ $updateColumns, $params);
Loading history...
323
        }
324
325
        return $this->newUpsert($table, $insertColumns, $updateColumns, $params);
0 ignored issues
show
Bug introduced by
It seems like $updateColumns can also be of type yii\db\Query; however, parameter $updateColumns of yii\db\pgsql\QueryBuilder::newUpsert() does only seem to accept array|boolean, 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

325
        return $this->newUpsert($table, $insertColumns, /** @scrutinizer ignore-type */ $updateColumns, $params);
Loading history...
326
    }
327
328
    /**
329
     * [[upsert()]] implementation for PostgreSQL 9.5 or higher.
330
     * @param string $table
331
     * @param array|Query $insertColumns
332
     * @param array|bool $updateColumns
333
     * @param array $params
334
     * @return string
335
     */
336
    private function newUpsert($table, $insertColumns, $updateColumns, &$params)
337
    {
338
        $insertSql = $this->insert($table, $insertColumns, $params);
339
        list($uniqueNames, , $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns);
340
        if (empty($uniqueNames)) {
341
            return $insertSql;
342
        }
343
        if ($updateNames === []) {
344
            // there are no columns to update
345
            $updateColumns = false;
346
        }
347
348
        if ($updateColumns === false) {
349
            return "$insertSql ON CONFLICT DO NOTHING";
350
        }
351
352
        if ($updateColumns === true) {
353
            $updateColumns = [];
354
            foreach ($updateNames as $name) {
355
                $updateColumns[$name] = new Expression('EXCLUDED.' . $this->db->quoteColumnName($name));
356
            }
357
        }
358
        list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params);
359
        return $insertSql . ' ON CONFLICT (' . implode(', ', $uniqueNames) . ') DO UPDATE SET ' . implode(', ', $updates);
360
    }
361
362
    /**
363
     * [[upsert()]] implementation for PostgreSQL older than 9.5.
364
     * @param string $table
365
     * @param array|Query $insertColumns
366
     * @param array|bool $updateColumns
367
     * @param array $params
368
     * @return string
369
     */
370
    private function oldUpsert($table, $insertColumns, $updateColumns, &$params)
371
    {
372
        /** @var Constraint[] $constraints */
373
        list($uniqueNames, $insertNames, $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns, $constraints);
374
        if (empty($uniqueNames)) {
375
            return $this->insert($table, $insertColumns, $params);
376
        }
377
        if ($updateNames === []) {
378
            // there are no columns to update
379
            $updateColumns = false;
380
        }
381
382
        /** @var Schema $schema */
383
        $schema = $this->db->getSchema();
384
        if (!$insertColumns instanceof Query) {
385
            $tableSchema = $schema->getTableSchema($table);
386
            $columnSchemas = $tableSchema !== null ? $tableSchema->columns : [];
387
            foreach ($insertColumns as $name => $value) {
388
                // NULLs and numeric values must be type hinted in order to be used in SET assigments
389
                // NVM, let's cast them all
390
                if (isset($columnSchemas[$name])) {
391
                    $phName = self::PARAM_PREFIX . count($params);
392
                    $params[$phName] = $value;
393
                    $insertColumns[$name] = new Expression("CAST($phName AS {$columnSchemas[$name]->dbType})");
394
                }
395
            }
396
        }
397
        list(, $placeholders, $values, $params) = $this->prepareInsertValues($table, $insertColumns, $params);
398
        $updateCondition = ['or'];
399
        $insertCondition = ['or'];
400
        $quotedTableName = $schema->quoteTableName($table);
401
        foreach ($constraints as $constraint) {
402
            $constraintUpdateCondition = ['and'];
403
            $constraintInsertCondition = ['and'];
404
            foreach ($constraint->columnNames as $name) {
405
                $quotedName = $schema->quoteColumnName($name);
406
                $constraintUpdateCondition[] = "$quotedTableName.$quotedName=\"EXCLUDED\".$quotedName";
407
                $constraintInsertCondition[] = "\"upsert\".$quotedName=\"EXCLUDED\".$quotedName";
408
            }
409
            $updateCondition[] = $constraintUpdateCondition;
410
            $insertCondition[] = $constraintInsertCondition;
411
        }
412
        $withSql = 'WITH "EXCLUDED" (' . implode(', ', $insertNames)
413
            . ') AS (' . (!empty($placeholders) ? 'VALUES (' . implode(', ', $placeholders) . ')' : ltrim($values, ' ')) . ')';
414
        if ($updateColumns === false) {
415
            $selectSubQuery = (new Query())
416
                ->select(new Expression('1'))
417
                ->from($table)
418
                ->where($updateCondition);
419
            $insertSelectSubQuery = (new Query())
420
                ->select($insertNames)
421
                ->from('EXCLUDED')
422
                ->where(['not exists', $selectSubQuery]);
423
            $insertSql = $this->insert($table, $insertSelectSubQuery, $params);
424
            return "$withSql $insertSql";
425
        }
426
427
        if ($updateColumns === true) {
428
            $updateColumns = [];
429
            foreach ($updateNames as $name) {
430
                $quotedName = $this->db->quoteColumnName($name);
431
                if (strrpos($quotedName, '.') === false) {
432
                    $quotedName = '"EXCLUDED".' . $quotedName;
433
                }
434
                $updateColumns[$name] = new Expression($quotedName);
435
            }
436
        }
437
        list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params);
438
        $updateSql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $updates)
439
            . ' FROM "EXCLUDED" ' . $this->buildWhere($updateCondition, $params)
440
            . ' RETURNING ' . $this->db->quoteTableName($table) . '.*';
441
        $selectUpsertSubQuery = (new Query())
442
            ->select(new Expression('1'))
443
            ->from('upsert')
444
            ->where($insertCondition);
445
        $insertSelectSubQuery = (new Query())
446
            ->select($insertNames)
447
            ->from('EXCLUDED')
448
            ->where(['not exists', $selectUpsertSubQuery]);
449
        $insertSql = $this->insert($table, $insertSelectSubQuery, $params);
450
        return "$withSql, \"upsert\" AS ($updateSql) $insertSql";
451
    }
452
453
    /**
454
     * {@inheritdoc}
455
     */
456
    public function update($table, $columns, $condition, &$params)
457
    {
458
        return parent::update($table, $this->normalizeTableRowData($table, $columns), $condition, $params);
0 ignored issues
show
Bug introduced by
It seems like $this->normalizeTableRowData($table, $columns) can also be of type yii\db\Query; however, parameter $columns of yii\db\QueryBuilder::update() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

458
        return parent::update($table, /** @scrutinizer ignore-type */ $this->normalizeTableRowData($table, $columns), $condition, $params);
Loading history...
459
    }
460
461
    /**
462
     * Normalizes data to be saved into the table, performing extra preparations and type converting, if necessary.
463
     *
464
     * @param string $table the table that data will be saved into.
465
     * @param array|Query $columns the column data (name => value) to be saved into the table or instance
466
     * of [[yii\db\Query|Query]] to perform INSERT INTO ... SELECT SQL statement.
467
     * Passing of [[yii\db\Query|Query]] is available since version 2.0.11.
468
     * @return array|Query normalized columns
469
     * @since 2.0.9
470
     */
471
    private function normalizeTableRowData($table, $columns)
472
    {
473
        if ($columns instanceof Query) {
474
            return $columns;
475
        }
476
477
        if (($tableSchema = $this->db->getSchema()->getTableSchema($table)) !== null) {
478
            $columnSchemas = $tableSchema->columns;
479
            foreach ($columns as $name => $value) {
480
                if (isset($columnSchemas[$name]) && $columnSchemas[$name]->type === Schema::TYPE_BINARY && is_string($value)) {
481
                    $columns[$name] = new PdoValue($value, \PDO::PARAM_LOB); // explicitly setup PDO param type for binary column
482
                }
483
            }
484
        }
485
486
        return $columns;
487
    }
488
489
    /**
490
     * {@inheritdoc}
491
     */
492
    public function batchInsert($table, $columns, $rows, &$params = [])
493
    {
494
        if (empty($rows)) {
495
            return '';
496
        }
497
498
        $schema = $this->db->getSchema();
499
        if (($tableSchema = $schema->getTableSchema($table)) !== null) {
500
            $columnSchemas = $tableSchema->columns;
501
        } else {
502
            $columnSchemas = [];
503
        }
504
505
        $values = [];
506
        foreach ($rows as $row) {
507
            $vs = [];
508
            foreach ($row as $i => $value) {
509
                if (isset($columns[$i], $columnSchemas[$columns[$i]])) {
510
                    $value = $columnSchemas[$columns[$i]]->dbTypecast($value);
511
                }
512
                if (is_string($value)) {
513
                    $value = $schema->quoteValue($value);
514
                } elseif (is_float($value)) {
515
                    // ensure type cast always has . as decimal separator in all locales
516
                    $value = StringHelper::floatToString($value);
517
                } elseif ($value === true) {
518
                    $value = 'TRUE';
519
                } elseif ($value === false) {
520
                    $value = 'FALSE';
521
                } elseif ($value === null) {
522
                    $value = 'NULL';
523
                } elseif ($value instanceof ExpressionInterface) {
524
                    $value = $this->buildExpression($value, $params);
525
                }
526
                $vs[] = $value;
527
            }
528
            $values[] = '(' . implode(', ', $vs) . ')';
529
        }
530
        if (empty($values)) {
531
            return '';
532
        }
533
534
        foreach ($columns as $i => $name) {
535
            $columns[$i] = $schema->quoteColumnName($name);
536
        }
537
538
        return 'INSERT INTO ' . $schema->quoteTableName($table)
539
        . ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values);
540
    }
541
}
542