1 | <?php |
||
2 | /** |
||
3 | * @link http://www.yiiframework.com/ |
||
4 | * @copyright Copyright (c) 2008 Yii Software LLC |
||
5 | * @license http://www.yiiframework.com/license/ |
||
6 | */ |
||
7 | |||
8 | namespace yii\db\pgsql; |
||
9 | |||
10 | use yii\base\InvalidArgumentException; |
||
11 | use yii\db\Constraint; |
||
12 | use yii\db\Expression; |
||
13 | use yii\db\ExpressionInterface; |
||
14 | use yii\db\Query; |
||
15 | use yii\db\PdoValue; |
||
16 | use yii\helpers\StringHelper; |
||
17 | |||
18 | /** |
||
19 | * QueryBuilder is the query builder for PostgreSQL databases. |
||
20 | * |
||
21 | * @author Gevik Babakhani <[email protected]> |
||
22 | * @since 2.0 |
||
23 | */ |
||
24 | class QueryBuilder extends \yii\db\QueryBuilder |
||
25 | { |
||
26 | /** |
||
27 | * Defines a UNIQUE index for [[createIndex()]]. |
||
28 | * @since 2.0.6 |
||
29 | */ |
||
30 | const INDEX_UNIQUE = 'unique'; |
||
31 | /** |
||
32 | * Defines a B-tree index for [[createIndex()]]. |
||
33 | * @since 2.0.6 |
||
34 | */ |
||
35 | const INDEX_B_TREE = 'btree'; |
||
36 | /** |
||
37 | * Defines a hash index for [[createIndex()]]. |
||
38 | * @since 2.0.6 |
||
39 | */ |
||
40 | const INDEX_HASH = 'hash'; |
||
41 | /** |
||
42 | * Defines a GiST index for [[createIndex()]]. |
||
43 | * @since 2.0.6 |
||
44 | */ |
||
45 | const INDEX_GIST = 'gist'; |
||
46 | /** |
||
47 | * Defines a GIN index for [[createIndex()]]. |
||
48 | * @since 2.0.6 |
||
49 | */ |
||
50 | const INDEX_GIN = 'gin'; |
||
51 | |||
52 | /** |
||
53 | * @var array mapping from abstract column types (keys) to physical column types (values). |
||
54 | */ |
||
55 | public $typeMap = [ |
||
56 | Schema::TYPE_PK => 'serial NOT NULL PRIMARY KEY', |
||
57 | Schema::TYPE_UPK => 'serial NOT NULL PRIMARY KEY', |
||
58 | Schema::TYPE_BIGPK => 'bigserial NOT NULL PRIMARY KEY', |
||
59 | Schema::TYPE_UBIGPK => 'bigserial NOT NULL PRIMARY KEY', |
||
60 | Schema::TYPE_CHAR => 'char(1)', |
||
61 | Schema::TYPE_STRING => 'varchar(255)', |
||
62 | Schema::TYPE_TEXT => 'text', |
||
63 | Schema::TYPE_TINYINT => 'smallint', |
||
64 | Schema::TYPE_SMALLINT => 'smallint', |
||
65 | Schema::TYPE_INTEGER => 'integer', |
||
66 | Schema::TYPE_BIGINT => 'bigint', |
||
67 | Schema::TYPE_FLOAT => 'double precision', |
||
68 | Schema::TYPE_DOUBLE => 'double precision', |
||
69 | Schema::TYPE_DECIMAL => 'numeric(10,0)', |
||
70 | Schema::TYPE_DATETIME => 'timestamp(0)', |
||
71 | Schema::TYPE_TIMESTAMP => 'timestamp(0)', |
||
72 | Schema::TYPE_TIME => 'time(0)', |
||
73 | Schema::TYPE_DATE => 'date', |
||
74 | Schema::TYPE_BINARY => 'bytea', |
||
75 | Schema::TYPE_BOOLEAN => 'boolean', |
||
76 | Schema::TYPE_MONEY => 'numeric(19,4)', |
||
77 | Schema::TYPE_JSON => 'jsonb', |
||
78 | ]; |
||
79 | |||
80 | |||
81 | /** |
||
82 | * {@inheritdoc} |
||
83 | */ |
||
84 | 612 | protected function defaultConditionClasses() |
|
85 | { |
||
86 | 612 | return array_merge(parent::defaultConditionClasses(), [ |
|
87 | 612 | 'ILIKE' => 'yii\db\conditions\LikeCondition', |
|
88 | 'NOT ILIKE' => 'yii\db\conditions\LikeCondition', |
||
89 | 'OR ILIKE' => 'yii\db\conditions\LikeCondition', |
||
90 | 'OR NOT ILIKE' => 'yii\db\conditions\LikeCondition', |
||
91 | ]); |
||
92 | } |
||
93 | |||
94 | /** |
||
95 | * {@inheritdoc} |
||
96 | */ |
||
97 | 612 | protected function defaultExpressionBuilders() |
|
98 | { |
||
99 | 612 | return array_merge(parent::defaultExpressionBuilders(), [ |
|
100 | 612 | 'yii\db\ArrayExpression' => 'yii\db\pgsql\ArrayExpressionBuilder', |
|
101 | 'yii\db\JsonExpression' => 'yii\db\pgsql\JsonExpressionBuilder', |
||
102 | ]); |
||
103 | } |
||
104 | |||
105 | /** |
||
106 | * Builds a SQL statement for creating a new index. |
||
107 | * @param string $name the name of the index. The name will be properly quoted by the method. |
||
108 | * @param string $table the table that the new index will be created for. The table name will be properly quoted by the method. |
||
109 | * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns, |
||
110 | * separate them with commas or use an array to represent them. Each column name will be properly quoted |
||
111 | * by the method, unless a parenthesis is found in the name. |
||
112 | * @param bool|string $unique whether to make this a UNIQUE index constraint. You can pass `true` or [[INDEX_UNIQUE]] to create |
||
113 | * a unique index, `false` to make a non-unique index using the default index type, or one of the following constants to specify |
||
114 | * the index method to use: [[INDEX_B_TREE]], [[INDEX_HASH]], [[INDEX_GIST]], [[INDEX_GIN]]. |
||
115 | * @return string the SQL statement for creating a new index. |
||
116 | * @see http://www.postgresql.org/docs/8.2/static/sql-createindex.html |
||
117 | */ |
||
118 | 6 | public function createIndex($name, $table, $columns, $unique = false) |
|
119 | { |
||
120 | 6 | if ($unique === self::INDEX_UNIQUE || $unique === true) { |
|
121 | 4 | $index = false; |
|
122 | 4 | $unique = true; |
|
123 | } else { |
||
124 | 3 | $index = $unique; |
|
125 | 3 | $unique = false; |
|
126 | } |
||
127 | |||
128 | 6 | return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ') . |
|
129 | 6 | $this->db->quoteTableName($name) . ' ON ' . |
|
130 | 6 | $this->db->quoteTableName($table) . |
|
131 | 6 | ($index !== false ? " USING $index" : '') . |
|
132 | 6 | ' (' . $this->buildColumns($columns) . ')'; |
|
133 | } |
||
134 | |||
135 | /** |
||
136 | * Builds a SQL statement for dropping an index. |
||
137 | * @param string $name the name of the index to be dropped. The name will be properly quoted by the method. |
||
138 | * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method. |
||
139 | * @return string the SQL statement for dropping an index. |
||
140 | */ |
||
141 | 3 | public function dropIndex($name, $table) |
|
142 | { |
||
143 | 3 | if (strpos($table, '.') !== false && strpos($name, '.') === false) { |
|
144 | 1 | if (strpos($table, '{{') !== false) { |
|
145 | 1 | $table = preg_replace('/\\{\\{(.*?)\\}\\}/', '\1', $table); |
|
146 | 1 | list($schema, $table) = explode('.', $table); |
|
147 | 1 | if (strpos($schema, '%') === false) |
|
148 | 1 | $name = $schema.'.'.$name; |
|
149 | else |
||
150 | 1 | $name = '{{'.$schema.'.'.$name.'}}'; |
|
151 | } else { |
||
152 | list($schema) = explode('.', $table); |
||
153 | $name = $schema.'.'.$name; |
||
154 | } |
||
155 | } |
||
156 | 3 | return 'DROP INDEX ' . $this->db->quoteTableName($name); |
|
157 | } |
||
158 | |||
159 | /** |
||
160 | * Builds a SQL statement for renaming a DB table. |
||
161 | * @param string $oldName the table to be renamed. The name will be properly quoted by the method. |
||
162 | * @param string $newName the new table name. The name will be properly quoted by the method. |
||
163 | * @return string the SQL statement for renaming a DB table. |
||
164 | */ |
||
165 | 2 | public function renameTable($oldName, $newName) |
|
166 | { |
||
167 | 2 | return 'ALTER TABLE ' . $this->db->quoteTableName($oldName) . ' RENAME TO ' . $this->db->quoteTableName($newName); |
|
168 | } |
||
169 | |||
170 | /** |
||
171 | * Creates a SQL statement for resetting the sequence value of a table's primary key. |
||
172 | * The sequence will be reset such that the primary key of the next new row inserted |
||
173 | * will have the specified value or 1. |
||
174 | * @param string $tableName the name of the table whose primary key sequence will be reset |
||
175 | * @param mixed $value the value for the primary key of the next new row inserted. If this is not set, |
||
176 | * the next new row's primary key will have a value 1. |
||
177 | * @return string the SQL statement for resetting sequence |
||
178 | * @throws InvalidArgumentException if the table does not exist or there is no sequence associated with the table. |
||
179 | */ |
||
180 | 6 | public function resetSequence($tableName, $value = null) |
|
181 | { |
||
182 | 6 | $table = $this->db->getTableSchema($tableName); |
|
183 | 6 | if ($table !== null && $table->sequenceName !== null) { |
|
184 | // c.f. http://www.postgresql.org/docs/8.1/static/functions-sequence.html |
||
185 | 6 | $sequence = $this->db->quoteTableName($table->sequenceName); |
|
186 | 6 | $tableName = $this->db->quoteTableName($tableName); |
|
187 | 6 | if ($value === null) { |
|
188 | 1 | $key = $this->db->quoteColumnName(reset($table->primaryKey)); |
|
189 | 1 | $value = "(SELECT COALESCE(MAX({$key}),0) FROM {$tableName})+1"; |
|
190 | } else { |
||
191 | 6 | $value = (int) $value; |
|
192 | } |
||
193 | |||
194 | 6 | return "SELECT SETVAL('$sequence',$value,false)"; |
|
195 | } elseif ($table === null) { |
||
196 | throw new InvalidArgumentException("Table not found: $tableName"); |
||
197 | } |
||
198 | |||
199 | throw new InvalidArgumentException("There is not sequence associated with table '$tableName'."); |
||
200 | } |
||
201 | |||
202 | /** |
||
203 | * Builds a SQL statement for enabling or disabling integrity check. |
||
204 | * @param bool $check whether to turn on or off the integrity check. |
||
205 | * @param string $schema the schema of the tables. |
||
206 | * @param string $table the table name. |
||
207 | * @return string the SQL statement for checking integrity |
||
208 | */ |
||
209 | public function checkIntegrity($check = true, $schema = '', $table = '') |
||
210 | { |
||
211 | $enable = $check ? 'ENABLE' : 'DISABLE'; |
||
212 | $schema = $schema ?: $this->db->getSchema()->defaultSchema; |
||
213 | $tableNames = $table ? [$table] : $this->db->getSchema()->getTableNames($schema); |
||
214 | $viewNames = $this->db->getSchema()->getViewNames($schema); |
||
215 | $tableNames = array_diff($tableNames, $viewNames); |
||
216 | $command = ''; |
||
217 | |||
218 | foreach ($tableNames as $tableName) { |
||
219 | $tableName = $this->db->quoteTableName("{$schema}.{$tableName}"); |
||
220 | $command .= "ALTER TABLE $tableName $enable TRIGGER ALL; "; |
||
221 | } |
||
222 | |||
223 | // enable to have ability to alter several tables |
||
224 | $this->db->getMasterPdo()->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true); |
||
225 | |||
226 | return $command; |
||
227 | } |
||
228 | |||
229 | /** |
||
230 | * Builds a SQL statement for truncating a DB table. |
||
231 | * Explicitly restarts identity for PGSQL to be consistent with other databases which all do this by default. |
||
232 | * @param string $table the table to be truncated. The name will be properly quoted by the method. |
||
233 | * @return string the SQL statement for truncating a DB table. |
||
234 | */ |
||
235 | 1 | public function truncateTable($table) |
|
236 | { |
||
237 | 1 | return 'TRUNCATE TABLE ' . $this->db->quoteTableName($table) . ' RESTART IDENTITY'; |
|
238 | } |
||
239 | |||
240 | /** |
||
241 | * Builds a SQL statement for changing the definition of a column. |
||
242 | * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method. |
||
243 | * @param string $column the name of the column to be changed. The name will be properly quoted by the method. |
||
244 | * @param string $type the new column type. The [[getColumnType()]] method will be invoked to convert abstract |
||
245 | * column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept |
||
246 | * in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null' |
||
247 | * will become 'varchar(255) not null'. You can also use PostgreSQL-specific syntax such as `SET NOT NULL`. |
||
248 | * @return string the SQL statement for changing the definition of a column. |
||
249 | */ |
||
250 | 2 | public function alterColumn($table, $column, $type) |
|
251 | { |
||
252 | 2 | $columnName = $this->db->quoteColumnName($column); |
|
253 | 2 | $tableName = $this->db->quoteTableName($table); |
|
254 | |||
255 | // https://github.com/yiisoft/yii2/issues/4492 |
||
256 | // http://www.postgresql.org/docs/9.1/static/sql-altertable.html |
||
257 | 2 | if (preg_match('/^(DROP|SET|RESET)\s+/i', $type)) { |
|
258 | 1 | return "ALTER TABLE {$tableName} ALTER COLUMN {$columnName} {$type}"; |
|
259 | } |
||
260 | |||
261 | 2 | $type = 'TYPE ' . $this->getColumnType($type); |
|
262 | |||
263 | 2 | $multiAlterStatement = []; |
|
264 | 2 | $constraintPrefix = preg_replace('/[^a-z0-9_]/i', '', $table . '_' . $column); |
|
265 | |||
266 | 2 | if (preg_match('/\s+DEFAULT\s+(["\']?\w*["\']?)/i', $type, $matches)) { |
|
267 | 1 | $type = preg_replace('/\s+DEFAULT\s+(["\']?\w*["\']?)/i', '', $type); |
|
268 | 1 | $multiAlterStatement[] = "ALTER COLUMN {$columnName} SET DEFAULT {$matches[1]}"; |
|
269 | } else { |
||
270 | // safe to drop default even if there was none in the first place |
||
271 | 2 | $multiAlterStatement[] = "ALTER COLUMN {$columnName} DROP DEFAULT"; |
|
272 | } |
||
273 | |||
274 | 2 | $type = preg_replace('/\s+NOT\s+NULL/i', '', $type, -1, $count); |
|
275 | 2 | if ($count) { |
|
276 | 1 | $multiAlterStatement[] = "ALTER COLUMN {$columnName} SET NOT NULL"; |
|
277 | } else { |
||
278 | // remove additional null if any |
||
279 | 2 | $type = preg_replace('/\s+NULL/i', '', $type); |
|
280 | // safe to drop not null even if there was none in the first place |
||
281 | 2 | $multiAlterStatement[] = "ALTER COLUMN {$columnName} DROP NOT NULL"; |
|
282 | } |
||
283 | |||
284 | 2 | if (preg_match('/\s+CHECK\s+\((.+)\)/i', $type, $matches)) { |
|
285 | 1 | $type = preg_replace('/\s+CHECK\s+\((.+)\)/i', '', $type); |
|
286 | 1 | $multiAlterStatement[] = "ADD CONSTRAINT {$constraintPrefix}_check CHECK ({$matches[1]})"; |
|
287 | } |
||
288 | |||
289 | 2 | $type = preg_replace('/\s+UNIQUE/i', '', $type, -1, $count); |
|
290 | 2 | if ($count) { |
|
291 | 1 | $multiAlterStatement[] = "ADD UNIQUE ({$columnName})"; |
|
292 | } |
||
293 | |||
294 | // add what's left at the beginning |
||
295 | 2 | array_unshift($multiAlterStatement, "ALTER COLUMN {$columnName} {$type}"); |
|
296 | |||
297 | 2 | return 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $multiAlterStatement); |
|
298 | } |
||
299 | |||
300 | /** |
||
301 | * {@inheritdoc} |
||
302 | */ |
||
303 | 200 | public function insert($table, $columns, &$params) |
|
304 | { |
||
305 | 200 | return parent::insert($table, $this->normalizeTableRowData($table, $columns), $params); |
|
306 | } |
||
307 | |||
308 | /** |
||
309 | * {@inheritdoc} |
||
310 | * @see https://www.postgresql.org/docs/9.5/static/sql-insert.html#SQL-ON-CONFLICT |
||
311 | * @see https://stackoverflow.com/questions/1109061/insert-on-duplicate-update-in-postgresql/8702291#8702291 |
||
312 | */ |
||
313 | 41 | public function upsert($table, $insertColumns, $updateColumns, &$params) |
|
314 | { |
||
315 | 41 | $insertColumns = $this->normalizeTableRowData($table, $insertColumns); |
|
316 | 41 | if (!is_bool($updateColumns)) { |
|
317 | 7 | $updateColumns = $this->normalizeTableRowData($table, $updateColumns); |
|
318 | } |
||
319 | 41 | if (version_compare($this->db->getServerVersion(), '9.5', '<')) { |
|
320 | return $this->oldUpsert($table, $insertColumns, $updateColumns, $params); |
||
321 | } |
||
322 | |||
323 | 41 | return $this->newUpsert($table, $insertColumns, $updateColumns, $params); |
|
324 | } |
||
325 | |||
326 | /** |
||
327 | * [[upsert()]] implementation for PostgreSQL 9.5 or higher. |
||
328 | * @param string $table |
||
329 | * @param array|Query $insertColumns |
||
330 | * @param array|bool $updateColumns |
||
331 | * @param array $params |
||
332 | * @return string |
||
333 | */ |
||
334 | 41 | private function newUpsert($table, $insertColumns, $updateColumns, &$params) |
|
335 | { |
||
336 | 41 | $insertSql = $this->insert($table, $insertColumns, $params); |
|
337 | 41 | list($uniqueNames, , $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns); |
|
338 | 41 | if (empty($uniqueNames)) { |
|
339 | 3 | return $insertSql; |
|
340 | } |
||
341 | 38 | if ($updateNames === []) { |
|
342 | // there are no columns to update |
||
343 | 1 | $updateColumns = false; |
|
344 | } |
||
345 | |||
346 | 38 | if ($updateColumns === false) { |
|
347 | 5 | return "$insertSql ON CONFLICT DO NOTHING"; |
|
348 | } |
||
349 | |||
350 | 33 | if ($updateColumns === true) { |
|
351 | 27 | $updateColumns = []; |
|
352 | 27 | foreach ($updateNames as $name) { |
|
353 | 27 | $updateColumns[$name] = new Expression('EXCLUDED.' . $this->db->quoteColumnName($name)); |
|
354 | } |
||
355 | } |
||
356 | 33 | list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params); |
|
357 | 33 | return $insertSql . ' ON CONFLICT (' . implode(', ', $uniqueNames) . ') DO UPDATE SET ' . implode(', ', $updates); |
|
358 | } |
||
359 | |||
360 | /** |
||
361 | * [[upsert()]] implementation for PostgreSQL older than 9.5. |
||
362 | * @param string $table |
||
363 | * @param array|Query $insertColumns |
||
364 | * @param array|bool $updateColumns |
||
365 | * @param array $params |
||
366 | * @return string |
||
367 | */ |
||
368 | private function oldUpsert($table, $insertColumns, $updateColumns, &$params) |
||
369 | { |
||
370 | /** @var Constraint[] $constraints */ |
||
371 | list($uniqueNames, $insertNames, $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns, $constraints); |
||
372 | if (empty($uniqueNames)) { |
||
373 | return $this->insert($table, $insertColumns, $params); |
||
374 | } |
||
375 | if ($updateNames === []) { |
||
376 | // there are no columns to update |
||
377 | $updateColumns = false; |
||
378 | } |
||
379 | |||
380 | /** @var Schema $schema */ |
||
381 | $schema = $this->db->getSchema(); |
||
382 | if (!$insertColumns instanceof Query) { |
||
383 | $tableSchema = $schema->getTableSchema($table); |
||
384 | $columnSchemas = $tableSchema !== null ? $tableSchema->columns : []; |
||
385 | foreach ($insertColumns as $name => $value) { |
||
386 | // NULLs and numeric values must be type hinted in order to be used in SET assigments |
||
387 | // NVM, let's cast them all |
||
388 | if (isset($columnSchemas[$name])) { |
||
389 | $phName = self::PARAM_PREFIX . count($params); |
||
390 | $params[$phName] = $value; |
||
391 | $insertColumns[$name] = new Expression("CAST($phName AS {$columnSchemas[$name]->dbType})"); |
||
392 | } |
||
393 | } |
||
394 | } |
||
395 | list(, $placeholders, $values, $params) = $this->prepareInsertValues($table, $insertColumns, $params); |
||
396 | $updateCondition = ['or']; |
||
397 | $insertCondition = ['or']; |
||
398 | $quotedTableName = $schema->quoteTableName($table); |
||
399 | foreach ($constraints as $constraint) { |
||
400 | $constraintUpdateCondition = ['and']; |
||
401 | $constraintInsertCondition = ['and']; |
||
402 | foreach ($constraint->columnNames as $name) { |
||
403 | $quotedName = $schema->quoteColumnName($name); |
||
404 | $constraintUpdateCondition[] = "$quotedTableName.$quotedName=\"EXCLUDED\".$quotedName"; |
||
405 | $constraintInsertCondition[] = "\"upsert\".$quotedName=\"EXCLUDED\".$quotedName"; |
||
406 | } |
||
407 | $updateCondition[] = $constraintUpdateCondition; |
||
408 | $insertCondition[] = $constraintInsertCondition; |
||
409 | } |
||
410 | $withSql = 'WITH "EXCLUDED" (' . implode(', ', $insertNames) |
||
411 | . ') AS (' . (!empty($placeholders) ? 'VALUES (' . implode(', ', $placeholders) . ')' : ltrim($values, ' ')) . ')'; |
||
412 | if ($updateColumns === false) { |
||
413 | $selectSubQuery = (new Query()) |
||
414 | ->select(new Expression('1')) |
||
415 | ->from($table) |
||
416 | ->where($updateCondition); |
||
417 | $insertSelectSubQuery = (new Query()) |
||
418 | ->select($insertNames) |
||
419 | ->from('EXCLUDED') |
||
420 | ->where(['not exists', $selectSubQuery]); |
||
421 | $insertSql = $this->insert($table, $insertSelectSubQuery, $params); |
||
422 | return "$withSql $insertSql"; |
||
423 | } |
||
424 | |||
425 | if ($updateColumns === true) { |
||
426 | $updateColumns = []; |
||
427 | foreach ($updateNames as $name) { |
||
428 | $quotedName = $this->db->quoteColumnName($name); |
||
429 | if (strrpos($quotedName, '.') === false) { |
||
430 | $quotedName = '"EXCLUDED".' . $quotedName; |
||
431 | } |
||
432 | $updateColumns[$name] = new Expression($quotedName); |
||
433 | } |
||
434 | } |
||
435 | list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params); |
||
436 | $updateSql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $updates) |
||
437 | . ' FROM "EXCLUDED" ' . $this->buildWhere($updateCondition, $params) |
||
438 | . ' RETURNING ' . $this->db->quoteTableName($table) .'.*'; |
||
439 | $selectUpsertSubQuery = (new Query()) |
||
440 | ->select(new Expression('1')) |
||
441 | ->from('upsert') |
||
442 | ->where($insertCondition); |
||
443 | $insertSelectSubQuery = (new Query()) |
||
444 | ->select($insertNames) |
||
445 | ->from('EXCLUDED') |
||
446 | ->where(['not exists', $selectUpsertSubQuery]); |
||
447 | $insertSql = $this->insert($table, $insertSelectSubQuery, $params); |
||
448 | return "$withSql, \"upsert\" AS ($updateSql) $insertSql"; |
||
449 | } |
||
450 | |||
451 | /** |
||
452 | * {@inheritdoc} |
||
453 | */ |
||
454 | 33 | public function update($table, $columns, $condition, &$params) |
|
455 | { |
||
456 | 33 | return parent::update($table, $this->normalizeTableRowData($table, $columns), $condition, $params); |
|
457 | } |
||
458 | |||
459 | /** |
||
460 | * Normalizes data to be saved into the table, performing extra preparations and type converting, if necessary. |
||
461 | * |
||
462 | * @param string $table the table that data will be saved into. |
||
463 | * @param array|Query $columns the column data (name => value) to be saved into the table or instance |
||
464 | * of [[yii\db\Query|Query]] to perform INSERT INTO ... SELECT SQL statement. |
||
465 | * Passing of [[yii\db\Query|Query]] is available since version 2.0.11. |
||
466 | * @return array normalized columns |
||
467 | * @since 2.0.9 |
||
468 | */ |
||
469 | 214 | private function normalizeTableRowData($table, $columns) |
|
470 | { |
||
471 | 214 | if ($columns instanceof Query) { |
|
472 | 14 | return $columns; |
|
0 ignored issues
–
show
Bug
Best Practice
introduced
by
![]() |
|||
473 | } |
||
474 | |||
475 | 206 | if (($tableSchema = $this->db->getSchema()->getTableSchema($table)) !== null) { |
|
476 | 206 | $columnSchemas = $tableSchema->columns; |
|
477 | 206 | foreach ($columns as $name => $value) { |
|
478 | 205 | if (isset($columnSchemas[$name]) && $columnSchemas[$name]->type === Schema::TYPE_BINARY && is_string($value)) { |
|
479 | 205 | $columns[$name] = new PdoValue($value, \PDO::PARAM_LOB); // explicitly setup PDO param type for binary column |
|
480 | } |
||
481 | } |
||
482 | } |
||
483 | |||
484 | 206 | return $columns; |
|
485 | } |
||
486 | |||
487 | /** |
||
488 | * {@inheritdoc} |
||
489 | */ |
||
490 | 22 | public function batchInsert($table, $columns, $rows, &$params = []) |
|
491 | { |
||
492 | 22 | if (empty($rows)) { |
|
493 | 2 | return ''; |
|
494 | } |
||
495 | |||
496 | 21 | $schema = $this->db->getSchema(); |
|
497 | 21 | if (($tableSchema = $schema->getTableSchema($table)) !== null) { |
|
498 | 21 | $columnSchemas = $tableSchema->columns; |
|
499 | } else { |
||
500 | $columnSchemas = []; |
||
501 | } |
||
502 | |||
503 | 21 | $values = []; |
|
504 | 21 | foreach ($rows as $row) { |
|
505 | 19 | $vs = []; |
|
506 | 19 | foreach ($row as $i => $value) { |
|
507 | 19 | if (isset($columns[$i], $columnSchemas[$columns[$i]])) { |
|
508 | 16 | $value = $columnSchemas[$columns[$i]]->dbTypecast($value); |
|
509 | } |
||
510 | 19 | if (is_string($value)) { |
|
511 | 8 | $value = $schema->quoteValue($value); |
|
512 | 14 | } elseif (is_float($value)) { |
|
513 | // ensure type cast always has . as decimal separator in all locales |
||
514 | 1 | $value = StringHelper::floatToString($value); |
|
515 | 14 | } elseif ($value === true) { |
|
516 | 4 | $value = 'TRUE'; |
|
517 | 14 | } elseif ($value === false) { |
|
518 | 6 | $value = 'FALSE'; |
|
519 | 11 | } elseif ($value === null) { |
|
520 | 4 | $value = 'NULL'; |
|
521 | 8 | } elseif ($value instanceof ExpressionInterface) { |
|
522 | 6 | $value = $this->buildExpression($value, $params); |
|
523 | } |
||
524 | 19 | $vs[] = $value; |
|
525 | } |
||
526 | 19 | $values[] = '(' . implode(', ', $vs) . ')'; |
|
527 | } |
||
528 | 21 | if (empty($values)) { |
|
529 | 2 | return ''; |
|
530 | } |
||
531 | |||
532 | 19 | foreach ($columns as $i => $name) { |
|
533 | 18 | $columns[$i] = $schema->quoteColumnName($name); |
|
534 | } |
||
535 | |||
536 | 19 | return 'INSERT INTO ' . $schema->quoteTableName($table) |
|
537 | 19 | . ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values); |
|
538 | } |
||
539 | } |
||
540 |