Test Failed
Push — remove-unsed-class ( 5007c9 )
by Wilmer
34:07 queued 20:38
created

DDLQueryBuilder::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
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
c 1
b 0
f 0
nc 1
nop 3
dl 0
loc 6
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Pgsql;
6
7
use Throwable;
8
use Yiisoft\Db\Exception\NotSupportedException;
9
use Yiisoft\Db\QueryBuilder\AbstractDDLQueryBuilder;
10
use Yiisoft\Db\Schema\Builder\ColumnInterface;
11
12
use function array_diff;
13
use function array_unshift;
14
use function explode;
15
use function implode;
16
use function preg_match;
17
use function preg_replace;
18
use function str_contains;
19
20
/**
21
 * Implements a (Data Definition Language) SQL statements for PostgreSQL Server.
22
 */
23
final class DDLQueryBuilder extends AbstractDDLQueryBuilder
24
{
25
    public function addDefaultValue(string $table, string $name, string $column, mixed $value): string
26
    {
27
        throw new NotSupportedException(__METHOD__ . ' is not supported by PostgreSQL.');
28
    }
29
30
    public function alterColumn(string $table, string $column, ColumnInterface|string $type): string
31
    {
32
        $columnName = $this->quoter->quoteColumnName($column);
0 ignored issues
show
Bug introduced by
The property quoter is declared private in Yiisoft\Db\QueryBuilder\AbstractDDLQueryBuilder and cannot be accessed from this context.
Loading history...
33
        $tableName = $this->quoter->quoteTableName($table);
34
35
        if ($type instanceof ColumnInterface) {
36
            $type = $type->asString();
37
        }
38
39
        /**
40
         * @link https://github.com/yiisoft/yii2/issues/4492
41
         * @link https://www.postgresql.org/docs/9.1/static/sql-altertable.html
42
         */
43
        if (preg_match('/^(DROP|SET|RESET|USING)\s+/i', $type)) {
44
            return "ALTER TABLE $tableName ALTER COLUMN $columnName $type";
45
        }
46
47
        $type = 'TYPE ' . $this->queryBuilder->getColumnType($type);
0 ignored issues
show
Bug introduced by
The property queryBuilder is declared private in Yiisoft\Db\QueryBuilder\AbstractDDLQueryBuilder and cannot be accessed from this context.
Loading history...
48
        $multiAlterStatement = [];
49
        $constraintPrefix = preg_replace('/[^a-z0-9_]/i', '', $table . '_' . $column);
50
51
        if (preg_match('/\s+DEFAULT\s+(["\']?\w*["\']?)/i', $type, $matches)) {
52
            $type = preg_replace('/\s+DEFAULT\s+(["\']?\w*["\']?)/i', '', $type);
53
            $multiAlterStatement[] = "ALTER COLUMN $columnName SET DEFAULT $matches[1]";
54
        }
55
56
        $type = preg_replace('/\s+NOT\s+NULL/i', '', $type, -1, $count);
57
58
        if ($count) {
59
            $multiAlterStatement[] = "ALTER COLUMN $columnName SET NOT NULL";
60
        } else {
61
            /** remove additional null if any */
62
            $type = preg_replace('/\s+NULL/i', '', $type, -1, $count);
63
            if ($count) {
64
                $multiAlterStatement[] = "ALTER COLUMN $columnName DROP NOT NULL";
65
            }
66
        }
67
68
        if (preg_match('/\s+CHECK\s+\((.+)\)/i', $type, $matches)) {
69
            $type = preg_replace('/\s+CHECK\s+\((.+)\)/i', '', $type);
70
            $multiAlterStatement[] = "ADD CONSTRAINT {$constraintPrefix}_check CHECK ($matches[1])";
71
        }
72
73
        $type = preg_replace('/\s+UNIQUE/i', '', $type, -1, $count);
74
75
        if ($count) {
76
            $multiAlterStatement[] = "ADD UNIQUE ($columnName)";
77
        }
78
79
        /** add what's left at the beginning */
80
        array_unshift($multiAlterStatement, "ALTER COLUMN $columnName $type");
81
82
        return 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $multiAlterStatement);
83
    }
84
85
    /**
86
     * @throws Throwable
87
     */
88
    public function checkIntegrity(string $schema = '', string $table = '', bool $check = true): string
