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
|
564 |
|
protected function defaultConditionClasses() |
85
|
|
|
{ |
86
|
564 |
|
return array_merge(parent::defaultConditionClasses(), [ |
87
|
564 |
|
'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
|
564 |
|
protected function defaultExpressionBuilders() |
98
|
|
|
{ |
99
|
564 |
|
return array_merge(parent::defaultExpressionBuilders(), [ |
100
|
564 |
|
'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
|
197 |
|
public function insert($table, $columns, &$params) |
304
|
|
|
{ |
305
|
197 |
|
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
|
39 |
|
public function upsert($table, $insertColumns, $updateColumns, &$params) |
314
|
|
|
{ |
315
|
39 |
|
$insertColumns = $this->normalizeTableRowData($table, $insertColumns); |
316
|
39 |
|
if (!is_bool($updateColumns)) { |
317
|
7 |
|
$updateColumns = $this->normalizeTableRowData($table, $updateColumns); |
318
|
|
|
} |
319
|
39 |
|
if (version_compare($this->db->getServerVersion(), '9.5', '<')) { |
320
|
|
|
return $this->oldUpsert($table, $insertColumns, $updateColumns, $params); |
321
|
|
|
} |
322
|
|
|
|
323
|
39 |
|
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
|
39 |
|
private function newUpsert($table, $insertColumns, $updateColumns, &$params) |
335
|
|
|
{ |
336
|
39 |
|
$insertSql = $this->insert($table, $insertColumns, $params); |
337
|
39 |
|
list($uniqueNames, , $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns); |
338
|
39 |
|
if (empty($uniqueNames)) { |
339
|
3 |
|
return $insertSql; |
340
|
|
|
} |
341
|
|
|
|
342
|
36 |
|
if ($updateColumns === false) { |
343
|
4 |
|
return "$insertSql ON CONFLICT DO NOTHING"; |
344
|
|
|
} |
345
|
|
|
|
346
|
32 |
|
if ($updateColumns === true) { |
347
|
26 |
|
$updateColumns = []; |
348
|
26 |
|
foreach ($updateNames as $name) { |
349
|
26 |
|
$updateColumns[$name] = new Expression('EXCLUDED.' . $this->db->quoteColumnName($name)); |
350
|
|
|
} |
351
|
|
|
} |
352
|
32 |
|
list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params); |
353
|
32 |
|
return $insertSql . ' ON CONFLICT (' . implode(', ', $uniqueNames) . ') DO UPDATE SET ' . implode(', ', $updates); |
354
|
|
|
} |
355
|
|
|
|
356
|
|
|
/** |
357
|
|
|
* [[upsert()]] implementation for PostgreSQL older than 9.5. |
358
|
|
|
* @param string $table |
359
|
|
|
* @param array|Query $insertColumns |
360
|
|
|
* @param array|bool $updateColumns |
361
|
|
|
* @param array $params |
362
|
|
|
* @return string |
363
|
|
|
*/ |
364
|
|
|
private function oldUpsert($table, $insertColumns, $updateColumns, &$params) |
365
|
|
|
{ |
366
|
|
|
/** @var Constraint[] $constraints */ |
367
|
|
|
list($uniqueNames, $insertNames, $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns, $constraints); |
368
|
|
|
if (empty($uniqueNames)) { |
369
|
|
|
return $this->insert($table, $insertColumns, $params); |
370
|
|
|
} |
371
|
|
|
|
372
|
|
|
/** @var Schema $schema */ |
373
|
|
|
$schema = $this->db->getSchema(); |
374
|
|
|
if (!$insertColumns instanceof Query) { |
375
|
|
|
$tableSchema = $schema->getTableSchema($table); |
376
|
|
|
$columnSchemas = $tableSchema !== null ? $tableSchema->columns : []; |
377
|
|
|
foreach ($insertColumns as $name => $value) { |
378
|
|
|
// NULLs and numeric values must be type hinted in order to be used in SET assigments |
379
|
|
|
// NVM, let's cast them all |
380
|
|
|
if (isset($columnSchemas[$name])) { |
381
|
|
|
$phName = self::PARAM_PREFIX . count($params); |
382
|
|
|
$params[$phName] = $value; |
383
|
|
|
$insertColumns[$name] = new Expression("CAST($phName AS {$columnSchemas[$name]->dbType})"); |
384
|
|
|
} |
385
|
|
|
} |
386
|
|
|
} |
387
|
|
|
list(, $placeholders, $values, $params) = $this->prepareInsertValues($table, $insertColumns, $params); |
388
|
|
|
$updateCondition = ['or']; |
389
|
|
|
$insertCondition = ['or']; |
390
|
|
|
$quotedTableName = $schema->quoteTableName($table); |
391
|
|
|
foreach ($constraints as $constraint) { |
392
|
|
|
$constraintUpdateCondition = ['and']; |
393
|
|
|
$constraintInsertCondition = ['and']; |
394
|
|
|
foreach ($constraint->columnNames as $name) { |
395
|
|
|
$quotedName = $schema->quoteColumnName($name); |
396
|
|
|
$constraintUpdateCondition[] = "$quotedTableName.$quotedName=\"EXCLUDED\".$quotedName"; |
397
|
|
|
$constraintInsertCondition[] = "\"upsert\".$quotedName=\"EXCLUDED\".$quotedName"; |
398
|
|
|
} |
399
|
|
|
$updateCondition[] = $constraintUpdateCondition; |
400
|
|
|
$insertCondition[] = $constraintInsertCondition; |
401
|
|
|
} |
402
|
|
|
$withSql = 'WITH "EXCLUDED" (' . implode(', ', $insertNames) |
403
|
|
|
. ') AS (' . (!empty($placeholders) ? 'VALUES (' . implode(', ', $placeholders) . ')' : ltrim($values, ' ')) . ')'; |
404
|
|
|
if ($updateColumns === false) { |
405
|
|
|
$selectSubQuery = (new Query()) |
406
|
|
|
->select(new Expression('1')) |
407
|
|
|
->from($table) |
408
|
|
|
->where($updateCondition); |
409
|
|
|
$insertSelectSubQuery = (new Query()) |
410
|
|
|
->select($insertNames) |
411
|
|
|
->from('EXCLUDED') |
412
|
|
|
->where(['not exists', $selectSubQuery]); |
413
|
|
|
$insertSql = $this->insert($table, $insertSelectSubQuery, $params); |
414
|
|
|
return "$withSql $insertSql"; |
415
|
|
|
} |
416
|
|
|
|
417
|
|
|
if ($updateColumns === true) { |
418
|
|
|
$updateColumns = []; |
419
|
|
|
foreach ($updateNames as $name) { |
420
|
|
|
$quotedName = $this->db->quoteColumnName($name); |
421
|
|
|
if (strrpos($quotedName, '.') === false) { |
422
|
|
|
$quotedName = '"EXCLUDED".' . $quotedName; |
423
|
|
|
} |
424
|
|
|
$updateColumns[$name] = new Expression($quotedName); |
425
|
|
|
} |
426
|
|
|
} |
427
|
|
|
list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params); |
428
|
|
|
$updateSql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $updates) |
429
|
|
|
. ' FROM "EXCLUDED" ' . $this->buildWhere($updateCondition, $params) |
430
|
|
|
. ' RETURNING ' . $this->db->quoteTableName($table) .'.*'; |
431
|
|
|
$selectUpsertSubQuery = (new Query()) |
432
|
|
|
->select(new Expression('1')) |
433
|
|
|
->from('upsert') |
434
|
|
|
->where($insertCondition); |
435
|
|
|
$insertSelectSubQuery = (new Query()) |
436
|
|
|
->select($insertNames) |
437
|
|
|
->from('EXCLUDED') |
438
|
|
|
->where(['not exists', $selectUpsertSubQuery]); |
439
|
|
|
$insertSql = $this->insert($table, $insertSelectSubQuery, $params); |
440
|
|
|
return "$withSql, \"upsert\" AS ($updateSql) $insertSql"; |
441
|
|
|
} |
442
|
|
|
|
443
|
|
|
/** |
444
|
|
|
* {@inheritdoc} |
445
|
|
|
*/ |
446
|
31 |
|
public function update($table, $columns, $condition, &$params) |
447
|
|
|
{ |
448
|
31 |
|
return parent::update($table, $this->normalizeTableRowData($table, $columns), $condition, $params); |
449
|
|
|
} |
450
|
|
|
|
451
|
|
|
/** |
452
|
|
|
* Normalizes data to be saved into the table, performing extra preparations and type converting, if necessary. |
453
|
|
|
* |
454
|
|
|
* @param string $table the table that data will be saved into. |
455
|
|
|
* @param array|Query $columns the column data (name => value) to be saved into the table or instance |
456
|
|
|
* of [[yii\db\Query|Query]] to perform INSERT INTO ... SELECT SQL statement. |
457
|
|
|
* Passing of [[yii\db\Query|Query]] is available since version 2.0.11. |
458
|
|
|
* @return array normalized columns |
459
|
|
|
* @since 2.0.9 |
460
|
|
|
*/ |
461
|
209 |
|
private function normalizeTableRowData($table, $columns) |
462
|
|
|
{ |
463
|
209 |
|
if ($columns instanceof Query) { |
464
|
14 |
|
return $columns; |
|
|
|
|
465
|
|
|
} |
466
|
|
|
|
467
|
201 |
|
if (($tableSchema = $this->db->getSchema()->getTableSchema($table)) !== null) { |
468
|
201 |
|
$columnSchemas = $tableSchema->columns; |
469
|
201 |
|
foreach ($columns as $name => $value) { |
470
|
200 |
|
if (isset($columnSchemas[$name]) && $columnSchemas[$name]->type === Schema::TYPE_BINARY && is_string($value)) { |
471
|
200 |
|
$columns[$name] = new PdoValue($value, \PDO::PARAM_LOB); // explicitly setup PDO param type for binary column |
472
|
|
|
} |
473
|
|
|
} |
474
|
|
|
} |
475
|
|
|
|
476
|
201 |
|
return $columns; |
477
|
|
|
} |
478
|
|
|
|
479
|
|
|
/** |
480
|
|
|
* {@inheritdoc} |
481
|
|
|
*/ |
482
|
22 |
|
public function batchInsert($table, $columns, $rows, &$params = []) |
483
|
|
|
{ |
484
|
22 |
|
if (empty($rows)) { |
485
|
2 |
|
return ''; |
486
|
|
|
} |
487
|
|
|
|
488
|
21 |
|
$schema = $this->db->getSchema(); |
489
|
21 |
|
if (($tableSchema = $schema->getTableSchema($table)) !== null) { |
490
|
21 |
|
$columnSchemas = $tableSchema->columns; |
491
|
|
|
} else { |
492
|
|
|
$columnSchemas = []; |
493
|
|
|
} |
494
|
|
|
|
495
|
21 |
|
$values = []; |
496
|
21 |
|
foreach ($rows as $row) { |
497
|
19 |
|
$vs = []; |
498
|
19 |
|
foreach ($row as $i => $value) { |
499
|
19 |
|
if (isset($columns[$i], $columnSchemas[$columns[$i]])) { |
500
|
16 |
|
$value = $columnSchemas[$columns[$i]]->dbTypecast($value); |
501
|
|
|
} |
502
|
19 |
|
if (is_string($value)) { |
503
|
8 |
|
$value = $schema->quoteValue($value); |
504
|
14 |
|
} elseif (is_float($value)) { |
505
|
|
|
// ensure type cast always has . as decimal separator in all locales |
506
|
1 |
|
$value = StringHelper::floatToString($value); |
507
|
14 |
|
} elseif ($value === true) { |
508
|
4 |
|
$value = 'TRUE'; |
509
|
14 |
|
} elseif ($value === false) { |
510
|
6 |
|
$value = 'FALSE'; |
511
|
11 |
|
} elseif ($value === null) { |
512
|
4 |
|
$value = 'NULL'; |
513
|
8 |
|
} elseif ($value instanceof ExpressionInterface) { |
514
|
6 |
|
$value = $this->buildExpression($value, $params); |
515
|
|
|
} |
516
|
19 |
|
$vs[] = $value; |
517
|
|
|
} |
518
|
19 |
|
$values[] = '(' . implode(', ', $vs) . ')'; |
519
|
|
|
} |
520
|
21 |
|
if (empty($values)) { |
521
|
2 |
|
return ''; |
522
|
|
|
} |
523
|
|
|
|
524
|
19 |
|
foreach ($columns as $i => $name) { |
525
|
18 |
|
$columns[$i] = $schema->quoteColumnName($name); |
526
|
|
|
} |
527
|
|
|
|
528
|
19 |
|
return 'INSERT INTO ' . $schema->quoteTableName($table) |
529
|
19 |
|
. ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values); |
530
|
|
|
} |
531
|
|
|
} |
532
|
|
|
|