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\mssql; |
9
|
|
|
|
10
|
|
|
use yii\base\InvalidArgumentException; |
11
|
|
|
use yii\db\Constraint; |
12
|
|
|
use yii\db\Expression; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* QueryBuilder is the query builder for MS SQL Server databases (version 2008 and above). |
16
|
|
|
* |
17
|
|
|
* @author Timur Ruziev <[email protected]> |
18
|
|
|
* @since 2.0 |
19
|
|
|
*/ |
20
|
|
|
class QueryBuilder extends \yii\db\QueryBuilder |
21
|
|
|
{ |
22
|
|
|
/** |
23
|
|
|
* @var array mapping from abstract column types (keys) to physical column types (values). |
24
|
|
|
*/ |
25
|
|
|
public $typeMap = [ |
26
|
|
|
Schema::TYPE_PK => 'int IDENTITY PRIMARY KEY', |
27
|
|
|
Schema::TYPE_UPK => 'int IDENTITY PRIMARY KEY', |
28
|
|
|
Schema::TYPE_BIGPK => 'bigint IDENTITY PRIMARY KEY', |
29
|
|
|
Schema::TYPE_UBIGPK => 'bigint IDENTITY PRIMARY KEY', |
30
|
|
|
Schema::TYPE_CHAR => 'nchar(1)', |
31
|
|
|
Schema::TYPE_STRING => 'nvarchar(255)', |
32
|
|
|
Schema::TYPE_TEXT => 'nvarchar(max)', |
33
|
|
|
Schema::TYPE_TINYINT => 'tinyint', |
34
|
|
|
Schema::TYPE_SMALLINT => 'smallint', |
35
|
|
|
Schema::TYPE_INTEGER => 'int', |
36
|
|
|
Schema::TYPE_BIGINT => 'bigint', |
37
|
|
|
Schema::TYPE_FLOAT => 'float', |
38
|
|
|
Schema::TYPE_DOUBLE => 'float', |
39
|
|
|
Schema::TYPE_DECIMAL => 'decimal(18,0)', |
40
|
|
|
Schema::TYPE_DATETIME => 'datetime', |
41
|
|
|
Schema::TYPE_TIMESTAMP => 'datetime', |
42
|
|
|
Schema::TYPE_TIME => 'time', |
43
|
|
|
Schema::TYPE_DATE => 'date', |
44
|
|
|
Schema::TYPE_BINARY => 'varbinary(max)', |
45
|
|
|
Schema::TYPE_BOOLEAN => 'bit', |
46
|
|
|
Schema::TYPE_MONEY => 'decimal(19,4)', |
47
|
|
|
]; |
48
|
|
|
|
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* {@inheritdoc} |
52
|
|
|
*/ |
53
|
379 |
|
protected function defaultExpressionBuilders() |
54
|
|
|
{ |
55
|
379 |
|
return array_merge(parent::defaultExpressionBuilders(), [ |
56
|
379 |
|
'yii\db\conditions\InCondition' => 'yii\db\mssql\conditions\InConditionBuilder', |
57
|
|
|
'yii\db\conditions\LikeCondition' => 'yii\db\mssql\conditions\LikeConditionBuilder', |
58
|
|
|
]); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* {@inheritdoc} |
63
|
|
|
*/ |
64
|
300 |
|
public function buildOrderByAndLimit($sql, $orderBy, $limit, $offset) |
65
|
|
|
{ |
66
|
300 |
|
if (!$this->hasOffset($offset) && !$this->hasLimit($limit)) { |
67
|
291 |
|
$orderBy = $this->buildOrderBy($orderBy); |
68
|
291 |
|
return $orderBy === '' ? $sql : $sql . $this->separator . $orderBy; |
69
|
|
|
} |
70
|
|
|
|
71
|
30 |
|
if (version_compare($this->db->getSchema()->getServerVersion(), '11', '<')) { |
72
|
|
|
return $this->oldBuildOrderByAndLimit($sql, $orderBy, $limit, $offset); |
73
|
|
|
} |
74
|
|
|
|
75
|
30 |
|
return $this->newBuildOrderByAndLimit($sql, $orderBy, $limit, $offset); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* Builds the ORDER BY/LIMIT/OFFSET clauses for SQL SERVER 2012 or newer. |
80
|
|
|
* @param string $sql the existing SQL (without ORDER BY/LIMIT/OFFSET) |
81
|
|
|
* @param array $orderBy the order by columns. See [[\yii\db\Query::orderBy]] for more details on how to specify this parameter. |
82
|
|
|
* @param int $limit the limit number. See [[\yii\db\Query::limit]] for more details. |
83
|
|
|
* @param int $offset the offset number. See [[\yii\db\Query::offset]] for more details. |
84
|
|
|
* @return string the SQL completed with ORDER BY/LIMIT/OFFSET (if any) |
85
|
|
|
*/ |
86
|
30 |
|
protected function newBuildOrderByAndLimit($sql, $orderBy, $limit, $offset) |
87
|
|
|
{ |
88
|
30 |
|
$orderBy = $this->buildOrderBy($orderBy); |
89
|
30 |
|
if ($orderBy === '') { |
90
|
|
|
// ORDER BY clause is required when FETCH and OFFSET are in the SQL |
91
|
23 |
|
$orderBy = 'ORDER BY (SELECT NULL)'; |
92
|
|
|
} |
93
|
30 |
|
$sql .= $this->separator . $orderBy; |
94
|
|
|
|
95
|
|
|
// http://technet.microsoft.com/en-us/library/gg699618.aspx |
96
|
30 |
|
$offset = $this->hasOffset($offset) ? $offset : '0'; |
97
|
30 |
|
$sql .= $this->separator . "OFFSET $offset ROWS"; |
98
|
30 |
|
if ($this->hasLimit($limit)) { |
99
|
28 |
|
$sql .= $this->separator . "FETCH NEXT $limit ROWS ONLY"; |
100
|
|
|
} |
101
|
|
|
|
102
|
30 |
|
return $sql; |
103
|
|
|
} |
104
|
|
|
|
105
|
|
|
/** |
106
|
|
|
* Builds the ORDER BY/LIMIT/OFFSET clauses for SQL SERVER 2005 to 2008. |
107
|
|
|
* @param string $sql the existing SQL (without ORDER BY/LIMIT/OFFSET) |
108
|
|
|
* @param array $orderBy the order by columns. See [[\yii\db\Query::orderBy]] for more details on how to specify this parameter. |
109
|
|
|
* @param int $limit the limit number. See [[\yii\db\Query::limit]] for more details. |
110
|
|
|
* @param int $offset the offset number. See [[\yii\db\Query::offset]] for more details. |
111
|
|
|
* @return string the SQL completed with ORDER BY/LIMIT/OFFSET (if any) |
112
|
|
|
*/ |
113
|
|
|
protected function oldBuildOrderByAndLimit($sql, $orderBy, $limit, $offset) |
114
|
|
|
{ |
115
|
|
|
$orderBy = $this->buildOrderBy($orderBy); |
116
|
|
|
if ($orderBy === '') { |
117
|
|
|
// ROW_NUMBER() requires an ORDER BY clause |
118
|
|
|
$orderBy = 'ORDER BY (SELECT NULL)'; |
119
|
|
|
} |
120
|
|
|
|
121
|
|
|
$sql = preg_replace('/^([\s(])*SELECT(\s+DISTINCT)?(?!\s*TOP\s*\()/i', "\\1SELECT\\2 rowNum = ROW_NUMBER() over ($orderBy),", $sql); |
122
|
|
|
|
123
|
|
|
if ($this->hasLimit($limit)) { |
124
|
|
|
$sql = "SELECT TOP $limit * FROM ($sql) sub"; |
125
|
|
|
} else { |
126
|
|
|
$sql = "SELECT * FROM ($sql) sub"; |
127
|
|
|
} |
128
|
|
|
if ($this->hasOffset($offset)) { |
129
|
|
|
$sql .= $this->separator . "WHERE rowNum > $offset"; |
130
|
|
|
} |
131
|
|
|
|
132
|
|
|
return $sql; |
133
|
|
|
} |
134
|
|
|
|
135
|
|
|
/** |
136
|
|
|
* Builds a SQL statement for renaming a DB table. |
137
|
|
|
* @param string $oldName the table to be renamed. The name will be properly quoted by the method. |
138
|
|
|
* @param string $newName the new table name. The name will be properly quoted by the method. |
139
|
|
|
* @return string the SQL statement for renaming a DB table. |
140
|
|
|
*/ |
141
|
2 |
|
public function renameTable($oldName, $newName) |
142
|
|
|
{ |
143
|
2 |
|
return 'sp_rename ' . $this->db->quoteTableName($oldName) . ', ' . $this->db->quoteTableName($newName); |
144
|
|
|
} |
145
|
|
|
|
146
|
|
|
/** |
147
|
|
|
* Builds a SQL statement for renaming a column. |
148
|
|
|
* @param string $table the table whose column is to be renamed. The name will be properly quoted by the method. |
149
|
|
|
* @param string $oldName the old name of the column. The name will be properly quoted by the method. |
150
|
|
|
* @param string $newName the new name of the column. The name will be properly quoted by the method. |
151
|
|
|
* @return string the SQL statement for renaming a DB column. |
152
|
|
|
*/ |
153
|
|
|
public function renameColumn($table, $oldName, $newName) |
154
|
|
|
{ |
155
|
|
|
$table = $this->db->quoteTableName($table); |
156
|
|
|
$oldName = $this->db->quoteColumnName($oldName); |
157
|
|
|
$newName = $this->db->quoteColumnName($newName); |
158
|
|
|
return "sp_rename '{$table}.{$oldName}', {$newName}, 'COLUMN'"; |
159
|
|
|
} |
160
|
|
|
|
161
|
|
|
/** |
162
|
|
|
* Builds a SQL statement for changing the definition of a column. |
163
|
|
|
* @param string $table the table whose column is to be changed. The table name will be properly quoted by the method. |
164
|
|
|
* @param string $column the name of the column to be changed. The name will be properly quoted by the method. |
165
|
|
|
* @param string $type the new column type. The [[getColumnType]] method will be invoked to convert abstract column type (if any) |
166
|
|
|
* into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL. |
167
|
|
|
* For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'. |
168
|
|
|
* @return string the SQL statement for changing the definition of a column. |
169
|
|
|
*/ |
170
|
1 |
|
public function alterColumn($table, $column, $type) |
171
|
|
|
{ |
172
|
1 |
|
$type = $this->getColumnType($type); |
173
|
1 |
|
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ALTER COLUMN ' |
174
|
1 |
|
. $this->db->quoteColumnName($column) . ' ' |
175
|
1 |
|
. $this->getColumnType($type); |
176
|
|
|
|
177
|
1 |
|
return $sql; |
178
|
|
|
} |
179
|
|
|
|
180
|
|
|
/** |
181
|
|
|
* {@inheritdoc} |
182
|
|
|
*/ |
183
|
2 |
|
public function addDefaultValue($name, $table, $column, $value) |
184
|
|
|
{ |
185
|
2 |
|
return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT ' |
186
|
2 |
|
. $this->db->quoteColumnName($name) . ' DEFAULT ' . $this->db->quoteValue($value) . ' FOR ' |
187
|
2 |
|
. $this->db->quoteColumnName($column); |
188
|
|
|
} |
189
|
|
|
|
190
|
|
|
/** |
191
|
|
|
* {@inheritdoc} |
192
|
|
|
*/ |
193
|
2 |
|
public function dropDefaultValue($name, $table) |
194
|
|
|
{ |
195
|
2 |
|
return 'ALTER TABLE ' . $this->db->quoteTableName($table) |
196
|
2 |
|
. ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name); |
197
|
|
|
} |
198
|
|
|
|
199
|
|
|
/** |
200
|
|
|
* Creates a SQL statement for resetting the sequence value of a table's primary key. |
201
|
|
|
* The sequence will be reset such that the primary key of the next new row inserted |
202
|
|
|
* will have the specified value or 1. |
203
|
|
|
* @param string $tableName the name of the table whose primary key sequence will be reset |
204
|
|
|
* @param mixed $value the value for the primary key of the next new row inserted. If this is not set, |
205
|
|
|
* the next new row's primary key will have a value 1. |
206
|
|
|
* @return string the SQL statement for resetting sequence |
207
|
|
|
* @throws InvalidArgumentException if the table does not exist or there is no sequence associated with the table. |
208
|
|
|
*/ |
209
|
6 |
|
public function resetSequence($tableName, $value = null) |
210
|
|
|
{ |
211
|
6 |
|
$table = $this->db->getTableSchema($tableName); |
212
|
6 |
|
if ($table !== null && $table->sequenceName !== null) { |
213
|
6 |
|
$tableName = $this->db->quoteTableName($tableName); |
214
|
6 |
|
if ($value === null) { |
215
|
1 |
|
$key = $this->db->quoteColumnName(reset($table->primaryKey)); |
216
|
1 |
|
$value = "(SELECT COALESCE(MAX({$key}),0) FROM {$tableName})+1"; |
217
|
|
|
} else { |
218
|
6 |
|
$value = (int) $value; |
219
|
|
|
} |
220
|
|
|
|
221
|
6 |
|
return "DBCC CHECKIDENT ('{$tableName}', RESEED, {$value})"; |
222
|
|
|
} elseif ($table === null) { |
223
|
|
|
throw new InvalidArgumentException("Table not found: $tableName"); |
224
|
|
|
} |
225
|
|
|
|
226
|
|
|
throw new InvalidArgumentException("There is not sequence associated with table '$tableName'."); |
227
|
|
|
} |
228
|
|
|
|
229
|
|
|
/** |
230
|
|
|
* Builds a SQL statement for enabling or disabling integrity check. |
231
|
|
|
* @param bool $check whether to turn on or off the integrity check. |
232
|
|
|
* @param string $schema the schema of the tables. |
233
|
|
|
* @param string $table the table name. |
234
|
|
|
* @return string the SQL statement for checking integrity |
235
|
|
|
*/ |
236
|
|
|
public function checkIntegrity($check = true, $schema = '', $table = '') |
237
|
|
|
{ |
238
|
|
|
$enable = $check ? 'CHECK' : 'NOCHECK'; |
239
|
|
|
$schema = $schema ?: $this->db->getSchema()->defaultSchema; |
240
|
|
|
$tableNames = $this->db->getTableSchema($table) ? [$table] : $this->db->getSchema()->getTableNames($schema); |
241
|
|
|
$viewNames = $this->db->getSchema()->getViewNames($schema); |
|
|
|
|
242
|
|
|
$tableNames = array_diff($tableNames, $viewNames); |
243
|
|
|
$command = ''; |
244
|
|
|
|
245
|
|
|
foreach ($tableNames as $tableName) { |
246
|
|
|
$tableName = $this->db->quoteTableName("{$schema}.{$tableName}"); |
247
|
|
|
$command .= "ALTER TABLE $tableName $enable CONSTRAINT ALL; "; |
248
|
|
|
} |
249
|
|
|
|
250
|
|
|
return $command; |
251
|
|
|
} |
252
|
|
|
|
253
|
|
|
/** |
254
|
|
|
* Builds a SQL command for adding or updating a comment to a table or a column. The command built will check if a comment |
255
|
|
|
* already exists. If so, it will be updated, otherwise, it will be added. |
256
|
|
|
* |
257
|
|
|
* @param string $comment the text of the comment to be added. The comment will be properly quoted by the method. |
258
|
|
|
* @param string $table the table to be commented or whose column is to be commented. The table name will be |
259
|
|
|
* properly quoted by the method. |
260
|
|
|
* @param string $column optional. The name of the column to be commented. If empty, the command will add the |
261
|
|
|
* comment to the table instead. The column name will be properly quoted by the method. |
262
|
|
|
* @return string the SQL statement for adding a comment. |
263
|
|
|
* @throws InvalidArgumentException if the table does not exist. |
264
|
|
|
* @since 2.0.24 |
265
|
|
|
*/ |
266
|
4 |
|
protected function buildAddCommentSql($comment, $table, $column = null) |
267
|
|
|
{ |
268
|
4 |
|
$tableSchema = $this->db->schema->getTableSchema($table); |
269
|
|
|
|
270
|
4 |
|
if ($tableSchema === null) { |
271
|
|
|
throw new InvalidArgumentException("Table not found: $table"); |
272
|
|
|
} |
273
|
|
|
|
274
|
4 |
|
$schemaName = $tableSchema->schemaName ? "N'" . $tableSchema->schemaName . "'": 'SCHEMA_NAME()'; |
275
|
4 |
|
$tableName = "N" . $this->db->quoteValue($tableSchema->name); |
276
|
4 |
|
$columnName = $column ? "N" . $this->db->quoteValue($column) : null; |
277
|
4 |
|
$comment = "N" . $this->db->quoteValue($comment); |
278
|
|
|
|
279
|
|
|
$functionParams = " |
280
|
|
|
@name = N'MS_description', |
281
|
4 |
|
@value = $comment, |
282
|
4 |
|
@level0type = N'SCHEMA', @level0name = $schemaName, |
283
|
4 |
|
@level1type = N'TABLE', @level1name = $tableName" |
284
|
4 |
|
. ($column ? ", @level2type = N'COLUMN', @level2name = $columnName" : '') . ';'; |
285
|
|
|
|
286
|
|
|
return " |
287
|
|
|
IF NOT EXISTS ( |
288
|
|
|
SELECT 1 |
289
|
|
|
FROM fn_listextendedproperty ( |
290
|
|
|
N'MS_description', |
291
|
4 |
|
'SCHEMA', $schemaName, |
292
|
4 |
|
'TABLE', $tableName, |
293
|
4 |
|
" . ($column ? "'COLUMN', $columnName " : ' DEFAULT, DEFAULT ') . " |
294
|
|
|
) |
295
|
|
|
) |
296
|
4 |
|
EXEC sys.sp_addextendedproperty $functionParams |
297
|
|
|
ELSE |
298
|
4 |
|
EXEC sys.sp_updateextendedproperty $functionParams |
299
|
|
|
"; |
300
|
|
|
} |
301
|
|
|
|
302
|
|
|
/** |
303
|
|
|
* {@inheritdoc} |
304
|
|
|
* @since 2.0.8 |
305
|
|
|
*/ |
306
|
4 |
|
public function addCommentOnColumn($table, $column, $comment) |
307
|
|
|
{ |
308
|
4 |
|
return $this->buildAddCommentSql($comment, $table, $column); |
309
|
|
|
} |
310
|
|
|
|
311
|
|
|
/** |
312
|
|
|
* {@inheritdoc} |
313
|
|
|
* @since 2.0.8 |
314
|
|
|
*/ |
315
|
4 |
|
public function addCommentOnTable($table, $comment) |
316
|
|
|
{ |
317
|
4 |
|
return $this->buildAddCommentSql($comment, $table); |
318
|
|
|
} |
319
|
|
|
|
320
|
|
|
/** |
321
|
|
|
* Builds a SQL command for removing a comment from a table or a column. The command built will check if a comment |
322
|
|
|
* already exists before trying to perform the removal. |
323
|
|
|
* |
324
|
|
|
* @param string $table the table that will have the comment removed or whose column will have the comment removed. |
325
|
|
|
* The table name will be properly quoted by the method. |
326
|
|
|
* @param string $column optional. The name of the column whose comment will be removed. If empty, the command |
327
|
|
|
* will remove the comment from the table instead. The column name will be properly quoted by the method. |
328
|
|
|
* @return string the SQL statement for removing the comment. |
329
|
|
|
* @throws InvalidArgumentException if the table does not exist. |
330
|
|
|
* @since 2.0.24 |
331
|
|
|
*/ |
332
|
2 |
|
protected function buildRemoveCommentSql($table, $column = null) |
333
|
|
|
{ |
334
|
2 |
|
$tableSchema = $this->db->schema->getTableSchema($table); |
335
|
|
|
|
336
|
2 |
|
if ($tableSchema === null) { |
337
|
|
|
throw new InvalidArgumentException("Table not found: $table"); |
338
|
|
|
} |
339
|
|
|
|
340
|
2 |
|
$schemaName = $tableSchema->schemaName ? "N'" . $tableSchema->schemaName . "'": 'SCHEMA_NAME()'; |
341
|
2 |
|
$tableName = "N" . $this->db->quoteValue($tableSchema->name); |
342
|
2 |
|
$columnName = $column ? "N" . $this->db->quoteValue($column) : null; |
343
|
|
|
|
344
|
|
|
return " |
345
|
|
|
IF EXISTS ( |
346
|
|
|
SELECT 1 |
347
|
|
|
FROM fn_listextendedproperty ( |
348
|
|
|
N'MS_description', |
349
|
2 |
|
'SCHEMA', $schemaName, |
350
|
2 |
|
'TABLE', $tableName, |
351
|
2 |
|
" . ($column ? "'COLUMN', $columnName " : ' DEFAULT, DEFAULT ') . " |
352
|
|
|
) |
353
|
|
|
) |
354
|
|
|
EXEC sys.sp_dropextendedproperty |
355
|
|
|
@name = N'MS_description', |
356
|
2 |
|
@level0type = N'SCHEMA', @level0name = $schemaName, |
357
|
2 |
|
@level1type = N'TABLE', @level1name = $tableName" |
358
|
2 |
|
. ($column ? ", @level2type = N'COLUMN', @level2name = $columnName" : '') . ';'; |
359
|
|
|
} |
360
|
|
|
|
361
|
|
|
/** |
362
|
|
|
* {@inheritdoc} |
363
|
|
|
* @since 2.0.8 |
364
|
|
|
*/ |
365
|
2 |
|
public function dropCommentFromColumn($table, $column) |
366
|
|
|
{ |
367
|
2 |
|
return $this->buildRemoveCommentSql($table, $column); |
368
|
|
|
} |
369
|
|
|
|
370
|
|
|
/** |
371
|
|
|
* {@inheritdoc} |
372
|
|
|
* @since 2.0.8 |
373
|
|
|
*/ |
374
|
2 |
|
public function dropCommentFromTable($table) |
375
|
|
|
{ |
376
|
2 |
|
return $this->buildRemoveCommentSql($table); |
377
|
|
|
} |
378
|
|
|
|
379
|
|
|
/** |
380
|
|
|
* Returns an array of column names given model name. |
381
|
|
|
* |
382
|
|
|
* @param string $modelClass name of the model class |
383
|
|
|
* @return array|null array of column names |
384
|
|
|
*/ |
385
|
|
|
protected function getAllColumnNames($modelClass = null) |
386
|
|
|
{ |
387
|
|
|
if (!$modelClass) { |
388
|
|
|
return null; |
389
|
|
|
} |
390
|
|
|
/* @var $modelClass \yii\db\ActiveRecord */ |
391
|
|
|
$schema = $modelClass::getTableSchema(); |
392
|
|
|
return array_keys($schema->columns); |
393
|
|
|
} |
394
|
|
|
|
395
|
|
|
/** |
396
|
|
|
* @return bool whether the version of the MSSQL being used is older than 2012. |
397
|
|
|
* @throws \yii\base\InvalidConfigException |
398
|
|
|
* @throws \yii\db\Exception |
399
|
|
|
* @deprecated 2.0.14 Use [[Schema::getServerVersion]] with [[\version_compare()]]. |
400
|
|
|
*/ |
401
|
|
|
protected function isOldMssql() |
402
|
|
|
{ |
403
|
|
|
return version_compare($this->db->getSchema()->getServerVersion(), '11', '<'); |
404
|
|
|
} |
405
|
|
|
|
406
|
|
|
/** |
407
|
|
|
* {@inheritdoc} |
408
|
|
|
* @since 2.0.8 |
409
|
|
|
*/ |
410
|
21 |
|
public function selectExists($rawSql) |
411
|
|
|
{ |
412
|
21 |
|
return 'SELECT CASE WHEN EXISTS(' . $rawSql . ') THEN 1 ELSE 0 END'; |
413
|
|
|
} |
414
|
|
|
|
415
|
|
|
/** |
416
|
|
|
* Normalizes data to be saved into the table, performing extra preparations and type converting, if necessary. |
417
|
|
|
* @param string $table the table that data will be saved into. |
418
|
|
|
* @param array $columns the column data (name => value) to be saved into the table. |
419
|
|
|
* @return array normalized columns |
420
|
|
|
*/ |
421
|
67 |
|
private function normalizeTableRowData($table, $columns, &$params) |
422
|
|
|
{ |
423
|
67 |
|
if (($tableSchema = $this->db->getSchema()->getTableSchema($table)) !== null) { |
424
|
67 |
|
$columnSchemas = $tableSchema->columns; |
425
|
67 |
|
foreach ($columns as $name => $value) { |
426
|
|
|
// @see https://github.com/yiisoft/yii2/issues/12599 |
427
|
66 |
|
if (isset($columnSchemas[$name]) && $columnSchemas[$name]->type === Schema::TYPE_BINARY && $columnSchemas[$name]->dbType === 'varbinary' && (is_string($value) || $value === null)) { |
428
|
|
|
$phName = $this->bindParam($value, $params); |
429
|
66 |
|
$columns[$name] = new Expression("CONVERT(VARBINARY, $phName)", $params); |
430
|
|
|
} |
431
|
|
|
} |
432
|
|
|
} |
433
|
|
|
|
434
|
67 |
|
return $columns; |
435
|
|
|
} |
436
|
|
|
|
437
|
|
|
/** |
438
|
|
|
* {@inheritdoc} |
439
|
|
|
*/ |
440
|
56 |
|
public function insert($table, $columns, &$params) |
441
|
|
|
{ |
442
|
56 |
|
return parent::insert($table, $this->normalizeTableRowData($table, $columns, $params), $params); |
443
|
|
|
} |
444
|
|
|
|
445
|
|
|
/** |
446
|
|
|
* {@inheritdoc} |
447
|
|
|
* @see https://docs.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql |
448
|
|
|
* @see http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx |
449
|
|
|
*/ |
450
|
23 |
|
public function upsert($table, $insertColumns, $updateColumns, &$params) |
451
|
|
|
{ |
452
|
|
|
/** @var Constraint[] $constraints */ |
453
|
23 |
|
list($uniqueNames, $insertNames, $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns, $constraints); |
454
|
23 |
|
if (empty($uniqueNames)) { |
455
|
3 |
|
return $this->insert($table, $insertColumns, $params); |
456
|
|
|
} |
457
|
|
|
|
458
|
20 |
|
$onCondition = ['or']; |
459
|
20 |
|
$quotedTableName = $this->db->quoteTableName($table); |
460
|
20 |
|
foreach ($constraints as $constraint) { |
461
|
20 |
|
$constraintCondition = ['and']; |
462
|
20 |
|
foreach ($constraint->columnNames as $name) { |
463
|
20 |
|
$quotedName = $this->db->quoteColumnName($name); |
464
|
20 |
|
$constraintCondition[] = "$quotedTableName.$quotedName=[EXCLUDED].$quotedName"; |
465
|
|
|
} |
466
|
20 |
|
$onCondition[] = $constraintCondition; |
467
|
|
|
} |
468
|
20 |
|
$on = $this->buildCondition($onCondition, $params); |
469
|
20 |
|
list(, $placeholders, $values, $params) = $this->prepareInsertValues($table, $insertColumns, $params); |
470
|
20 |
|
$mergeSql = 'MERGE ' . $this->db->quoteTableName($table) . ' WITH (HOLDLOCK) ' |
471
|
20 |
|
. 'USING (' . (!empty($placeholders) ? 'VALUES (' . implode(', ', $placeholders) . ')' : ltrim($values, ' ')) . ') AS [EXCLUDED] (' . implode(', ', $insertNames) . ') ' |
472
|
20 |
|
. "ON ($on)"; |
473
|
20 |
|
$insertValues = []; |
474
|
20 |
|
foreach ($insertNames as $name) { |
475
|
20 |
|
$quotedName = $this->db->quoteColumnName($name); |
476
|
20 |
|
if (strrpos($quotedName, '.') === false) { |
477
|
20 |
|
$quotedName = '[EXCLUDED].' . $quotedName; |
478
|
|
|
} |
479
|
20 |
|
$insertValues[] = $quotedName; |
480
|
|
|
} |
481
|
20 |
|
$insertSql = 'INSERT (' . implode(', ', $insertNames) . ')' |
482
|
20 |
|
. ' VALUES (' . implode(', ', $insertValues) . ')'; |
483
|
20 |
|
if ($updateColumns === false) { |
484
|
4 |
|
return "$mergeSql WHEN NOT MATCHED THEN $insertSql;"; |
485
|
|
|
} |
486
|
|
|
|
487
|
16 |
|
if ($updateColumns === true) { |
488
|
10 |
|
$updateColumns = []; |
489
|
10 |
|
foreach ($updateNames as $name) { |
490
|
10 |
|
$quotedName = $this->db->quoteColumnName($name); |
491
|
10 |
|
if (strrpos($quotedName, '.') === false) { |
492
|
10 |
|
$quotedName = '[EXCLUDED].' . $quotedName; |
493
|
|
|
} |
494
|
10 |
|
$updateColumns[$name] = new Expression($quotedName); |
495
|
|
|
} |
496
|
|
|
} |
497
|
16 |
|
list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params); |
498
|
16 |
|
$updateSql = 'UPDATE SET ' . implode(', ', $updates); |
499
|
16 |
|
return "$mergeSql WHEN MATCHED THEN $updateSql WHEN NOT MATCHED THEN $insertSql;"; |
500
|
|
|
} |
501
|
|
|
|
502
|
|
|
/** |
503
|
|
|
* {@inheritdoc} |
504
|
|
|
*/ |
505
|
17 |
|
public function update($table, $columns, $condition, &$params) |
506
|
|
|
{ |
507
|
17 |
|
return parent::update($table, $this->normalizeTableRowData($table, $columns, $params), $condition, $params); |
508
|
|
|
} |
509
|
|
|
|
510
|
|
|
/** |
511
|
|
|
* {@inheritdoc} |
512
|
|
|
*/ |
513
|
21 |
|
public function getColumnType($type) |
514
|
|
|
{ |
515
|
21 |
|
$columnType = parent::getColumnType($type); |
516
|
|
|
// remove unsupported keywords |
517
|
21 |
|
$columnType = preg_replace("/\s*comment '.*'/i", '', $columnType); |
518
|
21 |
|
$columnType = preg_replace('/ first$/i', '', $columnType); |
519
|
|
|
|
520
|
21 |
|
return $columnType; |
521
|
|
|
} |
522
|
|
|
|
523
|
|
|
/** |
524
|
|
|
* {@inheritdoc} |
525
|
|
|
*/ |
526
|
206 |
|
protected function extractAlias($table) |
527
|
|
|
{ |
528
|
206 |
|
if (preg_match('/^\[.*\]$/', $table)) { |
529
|
6 |
|
return false; |
530
|
|
|
} |
531
|
|
|
|
532
|
200 |
|
return parent::extractAlias($table); |
533
|
|
|
} |
534
|
|
|
} |
535
|
|
|
|