Test Failed
Pull Request — master (#94)
by Wilmer
14:06 queued 02:52
created

DDLQueryBuilder::addCommentOnColumn()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 33
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 21
c 1
b 0
f 0
nc 8
nop 3
dl 0
loc 33
rs 9.584
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\Query\DDLQueryBuilder as AbstractDDLQueryBuilder;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Query\DDLQueryBuilder was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use Yiisoft\Db\Query\QueryBuilderInterface;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Query\QueryBuilderInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
12
13
final class DDLQueryBuilder extends AbstractDDLQueryBuilder
14
{
15
    public function __construct(private QueryBuilderInterface $queryBuilder)
16
    {
17
        parent::__construct($queryBuilder);
18
    }
19
20
    /**
21
     * @throws Exception|Throwable
22
     */
23
    public function addCommentOnColumn(string $table, string $column, string $comment): string
24
    {
25
        /* Strip existing comment which may include escaped quotes */
26
        $definition = trim(
27
            preg_replace(
28
                "/COMMENT '(?:''|[^'])*'/i",
29
                '',
30
                $this->getColumnDefinition($table, $column)
31
            )
32
        );
33
34
        $checkRegex = '/CHECK *(\(([^()]|(?-2))*\))/';
35
        $check = preg_match($checkRegex, $definition, $checkMatches);
36
37
        if ($check === 1) {
38
            $definition = preg_replace($checkRegex, '', $definition);
39
        }
40
41
        $alterSql = 'ALTER TABLE '
42
            . $this->queryBuilder->quoter()->quoteTableName($table)
43
            . ' CHANGE '
44
            . $this->queryBuilder->quoter()->quoteColumnName($column)
45
            . ' '
46
            . $this->queryBuilder->quoter()->quoteColumnName($column)
47
            . (empty($definition) ? '' : ' ' . $definition)
48
            . ' COMMENT '
49
            . $this->queryBuilder->quoter()->quoteValue($comment);
50
51
        if ($check === 1) {
52
            $alterSql .= ' ' . $checkMatches[0];
53
        }
54
55
        return $alterSql;
56
    }
57
58
    /**
59
     * @throws \Exception
60
     */
61
    public function addCommentOnTable(string $table, string $comment): string
62
    {
63
        return 'ALTER TABLE '
64
            . $this->queryBuilder->quoter()->quoteTableName($table)
65
            . ' COMMENT '
66
            . $this->queryBuilder->quoter()->quoteValue($comment);
67
    }
68
69
    /**
70
     * @throws Exception|InvalidArgumentException
71
     */
72
    public function createIndex(string $name, string $table, array|string $columns, bool $unique = false): string
73
    {
74
        return 'ALTER TABLE '
75
            . $this->queryBuilder->quoter()->quoteTableName($table)
76
            . ($unique ? ' ADD UNIQUE INDEX ' : ' ADD INDEX ')
77
            . $this->queryBuilder->quoter()->quoteTableName($name)
78
            . ' (' . $this->queryBuilder->buildColumns($columns) . ')';
79
    }
80
81
    public function dropForeignKey(string $name, string $table): string
82
    {
83
        return 'ALTER TABLE '
84
            . $this->queryBuilder->quoter()->quoteTableName($table)
85
            . ' DROP FOREIGN KEY '
86
            . $this->queryBuilder->quoter()->quoteColumnName($name);
87
    }
88
89
    public function dropPrimaryKey(string $name, string $table): string
90
    {
91
        return 'ALTER TABLE ' . $this->queryBuilder->quoter()->quoteTableName($table) . ' DROP PRIMARY KEY';
92
    }
93
94
    /**
95
     * @throws Exception|Throwable
96
     */
97
    public function renameColumn(string $table, string $oldName, string $newName): string
98
    {
99
        $quotedTable = $this->queryBuilder->quoter()->quoteTableName($table);
100
101
        /** @psalm-var array<array-key, string> $row */
102
        $row = $this->queryBuilder->command()->setSql('SHOW CREATE TABLE ' . $quotedTable)->queryOne();
103
104
        if (isset($row['Create Table'])) {
105
            $sql = $row['Create Table'];
106
        } else {
107
            $row = array_values($row);
108
            $sql = $row[1];
109
        }
110
111
        if (preg_match_all('/^\s*`(.*?)`\s+(.*?),?$/m', $sql, $matches)) {
112
            foreach ($matches[1] as $i => $c) {
113
                if ($c === $oldName) {
114
                    return "ALTER TABLE $quotedTable CHANGE "
115
                        . $this->queryBuilder->quoter()->quoteColumnName($oldName) . ' '
116
                        . $this->queryBuilder->quoter()->quoteColumnName($newName) . ' '
117
                        . $matches[2][$i];
118
                }
119
            }
120
        }
121
122
        /* try to give back a SQL anyway */
123
        return "ALTER TABLE $quotedTable CHANGE "
124
            . $this->queryBuilder->quoter()->quoteColumnName($oldName) . ' '
125
            . $this->queryBuilder->quoter()->quoteColumnName($newName);
126
    }
127
128
    /**
129
     * Gets column definition.
130
     *
131
     * @param string $table table name.
132
     * @param string $column column name.
133
     *
134
     * @throws Exception|Throwable in case when table does not contain column.
135
     *
136
     * @return string the column definition.
137
     */
138
    private function getColumnDefinition(string $table, string $column): string
139
    {
140
        $result = '';
141
        $quotedTable = $this->queryBuilder->quoter()->quoteTableName($table);
142
143
        /** @var array<array-key, string> $row */
144
        $row = $this->queryBuilder->command()->setSql('SHOW CREATE TABLE ' . $quotedTable)->queryOne();
145
146
        if (!isset($row['Create Table'])) {
147
            $row = array_values($row);
148
            $sql = $row[1];
149
        } else {
150
            $sql = $row['Create Table'];
151
        }
152
153
        if (preg_match_all('/^\s*`(.*?)`\s+(.*?),?$/m', $sql, $matches)) {
154
            foreach ($matches[1] as $i => $c) {
155
                if ($c === $column) {
156
                    $result = $matches[2][$i];
157
                }
158
            }
159
        }
160
161
        return $result;
162
    }
163
}
164