89
    {
90
        /** @psalm-var Schema $schemaInstance */
91
        $schemaInstance = $this->schema;
0 ignored issues
show
Bug introduced by
The property schema is declared private in Yiisoft\Db\QueryBuilder\AbstractDDLQueryBuilder and cannot be accessed from this context.
Loading history...
92
        $enable = $check ? 'ENABLE' : 'DISABLE';
93
        $schema = $schema ?: $schemaInstance->getDefaultSchema();
94
        $tableNames = [];
95
        $viewNames = [];
96
97
        if ($schema !== null) {
98
            $tableNames = $table ? [$table] : $schemaInstance->getTableNames($schema);
99
            $viewNames = $schemaInstance->getViewNames($schema);
100
        }
101
102
        $tableNames = array_diff($tableNames, $viewNames);
103
        $command = '';
104
105
        /** @psalm-var string[] $tableNames */
106
        foreach ($tableNames as $tableName) {
107
            $tableName = $this->quoter->quoteTableName("$schema.$tableName");
0 ignored issues
show
Bug introduced by
The property quoter is declared private in Yiisoft\Db\QueryBuilder\AbstractDDLQueryBuilder and cannot be accessed from this context.
Loading history...
108
            $command .= "ALTER TABLE $tableName $enable TRIGGER ALL; ";
109
        }
110
111
        return $command;
112
    }
113
114
    public function createIndex(string $table, string $name, array|string $columns, ?string $indexType = null, ?string $indexMethod = null): string
115
    {
116
        return 'CREATE ' . ($indexType ? ($indexType . ' ') : '') . 'INDEX '
117
            . $this->quoter->quoteTableName($name) . ' ON '
0 ignored issues
show
Bug introduced by
The property quoter is declared private in Yiisoft\Db\QueryBuilder\AbstractDDLQueryBuilder and cannot be accessed from this context.
Loading history...
118
            . $this->quoter->quoteTableName($table)
119
            . ($indexMethod !== null ? " USING $indexMethod" : '')
120
            . ' (' . $this->queryBuilder->buildColumns($columns) . ')';
0 ignored issues
show
Bug introduced by
The property queryBuilder is declared private in Yiisoft\Db\QueryBuilder\AbstractDDLQueryBuilder and cannot be accessed from this context.
Loading history...
121
    }
122
123
    public function dropDefaultValue(string $table, string $name): string
124
    {
125
        throw new NotSupportedException(__METHOD__ . ' is not supported by PostgreSQL.');
126
    }
127
128
    public function dropIndex(string $table, string $name): string
129
    {
130
        if (str_contains($table, '.') && !str_contains($name, '.')) {
131
            if (str_contains($table, '{{')) {
132
                $table = preg_replace('/{{(.*?)}}/', '\1', $table);
133
                [$schema] = explode('.', $table);
134
                if (!str_contains($schema, '%')) {
135
                    $name = $schema . '.' . $name;
136
                } else {
137
                    $name = '{{' . $schema . '.' . $name . '}}';
138
                }
139
            } else {
140
                [$schema] = explode('.', $table);
141
                $name = $schema . '.' . $name;
142
            }
143
        }
144
145
        return 'DROP INDEX ' . $this->quoter->quoteTableName($name);
0 ignored issues
show
Bug introduced by
The property quoter is declared private in Yiisoft\Db\QueryBuilder\AbstractDDLQueryBuilder and cannot be accessed from this context.
Loading history...
146
    }
147
148
    public function truncateTable(string $table): string
149
    {
150
        return 'TRUNCATE TABLE ' . $this->quoter->quoteTableName($table) . ' RESTART IDENTITY';
0 ignored issues
show
Bug introduced by
The property quoter is declared private in Yiisoft\Db\QueryBuilder\AbstractDDLQueryBuilder and cannot be accessed from this context.
Loading history...
151
    }
152
153
    public function renameTable(string $oldName, string $newName): string
154
    {
155
        return 'ALTER TABLE '
156
            . $this->quoter->quoteTableName($oldName)
0 ignored issues
show
Bug introduced by
The property quoter is declared private in Yiisoft\Db\QueryBuilder\AbstractDDLQueryBuilder and cannot be accessed from this context.
Loading history...
157
            . ' RENAME TO '
158
            . $this->quoter->quoteTableName($newName);
159
    }
160
}
161