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