Completed
Push — master ( e0dde8...a7d2aa )
by Carsten
09:47
created

QueryBuilder::dropIndex()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 0
cts 10
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 2
crap 12
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db\cubrid;
9
10
use yii\base\InvalidParamException;
11
use yii\base\NotSupportedException;
12
use yii\db\Exception;
13
14
/**
15
 * QueryBuilder is the query builder for CUBRID databases (version 9.3.x and higher).
16
 *
17
 * @author Carsten Brandt <[email protected]>
18
 * @since 2.0
19
 */
20
class QueryBuilder extends \yii\db\QueryBuilder
21
{
22
    /**
23
     * @var array mapping from abstract column types (keys) to physical column types (values).
24
     */
25
    public $typeMap = [
26
        Schema::TYPE_PK => 'int NOT NULL AUTO_INCREMENT PRIMARY KEY',
27
        Schema::TYPE_UPK => 'int UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY',
28
        Schema::TYPE_BIGPK => 'bigint NOT NULL AUTO_INCREMENT PRIMARY KEY',
29
        Schema::TYPE_UBIGPK => 'bigint UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY',
30
        Schema::TYPE_CHAR => 'char(1)',
31
        Schema::TYPE_STRING => 'varchar(255)',
32
        Schema::TYPE_TEXT => 'varchar',
33
        Schema::TYPE_SMALLINT => 'smallint',
34
        Schema::TYPE_INTEGER => 'int',
35
        Schema::TYPE_BIGINT => 'bigint',
36
        Schema::TYPE_FLOAT => 'float(7)',
37
        Schema::TYPE_DOUBLE => 'double(15)',
38
        Schema::TYPE_DECIMAL => 'decimal(10,0)',
39
        Schema::TYPE_DATETIME => 'datetime',
40
        Schema::TYPE_TIMESTAMP => 'timestamp',
41
        Schema::TYPE_TIME => 'time',
42
        Schema::TYPE_DATE => 'date',
43
        Schema::TYPE_BINARY => 'blob',
44
        Schema::TYPE_BOOLEAN => 'smallint',
45
        Schema::TYPE_MONEY => 'decimal(19,4)',
46
    ];
47
48
    /**
49
     * @inheritdoc
50
     */
51
    protected $likeEscapeCharacter = '!';
52
    /**
53
     * @inheritdoc
54
     */
55
    protected $likeEscapingReplacements = [
56
        '%' => '!%',
57
        '_' => '!_',
58
        '!' => '!!',
59
    ];
60
61
62
    /**
63
     * Creates a SQL statement for resetting the sequence value of a table's primary key.
64
     * The sequence will be reset such that the primary key of the next new row inserted
65
     * will have the specified value or 1.
66
     * @param string $tableName the name of the table whose primary key sequence will be reset
67
     * @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
68
     * the next new row's primary key will have a value 1.
69
     * @return string the SQL statement for resetting sequence
70
     * @throws InvalidParamException if the table does not exist or there is no sequence associated with the table.
71
     */
72
    public function resetSequence($tableName, $value = null)
73
    {
74
        $table = $this->db->getTableSchema($tableName);
75
        if ($table !== null && $table->sequenceName !== null) {
76
            $tableName = $this->db->quoteTableName($tableName);
77
            if ($value === null) {
78
                $key = reset($table->primaryKey);
79
                $value = (int) $this->db->createCommand("SELECT MAX(`$key`) FROM " . $this->db->schema->quoteTableName($tableName))->queryScalar() + 1;
80
            } else {
81
                $value = (int) $value;
82
            }
83
84
            return 'ALTER TABLE ' . $this->db->schema->quoteTableName($tableName) . " AUTO_INCREMENT=$value;";
85
        } elseif ($table === null) {
86
            throw new InvalidParamException("Table not found: $tableName");
87
        } else {
88
            throw new InvalidParamException("There is not sequence associated with table '$tableName'.");
89
        }
90
    }
91
92
    /**
93
     * @inheritdoc
94
     */
95
    public function buildLimit($limit, $offset)
96
    {
97
        $sql = '';
98
        // limit is not optional in CUBRID
99
        // http://www.cubrid.org/manual/90/en/LIMIT%20Clause
100
        // "You can specify a very big integer for row_count to display to the last row, starting from a specific row."
101
        if ($this->hasLimit($limit)) {
102
            $sql = 'LIMIT ' . $limit;
103
            if ($this->hasOffset($offset)) {
104
                $sql .= ' OFFSET ' . $offset;
105
            }
106
        } elseif ($this->hasOffset($offset)) {
107
            $sql = "LIMIT 9223372036854775807 OFFSET $offset"; // 2^63-1
108
        }
109
110
        return $sql;
111
    }
112
113
    /**
114
     * @inheritdoc
115
     * @since 2.0.8
116
     */
117
    public function selectExists($rawSql)
118
    {
119
        return 'SELECT CASE WHEN EXISTS(' . $rawSql . ') THEN 1 ELSE 0 END';
120
    }
121
122
    /**
123
     * @inheritDoc
124
     * @see http://www.cubrid.org/manual/93/en/sql/schema/table.html#drop-index-clause
125
     */
126
    public function dropIndex($name, $table)
127
    {
128
        /** @var Schema $schema */
129
        $schema = $this->db->getSchema();
130
        foreach ($schema->getTableUniques($table) as $unique) {
131
            if ($unique->name === $name) {
132
                return $this->dropUnique($name, $table);
133
            }
134
        }
135
136
        return 'DROP INDEX ' . $this->db->quoteTableName($name) . ' ON ' . $this->db->quoteTableName($table);
137
    }
138
139
    /**
140
     * @inheritDoc
141
     * @throws NotSupportedException this is not supported by CUBRID.
142
     */
143
    public function addCheck($name, $table, $expression)
144
    {
145
        throw new NotSupportedException(__METHOD__ . ' is not supported by CUBRID.');
146
    }
147
148
    /**
149
     * @inheritDoc
150
     * @throws NotSupportedException this is not supported by CUBRID.
151
     */
152
    public function dropCheck($name, $table)
153
    {
154
        throw new NotSupportedException(__METHOD__ . ' is not supported by CUBRID.');
155
    }
156
157
    /**
158
     * @inheritdoc
159
     * @since 2.0.8
160
     */
161
    public function addCommentOnColumn($table, $column, $comment)
162
    {
163
        $definition = $this->getColumnDefinition($table, $column);
164
        $definition = trim(preg_replace("/COMMENT '(.*?)'/i", '', $definition));
165
166
        return 'ALTER TABLE ' . $this->db->quoteTableName($table)
167
        . ' CHANGE ' . $this->db->quoteColumnName($column)
168
        . ' ' . $this->db->quoteColumnName($column)
169
        . (empty($definition) ? '' : ' ' . $definition)
170
        . ' COMMENT ' . $this->db->quoteValue($comment);
171
    }
172
173
    /**
174
     * @inheritdoc
175
     * @since 2.0.8
176
     */
177
    public function addCommentOnTable($table, $comment)
178
    {
179
        return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' COMMENT ' . $this->db->quoteValue($comment);
180
    }
181
182
    /**
183
     * @inheritdoc
184
     * @since 2.0.8
185
     */
186
    public function dropCommentFromColumn($table, $column)
187
    {
188
        return $this->addCommentOnColumn($table, $column, '');
189
    }
190
191
    /**
192
     * @inheritdoc
193
     * @since 2.0.8
194
     */
195
    public function dropCommentFromTable($table)
196
    {
197
        return $this->addCommentOnTable($table, '');
198
    }
199
200
201
    /**
202
     * Gets column definition.
203
     *
204
     * @param string $table table name
205
     * @param string $column column name
206
     * @return null|string the column definition
207
     * @throws Exception in case when table does not contain column
208
     * @since 2.0.8
209
     */
210
    private function getColumnDefinition($table, $column)
211
    {
212
        $row = $this->db->createCommand('SHOW CREATE TABLE ' . $this->db->quoteTableName($table))->queryOne();
213
        if ($row === false) {
214
            throw new Exception("Unable to find column '$column' in table '$table'.");
215
        }
216
        if (isset($row['Create Table'])) {
217
            $sql = $row['Create Table'];
218
        } else {
219
            $row = array_values($row);
220
            $sql = $row[1];
221
        }
222
        $sql = preg_replace('/^[^(]+\((.*)\).*$/', '\1', $sql);
223
        $sql = str_replace(', [', ",\n[", $sql);
224
        if (preg_match_all('/^\s*\[(.*?)\]\s+(.*?),?$/m', $sql, $matches)) {
225
            foreach ($matches[1] as $i => $c) {
226
                if ($c === $column) {
227
                    return $matches[2][$i];
228
                }
229
            }
230
        }
231
        return null;
232
    }
233
}
234