QueryBuilder   F
last analyzed

Complexity

Total Complexity 97

Size/Duplication

Total Lines 654
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 240
dl 0
loc 654
ccs 0
cts 247
cp 0
rs 2
c 0
b 0
f 0
wmc 97

28 Methods

Rating   Name   Duplication   Size   Complexity  
A dropConstraintsForColumn() 0 21 2
C upsert() 0 68 13
A update() 0 3 1
C insert() 0 44 14
A dropColumn() 0 4 1
A extractAlias() 0 7 2
A getColumnType() 0 8 1
A addCommentOnColumn() 0 3 1
A newBuildOrderByAndLimit() 0 17 4
A buildRemoveCommentSql() 0 27 6
B alterColumn() 0 38 7
A buildOrderByAndLimit() 0 12 5
A dropDefaultValue() 0 4 1
A buildAddCommentSql() 0 33 6
A dropCommentFromColumn() 0 3 1
A renameColumn() 0 6 1
A checkIntegrity() 0 15 5
A addCommentOnTable() 0 3 1
A getAllColumnNames() 0 8 2
A dropCommentFromTable() 0 3 1
A renameTable() 0 3 1
A oldBuildOrderByAndLimit() 0 23 5
A resetSequence() 0 18 5
A addDefaultValue() 0 5 1
A defaultExpressionBuilders() 0 5 1
B normalizeTableRowData() 0 14 7
A isOldMssql() 0 3 1
A selectExists() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like QueryBuilder often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use QueryBuilder, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * @link https://www.yiiframework.com/
5
 * @copyright Copyright (c) 2008 Yii Software LLC
6
 * @license https://www.yiiframework.com/license/
7
 */
8
9
namespace yii\db\mssql;
10
11
use yii\base\InvalidArgumentException;
12
use yii\base\NotSupportedException;
13
use yii\db\Constraint;
14
use yii\db\Expression;
15
use yii\db\TableSchema;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, yii\db\mssql\TableSchema. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
16
17
/**
18
 * QueryBuilder is the query builder for MS SQL Server databases (version 2008 and above).
19
 *
20
 * @author Timur Ruziev <[email protected]>
21
 * @since 2.0
22
 */
