Test Failed
Push — master ( 04353a...6bbdcb )
by Def
07:36 queued 03:45
created

DDLQueryBuilder::dropConstraintsForColumn()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 20
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
nc 2
nop 3
dl 0
loc 20
ccs 0
cts 0
cp 0
crap 6
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Mssql;
6
7
use Exception;
8
use Throwable;
9
use Yiisoft\Db\Exception\InvalidArgumentException;
10
use Yiisoft\Db\Exception\InvalidConfigException;
11
use Yiisoft\Db\Exception\NotSupportedException;
12
use Yiisoft\Db\Expression\Expression;
13
use Yiisoft\Db\QueryBuilder\AbstractDDLQueryBuilder;
14
use Yiisoft\Db\QueryBuilder\QueryBuilderInterface;
15
use Yiisoft\Db\Schema\ColumnSchemaBuilderInterface;
16
use Yiisoft\Db\Schema\QuoterInterface;
17
use Yiisoft\Db\Schema\SchemaInterface;
18
19
use function array_diff;
20
21
final class DDLQueryBuilder extends AbstractDDLQueryBuilder
22 516
{
23
    public function __construct(
24
        private QueryBuilderInterface $queryBuilder,
25
        private QuoterInterface $quoter,
26
        private SchemaInterface $schema
27 516
    ) {
28
        parent::__construct($queryBuilder, $quoter, $schema);
29
    }
30
31
    /**
32
     * @throws InvalidArgumentException
33 5
     */
34
    public function addCommentOnColumn(string $table, string $column, string $comment): string
35 5
    {
36
        return $this->buildAddCommentSql($comment, $table, $column);
37
    }
38
39
    /**
40
     * @throws InvalidArgumentException
41 4
     */
42
    public function addCommentOnTable(string $table, string $comment): string
43 4
    {
44
        return $this->buildAddCommentSql($comment, $table);
45
    }
46
47
    /**
48
     * @throws Exception
49 5
     */
50
    public function addDefaultValue(string $name, string $table, string $column, mixed $value): string
51 5
    {
52 5
        return 'ALTER TABLE '
53 5
            . $this->quoter->quoteTableName($table)
54 5
            . ' ADD CONSTRAINT '
55 5
            . $this->quoter->quoteColumnName($name)
56 5
            . ' DEFAULT ' . (string) $this->quoter->quoteValue($value)
57
            . ' FOR ' . $this->quoter->quoteColumnName($column);
58
    }
59 2
60
    public function alterColumn(string $table, string $column, ColumnSchemaBuilderInterface|string $type): string
61 2
    {
62 2
        $sqlAfter = [$this->dropConstraintsForColumn($table, $column, 'D')];
63 2
64 2
        $columnName = $this->quoter->quoteColumnName($column);
65 2
        $tableName = $this->quoter->quoteTableName($table);
66 2
        $constraintBase = preg_replace('/[^a-z0-9_]/i', '', $table . '_' . $column);
67
68
        if ($type instanceof ColumnSchemaBuilderInterface) {
69
            $type->setFormat('{type}{length}{notnull}{append}');
0 ignored issues
show
Bug introduced by
The method setFormat() does not exist on Yiisoft\Db\Schema\ColumnSchemaBuilderInterface. ( Ignorable by Annotation )

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

69
            $type->/** @scrutinizer ignore-call */ 
70
                   setFormat('{type}{length}{notnull}{append}');

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
70
71
            /** @psalm-var mixed $defaultValue */
72
            $defaultValue = $type->getDefault();
73
            if ($defaultValue !== null) {
74
                $sqlAfter[] = $this->addDefaultValue(
75 3
                    "DF_{$constraintBase}",
76
                    $table,
77 3
                    $column,
78
                    $defaultValue
79
                );
80 3
            }
81 3
82
            $checkValue = $type->getCheck();
83 3
            if ($checkValue !== null) {
84 3
                $sqlAfter[] = "ALTER TABLE {$tableName} ADD CONSTRAINT " .
85 3
                    $this->quoter->quoteColumnName("CK_{$constraintBase}") .
86 3
                    ' CHECK (' . ($defaultValue instanceof Expression ? $checkValue : new Expression($checkValue)) . ')';
87 3
            }
88
89 3
            if ($type->isUnique()) {
90 3
                $sqlAfter[] = "ALTER TABLE {$tableName} ADD CONSTRAINT " . $this->quoter->quoteColumnName("UQ_{$constraintBase}") . " UNIQUE ({$columnName})";
91 3
            }
92
        }
93
94 3
        return 'ALTER TABLE ' . $tableName
95
            . ' ALTER COLUMN '
96
            . $columnName . ' '
97
            . $this->queryBuilder->getColumnType($type) . "\n"
98
            . implode("\n", $sqlAfter);
99
    }
100 3
101
    /**
102 3
     * @throws InvalidConfigException
103
     * @throws NotSupportedException
104
     * @throws Throwable
105
     * @throws \Yiisoft\Db\Exception\Exception
106
     */
107
    public function checkIntegrity(string $schema = '', string $table = '', bool $check = true): string
108 3
    {
109
        $enable = $check ? 'CHECK' : 'NOCHECK';
110 3
111
        /** @var Schema */
112
        $schemaInstance = $this->schema;
113 4
        $defaultSchema = $schema ?: $schemaInstance->getDefaultSchema() ?? '';
114
        /** @psalm-var string[] */
115 4
        $tableNames = $schemaInstance->getTableSchema($table)
116 4
             ? [$table] : $schemaInstance->getTableNames($defaultSchema);
117 4
        $viewNames = $schemaInstance->getViewNames($defaultSchema);
118 4
        $tableNames = array_diff($tableNames, $viewNames);
119
        $command = '';
120
121 3
        foreach ($tableNames as $tableName) {
122
            $tableName = $this->quoter->quoteTableName("$defaultSchema.$tableName");
123 3
            $command .= "ALTER TABLE $tableName $enable CONSTRAINT ALL; ";
124 3
        }
125 3
126
        return $command;
127
    }
128 2
129
    /**
130 2
     * @throws InvalidArgumentException
131 2
     */
132 2
    public function dropCommentFromColumn(string $table, string $column): string
133 2
    {
134
        return $this->buildRemoveCommentSql($table, $column);
135
    }
136
137
    /**
138
     * @throws InvalidArgumentException
139
     */
140
    public function dropCommentFromTable(string $table): string
141
    {
142
        return $this->buildRemoveCommentSql($table);
143
    }
144
145
    public function dropDefaultValue(string $name, string $table): string
146
    {
147
        return 'ALTER TABLE '
148
            . $this->quoter->quoteTableName($table)
149
            . ' DROP CONSTRAINT '
150
            . $this->quoter->quoteColumnName($name);
151 9
    }
152
153 9
    public function dropColumn(string $table, string $column): string
154
    {
155 9
        return $this->dropConstraintsForColumn($table, $column)
156 2
            . "\nALTER TABLE "
157
            . $this->quoter->quoteTableName($table)
158
            . ' DROP COLUMN '
159 7
            . $this->quoter->quoteColumnName($column);
160 7
    }
161 7
162 7
    public function renameTable(string $oldName, string $newName): string
163 7
    {
164 7
        return 'sp_rename '
165
            . $this->quoter->quoteTableName($oldName) . ', '
166 7
            . $this->quoter->quoteTableName($newName);
167 7
    }
168 7
169 7
    public function renameColumn(string $table, string $oldName, string $newName): string
170
    {
171 7
        return 'sp_rename '
172
            . "'" . $this->quoter->quoteTableName($table) . '.' . $this->quoter->quoteColumnName($oldName) . "'" . ', '
173
            . $this->quoter->quoteColumnName($newName) . ', '
174
            . "'COLUMN'";
175
    }
176 7
177 7
    /**
178 7
     * Builds a SQL command for adding or updating a comment to a table or a column. The command built will check if a
179
     * comment already exists. If so, it will be updated, otherwise, it will be added.
180
     *
181 7
     * @param string $comment The text of the comment to be added. The comment will be properly quoted by the method.
182
     * @param string $table The table to be commented or whose column is to be commented. The table name will be
183 7
     * properly quoted by the method.
184 7
     * @param string|null $column Optional, the name of the column to be commented. If empty, the command will add the
185
     * comment to the table instead. The column name will be properly quoted by the method.
186
     *
187
     * @throws Exception
188
     * @throws InvalidArgumentException If the table does not exist.
189
     *
190
     * @return string The SQL statement for adding a comment.
191
     */
192
    private function buildAddCommentSql(string $comment, string $table, string $column = null): string
193
    {
194
        $tableSchema = $this->schema->getTableSchema($table);
195
196
        if ($tableSchema === null) {
197
            throw new InvalidArgumentException("Table not found: $table");
198
        }
199
200
        $schemaName = $tableSchema->getSchemaName()
201 6
            ? "N'" . (string) $tableSchema->getSchemaName() . "'" : 'SCHEMA_NAME()';
202
        $tableName = 'N' . (string) $this->quoter->quoteValue($tableSchema->getName());
203 6
        $columnName = $column ? 'N' . (string) $this->quoter->quoteValue($column) : null;
204
        $comment = 'N' . (string) $this->quoter->quoteValue($comment);
205 6
        $functionParams = "
206 2
            @name = N'MS_description',
207
            @value = $comment,
208
            @level0type = N'SCHEMA', @level0name = $schemaName,
209 4
            @level1type = N'TABLE', @level1name = $tableName"
210 4
            . ($column ? ", @level2type = N'COLUMN', @level2name = $columnName" : '') . ';';
211 4
212 4
        return "
213
            IF NOT EXISTS (
214 4
                    SELECT 1
215
                    FROM fn_listextendedproperty (
216
                        N'MS_description',
217
                        'SCHEMA', $schemaName,
218
                        'TABLE', $tableName,
219 4
                        " . ($column ? "'COLUMN', $columnName " : ' DEFAULT, DEFAULT ') . "
220 4
                    )
221 4
            )
222
                EXEC sys.sp_addextendedproperty $functionParams
223
            ELSE
224
                EXEC sys.sp_updateextendedproperty $functionParams
225
        ";
226 4
    }
227 4
228 4
    /**
229
     * Builds a SQL command for removing a comment from a table or a column. The command built will check if a comment
230
     * already exists before trying to perform the removal.
231
     *
232
     * @param string $table The table that will have the comment removed or whose column will have the comment removed.
233
     * The table name will be properly quoted by the method.
234
     * @param string|null $column Optional, the name of the column whose comment will be removed. If empty, the command
235
     * will remove the comment from the table instead. The column name will be properly quoted by the method.
236
     *
237
     * @throws Exception
238
     * @throws InvalidArgumentException If the table does not exist.
239
     *
240
     * @return string The SQL statement for removing the comment.
241
     */
242
    private function buildRemoveCommentSql(string $table, string $column = null): string
243
    {
244
        $tableSchema = $this->schema->getTableSchema($table);
245
246
        if ($tableSchema === null) {
247
            throw new InvalidArgumentException("Table not found: $table");
248
        }
249
250
        $schemaName = $tableSchema->getSchemaName()
251
            ? "N'" . (string) $tableSchema->getSchemaName() . "'" : 'SCHEMA_NAME()';
252
        $tableName = 'N' . (string) $this->quoter->quoteValue($tableSchema->getName());
253
        $columnName = $column ? 'N' . (string) $this->quoter->quoteValue($column) : null;
254
255
        return "
256
            IF EXISTS (
257
                    SELECT 1
258
                    FROM fn_listextendedproperty (
259
                        N'MS_description',
260
                        'SCHEMA', $schemaName,
261
                        'TABLE', $tableName,
262
                        " . ($column ? "'COLUMN', $columnName " : ' DEFAULT, DEFAULT ') . "
263
                    )
264
            )
265
                EXEC sys.sp_dropextendedproperty
266
                    @name = N'MS_description',
267
                    @level0type = N'SCHEMA', @level0name = $schemaName,
268
                    @level1type = N'TABLE', @level1name = $tableName"
269
                    . ($column ? ", @level2type = N'COLUMN', @level2name = $columnName" : '') . ';';
270
    }
271
272
    /**
273
     * Builds a SQL statement for dropping constraints for column of table.
274
     *
275
     * @param string $table the table whose constraint is to be dropped. The name will be properly quoted by the method.
276
     * @param string $column the column whose constraint is to be dropped. The name will be properly quoted by the method.
277
     * @param string $type type of constraint, leave empty for all type of constraints(for example: D - default, 'UQ' - unique, 'C' - check)
278
     *
279
     * @return string the DROP CONSTRAINTS SQL
280
     *
281
     * @see https://docs.microsoft.com/sql/relational-databases/system-catalog-views/sys-objects-transact-sql
282
     */
283
    private function dropConstraintsForColumn(string $table, string $column, string $type = ''): string
284
    {
285
        return "DECLARE @tableName VARCHAR(MAX) = '" . $this->quoter->quoteTableName($table) . "'
286
DECLARE @columnName VARCHAR(MAX) = '{$column}'
287
WHILE 1=1 BEGIN
288
    DECLARE @constraintName NVARCHAR(128)
289
    SET @constraintName = (SELECT TOP 1 OBJECT_NAME(cons.[object_id])
290
        FROM (
291
            SELECT sc.[constid] object_id
292
            FROM [sys].[sysconstraints] sc
293
            JOIN [sys].[columns] c ON c.[object_id]=sc.[id] AND c.[column_id]=sc.[colid] AND c.[name]=@columnName
294
            WHERE sc.[id] = OBJECT_ID(@tableName)
295
            UNION
296
            SELECT object_id(i.[name]) FROM [sys].[indexes] i
297
            JOIN [sys].[columns] c ON c.[object_id]=i.[object_id] AND c.[name]=@columnName
298
            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]
299
            WHERE i.[is_unique_constraint]=1 and i.[object_id]=OBJECT_ID(@tableName)
300
        ) cons
301
        JOIN [sys].[objects] so ON so.[object_id]=cons.[object_id]
302
        " . (!empty($type) ? " WHERE so.[type]='{$type}'" : '') . ")
303
    IF @constraintName IS NULL BREAK
304
    EXEC (N'ALTER TABLE ' + @tableName + ' DROP CONSTRAINT [' + @constraintName + ']')
305
END";
306
    }
307
}
308