Passed
Push — master ( 6bbdcb...f9cfec )
by Def
05:50 queued 02:16
created

DDLQueryBuilder::dropCommentFromTable()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 1
b 0
f 0
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
{
23 521
    public function __construct(
24
        private QueryBuilderInterface $queryBuilder,
25
        private QuoterInterface $quoter,
26
        private SchemaInterface $schema
27
    ) {
28 521
        parent::__construct($queryBuilder, $quoter, $schema);
29
    }
30
31
    /**
32
     * @throws InvalidArgumentException
33
     */
34 5
    public function addCommentOnColumn(string $table, string $column, string $comment): string
35
    {
36 5
        return $this->buildAddCommentSql($comment, $table, $column);
37
    }
38
39
    /**
40
     * @throws InvalidArgumentException
41
     */
42 4
    public function addCommentOnTable(string $table, string $comment): string
43
    {
44 4
        return $this->buildAddCommentSql($comment, $table);
45
    }
46
47
    /**
48
     * @throws Exception
49
     */
50 8
    public function addDefaultValue(string $name, string $table, string $column, mixed $value): string
51
    {
52 8
        return 'ALTER TABLE '
53 8
            . $this->quoter->quoteTableName($table)
54 8
            . ' ADD CONSTRAINT '
55 8
            . $this->quoter->quoteColumnName($name)
56 8
            . ' DEFAULT ' . (string) $this->quoter->quoteValue($value)
57 8
            . ' FOR ' . $this->quoter->quoteColumnName($column);
58
    }
59
60 7
    public function alterColumn(string $table, string $column, ColumnSchemaBuilderInterface|string $type): string
61
    {
62 7
        $sqlAfter = [$this->dropConstraintsForColumn($table, $column, 'D')];
63
64 7
        $columnName = $this->quoter->quoteColumnName($column);
65 7
        $tableName = $this->quoter->quoteTableName($table);
66 7
        $constraintBase = preg_replace('/[^a-z0-9_]/i', '', $table . '_' . $column);
67
68 7
        if ($type instanceof ColumnSchemaBuilderInterface) {
69 6
            $type->setFormat('{type}{length}{notnull}{append}');
70
71
            /** @psalm-var mixed $defaultValue */
72 6
            $defaultValue = $type->getDefault();
73 6
            if ($defaultValue !== null) {
74 3
                $sqlAfter[] = $this->addDefaultValue(
75 3
                    "DF_{$constraintBase}",
76 3
                    $table,
77 3
                    $column,
78 3
                    $defaultValue
79 3
                );
80
            }
81
82 6
            $checkValue = $type->getCheck();
83 6
            if ($checkValue !== null) {
84 4
                $sqlAfter[] = "ALTER TABLE {$tableName} ADD CONSTRAINT " .
85 4
                    $this->quoter->quoteColumnName("CK_{$constraintBase}") .
86 4
                    ' CHECK (' . ($defaultValue instanceof Expression ? $checkValue : new Expression($checkValue)) . ')';
87
            }
88
89 6
            if ($type->isUnique()) {
90 3
                $sqlAfter[] = "ALTER TABLE {$tableName} ADD CONSTRAINT " . $this->quoter->quoteColumnName("UQ_{$constraintBase}") . " UNIQUE ({$columnName})";
91
            }
92
        }
93
94 7
        return 'ALTER TABLE ' . $tableName
95 7
            . ' ALTER COLUMN '
96 7
            . $columnName . ' '
97 7
            . $this->queryBuilder->getColumnType($type) . "\n"
98 7
            . implode("\n", $sqlAfter);
99
    }
100
101
    /**
102
     * @throws InvalidConfigException
103
     * @throws NotSupportedException
104
     * @throws Throwable
105
     * @throws \Yiisoft\Db\Exception\Exception
106
     */
107 3
    public function checkIntegrity(string $schema = '', string $table = '', bool $check = true): string
108
    {
109 3
        $enable = $check ? 'CHECK' : 'NOCHECK';
110
111
        /** @var Schema */
112 3
        $schemaInstance = $this->schema;
113 3
        $defaultSchema = $schema ?: $schemaInstance->getDefaultSchema() ?? '';
114
        /** @psalm-var string[] */
115 3
        $tableNames = $schemaInstance->getTableSchema($table)
116 3
             ? [$table] : $schemaInstance->getTableNames($defaultSchema);
117 3
        $viewNames = $schemaInstance->getViewNames($defaultSchema);
118 3
        $tableNames = array_diff($tableNames, $viewNames);
119 3
        $command = '';
120
121 3
        foreach ($tableNames as $tableName) {
122 3
            $tableName = $this->quoter->quoteTableName("$defaultSchema.$tableName");
123 3
            $command .= "ALTER TABLE $tableName $enable CONSTRAINT ALL; ";
124
        }
125
126 3
        return $command;
127
    }
128
129
    /**
130
     * @throws InvalidArgumentException
131
     */
132 3
    public function dropCommentFromColumn(string $table, string $column): string
133
    {
134 3
        return $this->buildRemoveCommentSql($table, $column);
135
    }
136
137
    /**
138
     * @throws InvalidArgumentException
139
     */
140 3
    public function dropCommentFromTable(string $table): string
141
    {
142 3
        return $this->buildRemoveCommentSql($table);
143
    }
144
145 4
    public function dropDefaultValue(string $name, string $table): string
146
    {
147 4
        return 'ALTER TABLE '
148 4
            . $this->quoter->quoteTableName($table)
149 4
            . ' DROP CONSTRAINT '
150 4
            . $this->quoter->quoteColumnName($name);
151
    }
152
153 3
    public function dropColumn(string $table, string $column): string
154
    {
155 3
        return $this->dropConstraintsForColumn($table, $column)
156 3
            . "\nALTER TABLE "
157 3
            . $this->quoter->quoteTableName($table)
158 3
            . ' DROP COLUMN '
159 3
            . $this->quoter->quoteColumnName($column);
160
    }
161
162 3
    public function renameTable(string $oldName, string $newName): string
163
    {
164 3
        return 'sp_rename '
165 3
            . $this->quoter->quoteTableName($oldName) . ', '
166 3
            . $this->quoter->quoteTableName($newName);
167
    }
168
169 2
    public function renameColumn(string $table, string $oldName, string $newName): string
170
    {
171 2
        return 'sp_rename '
172 2
            . "'" . $this->quoter->quoteTableName($table) . '.' . $this->quoter->quoteColumnName($oldName) . "'" . ', '
173 2
            . $this->quoter->quoteColumnName($newName) . ', '
174 2
            . "'COLUMN'";
175
    }
176
177
    /**
178
     * 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
     * @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
     * properly quoted by the method.
184
     * @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 9
    private function buildAddCommentSql(string $comment, string $table, string $column = null): string
193
    {
194 9
        $tableSchema = $this->schema->getTableSchema($table);
195
196 9
        if ($tableSchema === null) {
197 2
            throw new InvalidArgumentException("Table not found: $table");
198
        }
199
200 7
        $schemaName = $tableSchema->getSchemaName()
201 7
            ? "N'" . (string) $tableSchema->getSchemaName() . "'" : 'SCHEMA_NAME()';
202 7
        $tableName = 'N' . (string) $this->quoter->quoteValue($tableSchema->getName());
203 7
        $columnName = $column ? 'N' . (string) $this->quoter->quoteValue($column) : null;
204 7
        $comment = 'N' . (string) $this->quoter->quoteValue($comment);
205 7
        $functionParams = "
206
            @name = N'MS_description',
207 7
            @value = $comment,
208 7
            @level0type = N'SCHEMA', @level0name = $schemaName,
209 7
            @level1type = N'TABLE', @level1name = $tableName"
210 7
            . ($column ? ", @level2type = N'COLUMN', @level2name = $columnName" : '') . ';';
211
212 7
        return "
213
            IF NOT EXISTS (
214
                    SELECT 1
215
                    FROM fn_listextendedproperty (
216
                        N'MS_description',
217 7
                        'SCHEMA', $schemaName,
218 7
                        'TABLE', $tableName,
219 7
                        " . ($column ? "'COLUMN', $columnName " : ' DEFAULT, DEFAULT ') . "
220
                    )
221
            )
222 7
                EXEC sys.sp_addextendedproperty $functionParams
223
            ELSE
224 7
                EXEC sys.sp_updateextendedproperty $functionParams
225 7
        ";
226
    }
227
228
    /**
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 6
    private function buildRemoveCommentSql(string $table, string $column = null): string
243
    {
244 6
        $tableSchema = $this->schema->getTableSchema($table);
245
246 6
        if ($tableSchema === null) {
247 2
            throw new InvalidArgumentException("Table not found: $table");
248
        }
249
250 4
        $schemaName = $tableSchema->getSchemaName()
251 4
            ? "N'" . (string) $tableSchema->getSchemaName() . "'" : 'SCHEMA_NAME()';
252 4
        $tableName = 'N' . (string) $this->quoter->quoteValue($tableSchema->getName());
253 4
        $columnName = $column ? 'N' . (string) $this->quoter->quoteValue($column) : null;
254
255 4
        return "
256
            IF EXISTS (
257
                    SELECT 1
258
                    FROM fn_listextendedproperty (
259
                        N'MS_description',
260 4
                        'SCHEMA', $schemaName,
261 4
                        'TABLE', $tableName,
262 4
                        " . ($column ? "'COLUMN', $columnName " : ' DEFAULT, DEFAULT ') . "
263
                    )
264
            )
265
                EXEC sys.sp_dropextendedproperty
266
                    @name = N'MS_description',
267 4
                    @level0type = N'SCHEMA', @level0name = $schemaName,
268 4
                    @level1type = N'TABLE', @level1name = $tableName"
269 4
                    . ($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 9
    private function dropConstraintsForColumn(string $table, string $column, string $type = ''): string
284
    {
285 9
        return "DECLARE @tableName VARCHAR(MAX) = '" . $this->quoter->quoteTableName($table) . "'
286 9
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 9
        " . (!empty($type) ? " WHERE so.[type]='{$type}'" : '') . ")
303
    IF @constraintName IS NULL BREAK
304
    EXEC (N'ALTER TABLE ' + @tableName + ' DROP CONSTRAINT [' + @constraintName + ']')
305 9
END";
306
    }
307
}
308