Passed
Pull Request — master (#160)
by Wilmer
22:50 queued 19:49
created

DDLQueryBuilder::dropForeignKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 6
ccs 3
cts 3
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Mysql;
6
7
use Throwable;
8
use Yiisoft\Db\Exception\Exception;
9
use Yiisoft\Db\Exception\InvalidArgumentException;
10
use Yiisoft\Db\Exception\NotSupportedException;
11
use Yiisoft\Db\QueryBuilder\DDLQueryBuilder as AbstractDDLQueryBuilder;
12
use Yiisoft\Db\QueryBuilder\QueryBuilderInterface;
13
use Yiisoft\Db\Schema\QuoterInterface;
14
use Yiisoft\Db\Schema\SchemaInterface;
15
16
use function preg_match;
17
use function preg_replace;
18
use function trim;
19
20
final class DDLQueryBuilder extends AbstractDDLQueryBuilder
21
{
22 393
    public function __construct(
23
        private QueryBuilderInterface $queryBuilder,
24
        private QuoterInterface $quoter,
25
        private SchemaInterface $schema
26
    ) {
27 393
        parent::__construct($queryBuilder, $quoter, $schema);
28
    }
29
30
    /**
31
     * @throws NotSupportedException
32
     */
33
    public function addCheck(string $name, string $table, string $expression): string
34
    {
35
        throw new NotSupportedException(__METHOD__ . ' is not supported by MySQL.');
36
    }
37
38
    /**
39
     * @throws Exception|Throwable
40
     */
41 3
    public function addCommentOnColumn(string $table, string $column, string $comment): string
42
    {
43
        /* Strip existing comment which may include escaped quotes */
44 3
        $definition = trim(
45 3
            preg_replace(
46
                "/COMMENT '(?:''|[^'])*'/i",
47
                '',
48 3
                $this->getColumnDefinition($table, $column)
49
            )
50
        );
51
52 3
        $checkRegex = '/CHECK *(\(([^()]|(?-2))*\))/';
53 3
        $check = preg_match($checkRegex, $definition, $checkMatches);
54
55 3
        if ($check === 1) {
56
            $definition = preg_replace($checkRegex, '', $definition);
57
        }
58
59 3
        $alterSql = 'ALTER TABLE '
60 3
            . $this->quoter->quoteTableName($table)
61
            . ' CHANGE '
62 3
            . $this->quoter->quoteColumnName($column)
63
            . ' '
64 3
            . $this->quoter->quoteColumnName($column)
65 3
            . (empty($definition) ? '' : ' ' . $definition)
66
            . ' COMMENT '
67 3
            . (string) $this->quoter->quoteValue($comment);
68
69 3
        if ($check === 1) {
70
            $alterSql .= ' ' . $checkMatches[0];
71
        }
72
73 3
        return $alterSql;
74
    }
75
76
    /**
77
     * @throws \Exception
78
     */
79 3
    public function addCommentOnTable(string $table, string $comment): string
80
    {
81
        return 'ALTER TABLE '
82 3
            . $this->quoter->quoteTableName($table)
83
            . ' COMMENT '
84 3
            . (string) $this->quoter->quoteValue($comment);
85
    }
86
87
    /**
88
     * @throws Exception|InvalidArgumentException
89
     */
90 9
    public function createIndex(
91
        string $name,
92
        string $table,
93
        array|string $columns,
94
        string $indexType = null,
95
        string $indexMethod = null
96
    ): string {
97 9
        return 'CREATE ' . ($indexType ? ($indexType . ' ') : '') . 'INDEX '
98 9
            . $this->quoter->quoteTableName($name)
99 9
            . ($indexMethod !== null ? " USING $indexMethod" : '')
100 9
            . ' ON ' . $this->quoter->quoteTableName($table)
101 9
            . ' (' . $this->queryBuilder->buildColumns($columns) . ')';
102
    }
103
104 2
    public function checkIntegrity(string $schema = '', string $table = '', bool $check = true): string
105
    {
106 2
        return 'SET FOREIGN_KEY_CHECKS = ' . ($check ? 1 : 0);
107
    }
108
109
    /**
110
     * @throws NotSupportedException
111
     */
112 1
    public function dropCheck(string $name, string $table): string
113
    {
114 1
        throw new NotSupportedException(__METHOD__ . ' is not supported by MySQL.');
115
    }
116
117
    /**
118
     * @throws Exception|Throwable
119
     */
120 2
    public function dropCommentFromColumn(string $table, string $column): string
121
    {
122 2
        return $this->addCommentOnColumn($table, $column, '');
123
    }
124
125
    /**
126
     * @throws \Exception
127
     */
128 2
    public function dropCommentFromTable(string $table): string
129
    {
130 2
        return $this->addCommentOnTable($table, '');
131
    }
132
133 2
    public function dropForeignKey(string $name, string $table): string
134
    {
135
        return 'ALTER TABLE '
136 2
            . $this->quoter->quoteTableName($table)
137
            . ' DROP FOREIGN KEY '
138 2
            . $this->quoter->quoteColumnName($name);
139
    }
140
141 2
    public function dropPrimaryKey(string $name, string $table): string
142
    {
143 2
        return 'ALTER TABLE ' . $this->quoter->quoteTableName($table) . ' DROP PRIMARY KEY';
144
    }
145
146 2
    public function dropUnique(string $name, string $table): string
147
    {
148 2
        return $this->dropIndex($name, $table);
149
    }
150
151
    /**
152
     * @throws Exception|Throwable
153
     */
154 2
    public function renameColumn(string $table, string $oldName, string $newName): string
155
    {
156 2
        $quotedTable = $this->quoter->quoteTableName($table);
157
158 2
        $columnDefinition = $this->getColumnDefinition($table, $oldName);
159
160
        /* try to give back a SQL anyway */
161 2
        return "ALTER TABLE $quotedTable CHANGE "
162 2
            . $this->quoter->quoteColumnName($oldName) . ' '
163 2
            . $this->quoter->quoteColumnName($newName)
164 2
            . (!empty($columnDefinition) ? ' ' . $columnDefinition : '');
165
    }
166
167
    /**
168
     * Gets column definition.
169
     *
170
     * @param string $table table name.
171
     * @param string $column column name.
172
     *
173
     * @throws Exception|Throwable in case when table does not contain column.
174
     *
175
     * @return string the column definition.
176
     */
177 5
    public function getColumnDefinition(string $table, string $column): string
178
    {
179 5
        $result = '';
180
181 5
        $sql = $this->schema->getTableSchema($table)?->getCreateSql();
182
183 5
        if (empty($sql)) {
184
            return '';
185
        }
186
187 5
        if (preg_match_all('/^\s*`(.*?)`\s+(.*?),?$/m', $sql, $matches)) {
188 5
            foreach ($matches[1] as $i => $c) {
189 5
                if ($c === $column) {
190 5
                    $result = $matches[2][$i];
191
                }
192
            }
193
        }
194
195 5
        return $result;
196
    }
197
}
198