23
class QueryBuilder extends \yii\db\QueryBuilder
24
{
25
    /**
26
     * @var array mapping from abstract column types (keys) to physical column types (values).
27
     */
28
    public $typeMap = [
29
        Schema::TYPE_PK => 'int IDENTITY PRIMARY KEY',
30
        Schema::TYPE_UPK => 'int IDENTITY PRIMARY KEY',
31
        Schema::TYPE_BIGPK => 'bigint IDENTITY PRIMARY KEY',
32
        Schema::TYPE_UBIGPK => 'bigint IDENTITY PRIMARY KEY',
33
        Schema::TYPE_CHAR => 'nchar(1)',
34
        Schema::TYPE_STRING => 'nvarchar(255)',
35
        Schema::TYPE_TEXT => 'nvarchar(max)',
36
        Schema::TYPE_TINYINT => 'tinyint',
37
        Schema::TYPE_SMALLINT => 'smallint',
38
        Schema::TYPE_INTEGER => 'int',
39
        Schema::TYPE_BIGINT => 'bigint',
40
        Schema::TYPE_FLOAT => 'float',
41
        Schema::TYPE_DOUBLE => 'float',
42
        Schema::TYPE_DECIMAL => 'decimal(18,0)',
43
        Schema::TYPE_DATETIME => 'datetime',
44
        Schema::TYPE_TIMESTAMP => 'datetime',
45
        Schema::TYPE_TIME => 'time',
46
        Schema::TYPE_DATE => 'date',
47
        Schema::TYPE_BINARY => 'varbinary(max)',
48
        Schema::TYPE_BOOLEAN => 'bit',
49
        Schema::TYPE_MONEY => 'decimal(19,4)',
50
    ];
51
52
53
    /**
54
     * {@inheritdoc}
55
     */
56
    protected function defaultExpressionBuilders()
57
    {
58
        return array_merge(parent::defaultExpressionBuilders(), [
59
            'yii\db\conditions\InCondition' => 'yii\db\mssql\conditions\InConditionBuilder',
60
            'yii\db\conditions\LikeCondition' => 'yii\db\mssql\conditions\LikeConditionBuilder',
61
        ]);
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67
    public function buildOrderByAndLimit($sql, $orderBy, $limit, $offset)
68
    {
69
        if (!$this->hasOffset($offset) && !$this->hasLimit($limit)) {
70
            $orderBy = $this->buildOrderBy($orderBy);
71
            return $orderBy === '' ? $sql : $sql . $this->separator . $orderBy;
72
        }
73
74
        if (version_compare($this->db->getSchema()->getServerVersion(), '11', '<')) {
75
            return $this->oldBuildOrderByAndLimit($sql, $orderBy, $limit, $offset);
76
        }
77
78
        return $this->newBuildOrderByAndLimit($sql, $orderBy, $limit, $offset);
79
    }
80
81
    /**
82
     * Builds the ORDER BY/LIMIT/OFFSET clauses for SQL SERVER 2012 or newer.
83
     * @param string $sql the existing SQL (without ORDER BY/LIMIT/OFFSET)
84
     * @param array $orderBy the order by columns. See [[\yii\db\Query::orderBy]] for more details on how to specify this parameter.
85
     * @param int $limit the limit number. See [[\yii\db\Query::limit]] for more details.
86
     * @param int $offset the offset number. See [[\yii\db\Query::offset]] for more details.
87
     * @return string the SQL completed with ORDER BY/LIMIT/OFFSET (if any)
88
     */
89
    protected function newBuildOrderByAndLimit($sql, $orderBy, $limit, $offset)
90
    {
91
        $orderBy = $this->buildOrderBy($orderBy);
92
        if ($orderBy === '') {
93
            // ORDER BY clause is required when FETCH and OFFSET are in the SQL
94
            $orderBy = 'ORDER BY (SELECT NULL)';
95
        }
96
        $sql .= $this->separator . $orderBy;
97
98
        // http://technet.microsoft.com/en-us/library/gg699618.aspx
99
        $offset = $this->hasOffset($offset) ? $offset : '0';
100
        $sql .= $this->separator . "OFFSET $offset ROWS";
101
        if ($this->hasLimit($limit)) {
102
            $sql .= $this->separator . "FETCH NEXT $limit ROWS ONLY";
103
        }
104
105
        return $sql;
106
    }
107
108
    /**
109
     * Builds the ORDER BY/LIMIT/OFFSET clauses for SQL SERVER 2005 to 2008.
110
     * @param string $sql the existing SQL (without ORDER BY/LIMIT/OFFSET)
111
     * @param array $orderBy the order by columns. See [[\yii\db\Query::orderBy]] for more details on how to specify this parameter.
112
     * @param int|Expression $limit the limit number. See [[\yii\db\Query::limit]] for more details.
113
     * @param int $offset the offset number. See [[\yii\db\Query::offset]] for more details.
114
     * @return string the SQL completed with ORDER BY/LIMIT/OFFSET (if any)
115
     */
116
    protected function oldBuildOrderByAndLimit($sql, $orderBy, $limit, $offset)
117
    {
118
        $orderBy = $this->buildOrderBy($orderBy);
119
        if ($orderBy === '') {
120
            // ROW_NUMBER() requires an ORDER BY clause
121
            $orderBy = 'ORDER BY (SELECT NULL)';
122
        }
123
124
        $sql = preg_replace('/^([\s(])*SELECT(\s+DISTINCT)?(?!\s*TOP\s*\()/i', "\\1SELECT\\2 rowNum = ROW_NUMBER() over ($orderBy),", $sql);
125
126
        if ($this->hasLimit($limit)) {
127
            if ($limit instanceof Expression) {
128
                $limit = '(' . (string)$limit . ')';
129
            }
130
            $sql = "SELECT TOP $limit * FROM ($sql) sub";
131
        } else {
132
            $sql = "SELECT * FROM ($sql) sub";
133
        }
134
        if ($this->hasOffset($offset)) {
135
            $sql .= $this->separator . "WHERE rowNum > $offset";
136
        }
137
138
        return $sql;
139
    }
140
141
    /**
142
     * Builds a SQL statement for renaming a DB table.
143
     * @param string $oldName the table to be renamed. The name will be properly quoted by the method.
144
     * @param string $newName the new table name. The name will be properly quoted by the method.
145
     * @return string the SQL statement for renaming a DB table.
146
     */
147
    public function renameTable($oldName, $newName)
148
    {
149
        return 'sp_rename ' . $this->db->quoteTableName($oldName) . ', ' . $this->db->quoteTableName($newName);
150
    }
151
152
    /**
153
     * Builds a SQL statement for renaming a column.
154
     * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
155
     * @param string $oldName the old name of the column. The name will be properly quoted by the method.
156
     * @param string $newName the new name of the column. The name will be properly quoted by the method.
157
     * @return string the SQL statement for renaming a DB column.
158
     */
159
    public function renameColumn($table, $oldName, $newName)
160
    {
161
        $table = $this->db->quoteTableName($table);
162
        $oldName = $this->db->quoteColumnName($oldName);
163
        $newName = $this->db->quoteColumnName($newName);
164
        return "sp_rename '{$table}.{$oldName}', {$newName}, 'COLUMN'";
165
    }
166
167
    /**
168
     * Builds a SQL statement for changing the definition of a column.
169
     * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
170
     * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
171
     * @param string $type the new column type. The [[getColumnType]] method will be invoked to convert abstract column type (if any)
172
     * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
173
     * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
174
     * @return string the SQL statement for changing the definition of a column.
175
     * @throws NotSupportedException if this is not supported by the underlying DBMS.
176
     */
177
    public function alterColumn($table, $column, $type)
178
    {
179
        $sqlAfter = [$this->dropConstraintsForColumn($table, $column, 'D')];
180
181
        $columnName = $this->db->quoteColumnName($column);
182
        $tableName = $this->db->quoteTableName($table);
183
        $constraintBase = preg_replace('/[^a-z0-9_]/i', '', $table . '_' . $column);
184
185
        if ($type instanceof \yii\db\mssql\ColumnSchemaBuilder) {
0 ignored issues
show
introduced by
$type is never a sub-type of yii\db\mssql\ColumnSchemaBuilder.
Loading history...
186
            $type->setAlterColumnFormat();
187
188
189
            $defaultValue = $type->getDefaultValue();
190
            if ($defaultValue !== null) {
191
                $sqlAfter[] = $this->addDefaultValue(
192
                    "DF_{$constraintBase}",
193
                    $table,
194
                    $column,
195
                    $defaultValue instanceof Expression ? $defaultValue : new Expression($defaultValue)
196
                );
197
            }
198
199
            $checkValue = $type->getCheckValue();
200
            if ($checkValue !== null) {
201
                $sqlAfter[] = "ALTER TABLE {$tableName} ADD CONSTRAINT " .
202
                    $this->db->quoteColumnName("CK_{$constraintBase}") .
203
                    ' CHECK (' . ($defaultValue instanceof Expression ?  $checkValue : new Expression($checkValue)) . ')';
204
            }
205
206
            if ($type->isUnique()) {
207
                $sqlAfter[] = "ALTER TABLE {$tableName} ADD CONSTRAINT " . $this->db->quoteColumnName("UQ_{$constraintBase}") . " UNIQUE ({$columnName})";
208
            }
209
        }
210
211
        return 'ALTER TABLE ' . $tableName . ' ALTER COLUMN '
212
            . $columnName . ' '
213
            . $this->getColumnType($type) . "\n"
214
            . implode("\n", $sqlAfter);
215
    }
216
217
    /**
218
     * {@inheritdoc}
219
     */
220
    public function addDefaultValue($name, $table, $column, $value)
221
    {
222
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
223
            . $this->db->quoteColumnName($name) . ' DEFAULT ' . $this->db->quoteValue($value) . ' FOR '
224
            . $this->db->quoteColumnName($column);
225
    }
226
227
    /**
228
     * {@inheritdoc}
229
     */
230
    public function dropDefaultValue($name, $table)
231
    {
232
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
233
            . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
234
    }
235
236
    /**
237
     * Creates a SQL statement for resetting the sequence value of a table's primary key.
238
     * The sequence will be reset such that the primary key of the next new row inserted
239
     * will have the specified value or 1.
240
     * @param string $tableName the name of the table whose primary key sequence will be reset
241
     * @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
242
     * the next new row's primary key will have a value 1.
243
     * @return string the SQL statement for resetting sequence
244
     * @throws InvalidArgumentException if the table does not exist or there is no sequence associated with the table.
245
     */
246
    public function resetSequence($tableName, $value = null)
247
    {
248
        $table = $this->db->getTableSchema($tableName);
249
        if ($table !== null && $table->sequenceName !== null) {
250
            $tableName = $this->db->quoteTableName($tableName);
251
            if ($value === null) {
252
                $key = $this->db->quoteColumnName(reset($table->primaryKey));
253
                $value = "(SELECT COALESCE(MAX({$key}),0) FROM {$tableName})+1";
254
            } else {
255
                $value = (int) $value;
256
            }
257
258
            return "DBCC CHECKIDENT ('{$tableName}', RESEED, {$value})";
259
        } elseif ($table === null) {
260
            throw new InvalidArgumentException("Table not found: $tableName");
261
        }
262
263
        throw new InvalidArgumentException("There is not sequence associated with table '$tableName'.");
264
    }
265
266
    /**
267
     * Builds a SQL statement for enabling or disabling integrity check.
268
     * @param bool $check whether to turn on or off the integrity check.
269
     * @param string $schema the schema of the tables.
270
     * @param string $table the table name.
271
     * @return string the SQL statement for checking integrity
272
     */
273
    public function checkIntegrity($check = true, $schema = '', $table = '')
274
    {
275
        $enable = $check ? 'CHECK' : 'NOCHECK';
276
        $schema = $schema ?: $this->db->getSchema()->defaultSchema;
277
        $tableNames = $this->db->getTableSchema($table) ? [$table] : $this->db->getSchema()->getTableNames($schema);
278
        $viewNames = $this->db->getSchema()->getViewNames($schema);
0 ignored issues
show
Bug introduced by
The method getViewNames() does not exist on yii\db\Schema. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

278
        $viewNames = $this->db->getSchema()->/** @scrutinizer ignore-call */ getViewNames($schema);
Loading history...
279
        $tableNames = array_diff($tableNames, $viewNames);
280
        $command = '';
281
282
        foreach ($tableNames as $tableName) {
283
            $tableName = $this->db->quoteTableName("{$schema}.{$tableName}");
284
            $command .= "ALTER TABLE $tableName $enable CONSTRAINT ALL; ";
285
        }
286
287
        return $command;
288
    }
289
290
     /**
291
      * Builds a SQL command for adding or updating a comment to a table or a column. The command built will check if a comment
292
      * already exists. If so, it will be updated, otherwise, it will be added.
293
      *
294
      * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
295
      * @param string $table the table to be commented or whose column is to be commented. The table name will be
296
      * properly quoted by the method.
297
      * @param string|null $column optional. The name of the column to be commented. If empty, the command will add the
298
      * comment to the table instead. The column name will be properly quoted by the method.
299
      * @return string the SQL statement for adding a comment.
300
      * @throws InvalidArgumentException if the table does not exist.
301
      * @since 2.0.24
302
      */
303
    protected function buildAddCommentSql($comment, $table, $column = null)
304
    {
305
        $tableSchema = $this->db->schema->getTableSchema($table);
306
307
        if ($tableSchema === null) {
308
            throw new InvalidArgumentException("Table not found: $table");
309
        }
310
311
        $schemaName = $tableSchema->schemaName ? "N'" . $tableSchema->schemaName . "'" : 'SCHEMA_NAME()';
312
        $tableName = 'N' . $this->db->quoteValue($tableSchema->name);
313
        $columnName = $column ? 'N' . $this->db->quoteValue($column) : null;
314
        $comment = 'N' . $this->db->quoteValue($comment);
315
316
        $functionParams = "
317
            @name = N'MS_description',
318
            @value = $comment,
319
            @level0type = N'SCHEMA', @level0name = $schemaName,
320
            @level1type = N'TABLE', @level1name = $tableName"
321
            . ($column ? ", @level2type = N'COLUMN', @level2name = $columnName" : '') . ';';
322
323
        return "
324
            IF NOT EXISTS (
325
                    SELECT 1
326
                    FROM fn_listextendedproperty (
327
                        N'MS_description',
328
                        'SCHEMA', $schemaName,
329
                        'TABLE', $tableName,
330
                        " . ($column ? "'COLUMN', $columnName " : ' DEFAULT, DEFAULT ') . "
331
                    )
332
            )
333
                EXEC sys.sp_addextendedproperty $functionParams
334
            ELSE
335
                EXEC sys.sp_updateextendedproperty $functionParams
336
        ";
337
    }
338
339
    /**
340
     * {@inheritdoc}
341
     * @since 2.0.8
342
     */
343
    public function addCommentOnColumn($table, $column, $comment)
344
    {
345
        return $this->buildAddCommentSql($comment, $table, $column);
346
    }
347
348
    /**
349
     * {@inheritdoc}
350
     * @since 2.0.8
351
     */
352
    public function addCommentOnTable($table, $comment)
353
    {
354
        return $this->buildAddCommentSql($comment, $table);
355
    }
356
357
    /**
358
     * Builds a SQL command for removing a comment from a table or a column. The command built will check if a comment
359
     * already exists before trying to perform the removal.
360
     *
361
     * @param string $table the table that will have the comment removed or whose column will have the comment removed.
362
     * The table name will be properly quoted by the method.
363
     * @param string|null $column optional. The name of the column whose comment will be removed. If empty, the command
364
     * will remove the comment from the table instead. The column name will be properly quoted by the method.
365
     * @return string the SQL statement for removing the comment.
366
     * @throws InvalidArgumentException if the table does not exist.
367
     * @since 2.0.24
368
     */
369
    protected function buildRemoveCommentSql($table, $column = null)
370
    {
371
        $tableSchema = $this->db->schema->getTableSchema($table);
372
373
        if ($tableSchema === null) {
374
            throw new InvalidArgumentException("Table not found: $table");
375
        }
376
377
        $schemaName = $tableSchema->schemaName ? "N'" . $tableSchema->schemaName . "'" : 'SCHEMA_NAME()';
378
        $tableName = 'N' . $this->db->quoteValue($tableSchema->name);
379
        $columnName = $column ? 'N' . $this->db->quoteValue($column) : null;
380
381
        return "
382
            IF EXISTS (
383
                    SELECT 1
384
                    FROM fn_listextendedproperty (
385
                        N'MS_description',
386
                        'SCHEMA', $schemaName,
387
                        'TABLE', $tableName,
388
                        " . ($column ? "'COLUMN', $columnName " : ' DEFAULT, DEFAULT ') . "
389
                    )
390
            )
391
                EXEC sys.sp_dropextendedproperty
392
                    @name = N'MS_description',
393
                    @level0type = N'SCHEMA', @level0name = $schemaName,
394
                    @level1type = N'TABLE', @level1name = $tableName"
395
                    . ($column ? ", @level2type = N'COLUMN', @level2name = $columnName" : '') . ';';
396
    }
397
398
    /**
399
     * {@inheritdoc}
400
     * @since 2.0.8
401
     */
402
    public function dropCommentFromColumn($table, $column)
403
    {
404
        return $this->buildRemoveCommentSql($table, $column);
405
    }
406
407
    /**
408
     * {@inheritdoc}
409
     * @since 2.0.8
410
     */
411
    public function dropCommentFromTable($table)
412
    {
413
        return $this->buildRemoveCommentSql($table);
414
    }
415
416
    /**
417
     * Returns an array of column names given model name.
418
     *
419
     * @param string|null $modelClass name of the model class
420
     * @return array|null array of column names
421
     */
422
    protected function getAllColumnNames($modelClass = null)
423
    {
424
        if (!$modelClass) {
425
            return null;
426
        }
427
        /* @var $modelClass \yii\db\ActiveRecord */
428
        $schema = $modelClass::getTableSchema();
429
        return array_keys($schema->columns);
430
    }
431
432
    /**
433
     * @return bool whether the version of the MSSQL being used is older than 2012.
434
     * @throws \yii\base\InvalidConfigException
435
     * @throws \yii\db\Exception
436
     * @deprecated 2.0.14 Use [[Schema::getServerVersion]] with [[\version_compare()]].
437
     */
438
    protected function isOldMssql()
439
    {
440
        return version_compare($this->db->getSchema()->getServerVersion(), '11', '<');
0 ignored issues
show
Bug Best Practice introduced by
The expression return version_compare($...erVersion(), '11', '<') also could return the type integer which is incompatible with the documented return type boolean.
Loading history...
441
    }
442
443
    /**
444
     * {@inheritdoc}
445
     * @since 2.0.8
446
     */
447
    public function selectExists($rawSql)
448
    {
449
        return 'SELECT CASE WHEN EXISTS(' . $rawSql . ') THEN 1 ELSE 0 END';
450
    }
451
452
    /**
453
     * Normalizes data to be saved into the table, performing extra preparations and type converting, if necessary.
454
     * @param string $table the table that data will be saved into.
455
     * @param array $columns the column data (name => value) to be saved into the table.
456
     * @return array normalized columns
457
     */
458
    private function normalizeTableRowData($table, $columns, &$params)
0 ignored issues
show
Unused Code introduced by
The parameter $params is not used and could be removed. ( Ignorable by Annotation )

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

458
    private function normalizeTableRowData($table, $columns, /** @scrutinizer ignore-unused */ &$params)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
459
    {
460
        if (($tableSchema = $this->db->getSchema()->getTableSchema($table)) !== null) {
461
            $columnSchemas = $tableSchema->columns;
462
            foreach ($columns as $name => $value) {
463
                // @see https://github.com/yiisoft/yii2/issues/12599
464
                if (isset($columnSchemas[$name]) && $columnSchemas[$name]->type === Schema::TYPE_BINARY && $columnSchemas[$name]->dbType === 'varbinary' && (is_string($value))) {
465
                    // @see https://github.com/yiisoft/yii2/issues/12599
466
                    $columns[$name] = new Expression('CONVERT(VARBINARY(MAX), ' . ('0x' . bin2hex($value)) . ')');
467
                }
468
            }
469
        }
470
471
        return $columns;
472
    }
473
474
    /**
475
     * {@inheritdoc}
476
     * Added OUTPUT construction for getting inserted data (for SQL Server 2005 or later)
477
     * OUTPUT clause - The OUTPUT clause is new to SQL Server 2005 and has the ability to access
478
     * the INSERTED and DELETED tables as is the case with a trigger.
479
     */
480
    public function insert($table, $columns, &$params)
481
    {
482
        $columns = $this->normalizeTableRowData($table, $columns, $params);
483
484
        $version2005orLater = version_compare($this->db->getSchema()->getServerVersion(), '9', '>=');
485
486
        list($names, $placeholders, $values, $params) = $this->prepareInsertValues($table, $columns, $params);
487
        $cols = [];
488
        $outputColumns = [];
489
        if ($version2005orLater) {
490
            /* @var $schema TableSchema */
491
            $schema = $this->db->getTableSchema($table);
492
            foreach ($schema->columns as $column) {
493
                if ($column->isComputed) {
0 ignored issues
show
Bug Best Practice introduced by
The property isComputed does not exist on yii\db\ColumnSchema. Since you implemented __get, consider adding a @property annotation.
Loading history...
494
                    continue;
495
                }
496
497
                $dbType = $column->dbType;
498
                if (in_array($dbType, ['char', 'varchar', 'nchar', 'nvarchar', 'binary', 'varbinary'])) {
499
                    $dbType .= '(MAX)';
500
                }
501
                if ($column->dbType === Schema::TYPE_TIMESTAMP) {
502
                    $dbType = $column->allowNull ? 'varbinary(8)' : 'binary(8)';
503
                }
504
505
                $quoteColumnName = $this->db->quoteColumnName($column->name);
506
                $cols[] = $quoteColumnName . ' ' . $dbType . ' ' . ($column->allowNull ? 'NULL' : '');
507
                $outputColumns[] = 'INSERTED.' . $quoteColumnName;
508
            }
509
        }
510
511
        $countColumns = count($outputColumns);
512
513
        $sql = 'INSERT INTO ' . $this->db->quoteTableName($table)
514
            . (!empty($names) ? ' (' . implode(', ', $names) . ')' : '')
515
            . (($version2005orLater && $countColumns) ? ' OUTPUT ' . implode(',', $outputColumns) . ' INTO @temporary_inserted' : '')
516
            . (!empty($placeholders) ? ' VALUES (' . implode(', ', $placeholders) . ')' : $values);
517
518
        if ($version2005orLater && $countColumns) {
519
            $sql = 'SET NOCOUNT ON;DECLARE @temporary_inserted TABLE (' . implode(', ', $cols) . ');' . $sql .
520
                ';SELECT * FROM @temporary_inserted';
521
        }
522
523
        return $sql;
524
    }
525
526
    /**
527
     * {@inheritdoc}
528
     * @see https://docs.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql
529
     * @see https://weblogs.sqlteam.com/dang/2009/01/31/upsert-race-condition-with-merge/
530
     */
531
    public function upsert($table, $insertColumns, $updateColumns, &$params)
532
    {
533
        $insertColumns = $this->normalizeTableRowData($table, $insertColumns, $params);
534
535
        /** @var Constraint[] $constraints */
536
        list($uniqueNames, $insertNames, $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns, $constraints);
537
        if (empty($uniqueNames)) {
538
            return $this->insert($table, $insertColumns, $params);
539
        }
540
        if ($updateNames === []) {
541
            // there are no columns to update
542
            $updateColumns = false;
543
        }
544
545
        $onCondition = ['or'];
546
        $quotedTableName = $this->db->quoteTableName($table);
547
        foreach ($constraints as $constraint) {
548
            $constraintCondition = ['and'];
549
            foreach ($constraint->columnNames as $name) {
550
                $quotedName = $this->db->quoteColumnName($name);
551
                $constraintCondition[] = "$quotedTableName.$quotedName=[EXCLUDED].$quotedName";
552
            }
553
            $onCondition[] = $constraintCondition;
554
        }
555
        $on = $this->buildCondition($onCondition, $params);
556
        list(, $placeholders, $values, $params) = $this->prepareInsertValues($table, $insertColumns, $params);
557
558
        /**
559
         * Fix number of select query params for old MSSQL version that does not support offset correctly.
560
         * @see QueryBuilder::oldBuildOrderByAndLimit
561
         */
562
        $insertNamesUsing = $insertNames;
563
        if (strstr($values, 'rowNum = ROW_NUMBER()') !== false) {
564
            $insertNamesUsing = array_merge(['[rowNum]'], $insertNames);
565
        }
566
567
        $mergeSql = 'MERGE ' . $this->db->quoteTableName($table) . ' WITH (HOLDLOCK) '
568
            . 'USING (' . (!empty($placeholders) ? 'VALUES (' . implode(', ', $placeholders) . ')' : ltrim($values, ' ')) . ') AS [EXCLUDED] (' . implode(', ', $insertNamesUsing) . ') '
569
            . "ON ($on)";
570
        $insertValues = [];
571
        foreach ($insertNames as $name) {
572
            $quotedName = $this->db->quoteColumnName($name);
573
            if (strrpos($quotedName, '.') === false) {
574
                $quotedName = '[EXCLUDED].' . $quotedName;
575
            }
576
            $insertValues[] = $quotedName;
577
        }
578
        $insertSql = 'INSERT (' . implode(', ', $insertNames) . ')'
579
            . ' VALUES (' . implode(', ', $insertValues) . ')';
580
        if ($updateColumns === false) {
581
            return "$mergeSql WHEN NOT MATCHED THEN $insertSql;";
582
        }
583
584
        if ($updateColumns === true) {
585
            $updateColumns = [];
586
            foreach ($updateNames as $name) {
587
                $quotedName = $this->db->quoteColumnName($name);
588
                if (strrpos($quotedName, '.') === false) {
589
                    $quotedName = '[EXCLUDED].' . $quotedName;
590
                }
591
                $updateColumns[$name] = new Expression($quotedName);
592
            }
593
        }
594
        $updateColumns = $this->normalizeTableRowData($table, $updateColumns, $params);
595
596
        list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params);
597
        $updateSql = 'UPDATE SET ' . implode(', ', $updates);
598
        return "$mergeSql WHEN MATCHED THEN $updateSql WHEN NOT MATCHED THEN $insertSql;";
599
    }
600
601
    /**
602
     * {@inheritdoc}
603
     */
604
    public function update($table, $columns, $condition, &$params)
605
    {
606
        return parent::update($table, $this->normalizeTableRowData($table, $columns, $params), $condition, $params);
607
    }
608
609
    /**
610
     * {@inheritdoc}
611
     */
612
    public function getColumnType($type)
613
    {
614
        $columnType = parent::getColumnType($type);
615
        // remove unsupported keywords
616
        $columnType = preg_replace("/\s*comment '.*'/i", '', $columnType);
617
        $columnType = preg_replace('/ first$/i', '', $columnType);
618
619
        return $columnType;
620
    }
621
622
    /**
623
     * {@inheritdoc}
624
     */
625
    protected function extractAlias($table)
626
    {
627
        if (preg_match('/^\[.*\]$/', $table)) {
628
            return false;
629
        }
630
631
        return parent::extractAlias($table);
632
    }
633
634
    /**
635
     * Builds a SQL statement for dropping constraints for column of table.
636
     *
637
     * @param string $table the table whose constraint is to be dropped. The name will be properly quoted by the method.
638
     * @param string $column the column whose constraint is to be dropped. The name will be properly quoted by the method.
639
     * @param string $type type of constraint, leave empty for all type of constraints(for example: D - default, 'UQ' - unique, 'C' - check)
640
     * @see https://docs.microsoft.com/sql/relational-databases/system-catalog-views/sys-objects-transact-sql
641
     * @return string the DROP CONSTRAINTS SQL
642
     */
643
    private function dropConstraintsForColumn($table, $column, $type = '')
644
    {
645
        return "DECLARE @tableName VARCHAR(MAX) = '" . $this->db->quoteTableName($table) . "'
646
DECLARE @columnName VARCHAR(MAX) = '{$column}'
647
648
WHILE 1=1 BEGIN
649
    DECLARE @constraintName NVARCHAR(128)
650
    SET @constraintName = (SELECT TOP 1 OBJECT_NAME(cons.[object_id])
651
        FROM (
652
            SELECT sc.[constid] object_id
653
            FROM [sys].[sysconstraints] sc
654
            JOIN [sys].[columns] c ON c.[object_id]=sc.[id] AND c.[column_id]=sc.[colid] AND c.[name]=@columnName
655
            WHERE sc.[id] = OBJECT_ID(@tableName)
656
            UNION
657
            SELECT object_id(i.[name]) FROM [sys].[indexes] i
658
            JOIN [sys].[columns] c ON c.[object_id]=i.[object_id] AND c.[name]=@columnName
659
            JOIN [sys].[index_columns] ic ON ic.[object_id]=i.[object_id] AND i.[index_id]=ic.[index_id] AND c.[column_id]=ic.[column_id]
660
            WHERE i.[is_unique_constraint]=1 and i.[object_id]=OBJECT_ID(@tableName)
661
        ) cons
662
        JOIN [sys].[objects] so ON so.[object_id]=cons.[object_id]
663
        " . (!empty($type) ? " WHERE so.[type]='{$type}'" : '') . ")
664
    IF @constraintName IS NULL BREAK
665
    EXEC (N'ALTER TABLE ' + @tableName + ' DROP CONSTRAINT [' + @constraintName + ']')
666
END";
667
    }
668
669
    /**
670
     * Drop all constraints before column delete
671
     * {@inheritdoc}
672
     */
673
    public function dropColumn($table, $column)
674
    {
675
        return $this->dropConstraintsForColumn($table, $column) . "\nALTER TABLE " . $this->db->quoteTableName($table)
676
            . ' DROP COLUMN ' . $this->db->quoteColumnName($column);
677
    }
678
}
679