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

Schema::loadTableSchema()   C

Complexity

Conditions 7
Paths 19

Size

Total Lines 45
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
dl 0
loc 45
ccs 0
cts 37
cp 0
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 28
nc 19
nop 1
crap 56
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\NotSupportedException;
11
use yii\db\Constraint;
12
use yii\db\ConstraintFinderTrait;
13
use yii\db\Expression;
14
use yii\db\ForeignKeyConstraint;
15
use yii\db\IndexConstraint;
16
use yii\db\TableSchema;
17
use yii\db\Transaction;
18
use yii\helpers\ArrayHelper;
19
20
/**
21
 * Schema is the class for retrieving metadata from a CUBRID database (version 9.3.x and higher).
22
 *
23
 * @author Carsten Brandt <[email protected]>
24
 * @since 2.0
25
 */
26
class Schema extends \yii\db\Schema
27
{
28
    use ConstraintFinderTrait;
29
30
    /**
31
     * @var array mapping from physical column types (keys) to abstract column types (values)
32
     * Please refer to [CUBRID manual](http://www.cubrid.org/manual/91/en/sql/datatype.html) for
33
     * details on data types.
34
     */
35
    public $typeMap = [
36
        // Numeric data types
37
        'short' => self::TYPE_SMALLINT,
38
        'smallint' => self::TYPE_SMALLINT,
39
        'int' => self::TYPE_INTEGER,
40
        'integer' => self::TYPE_INTEGER,
41
        'bigint' => self::TYPE_BIGINT,
42
        'numeric' => self::TYPE_DECIMAL,
43
        'decimal' => self::TYPE_DECIMAL,
44
        'float' => self::TYPE_FLOAT,
45
        'real' => self::TYPE_FLOAT,
46
        'double' => self::TYPE_DOUBLE,
47
        'double precision' => self::TYPE_DOUBLE,
48
        'monetary' => self::TYPE_MONEY,
49
        // Date/Time data types
50
        'date' => self::TYPE_DATE,
51
        'time' => self::TYPE_TIME,
52
        'timestamp' => self::TYPE_TIMESTAMP,
53
        'datetime' => self::TYPE_DATETIME,
54
        // String data types
55
        'char' => self::TYPE_CHAR,
56
        'varchar' => self::TYPE_STRING,
57
        'char varying' => self::TYPE_STRING,
58
        'nchar' => self::TYPE_CHAR,
59
        'nchar varying' => self::TYPE_STRING,
60
        'string' => self::TYPE_STRING,
61
        // BLOB/CLOB data types
62
        'blob' => self::TYPE_BINARY,
63
        'clob' => self::TYPE_BINARY,
64
        // Bit string data types
65
        'bit' => self::TYPE_INTEGER,
66
        'bit varying' => self::TYPE_INTEGER,
67
        // Collection data types (considered strings for now)
68
        'set' => self::TYPE_STRING,
69
        'multiset' => self::TYPE_STRING,
70
        'list' => self::TYPE_STRING,
71
        'sequence' => self::TYPE_STRING,
72
        'enum' => self::TYPE_STRING,
73
    ];
74
    /**
75
     * @var array map of DB errors and corresponding exceptions
76
     * If left part is found in DB error message exception class from the right part is used.
77
     */
78
    public $exceptionMap = [
79
        'Operation would have caused one or more unique constraint violations' => 'yii\db\IntegrityException',
80
    ];
81
82
83
    /**
84
     * @inheritDoc
85
     */
86
    protected function findTableNames($schema = '')
87
    {
88
        $pdo = $this->db->getSlavePdo();
89
        $tables = $pdo->cubrid_schema(\PDO::CUBRID_SCH_TABLE);
90
        $tableNames = [];
91
        foreach ($tables as $table) {
92
            // do not list system tables
93
            if ($table['TYPE'] != 0) {
94
                $tableNames[] = $table['NAME'];
95
            }
96
        }
97
98
        return $tableNames;
99
    }
100
101
    /**
102
     * @inheritDoc
103
     */
104
    protected function loadTableSchema($name)
105
    {
106
        $pdo = $this->db->getSlavePdo();
107
108
        $tableInfo = $pdo->cubrid_schema(\PDO::CUBRID_SCH_TABLE, $name);
109
110
        if (!isset($tableInfo[0]['NAME'])) {
111
            return null;
112
        }
113
114
        $table = new TableSchema();
115
        $table->fullName = $table->name = $tableInfo[0]['NAME'];
116
117
        $sql = 'SHOW FULL COLUMNS FROM ' . $this->quoteSimpleTableName($table->name);
118
        $columns = $this->db->createCommand($sql)->queryAll();
119
120
        foreach ($columns as $info) {
121
            $column = $this->loadColumnSchema($info);
122
            $table->columns[$column->name] = $column;
123
        }
124
125
        $primaryKeys = $pdo->cubrid_schema(\PDO::CUBRID_SCH_PRIMARY_KEY, $table->name);
126
        foreach ($primaryKeys as $key) {
127
            $column = $table->columns[$key['ATTR_NAME']];
128
            $column->isPrimaryKey = true;
129
            $table->primaryKey[] = $column->name;
130
            if ($column->autoIncrement) {
131
                $table->sequenceName = '';
132
            }
133
        }
134
135
        $foreignKeys = $pdo->cubrid_schema(\PDO::CUBRID_SCH_IMPORTED_KEYS, $table->name);
136
        foreach ($foreignKeys as $key) {
137
            if (isset($table->foreignKeys[$key['FK_NAME']])) {
138
                $table->foreignKeys[$key['FK_NAME']][$key['FKCOLUMN_NAME']] = $key['PKCOLUMN_NAME'];
139
            } else {
140
                $table->foreignKeys[$key['FK_NAME']] = [
141
                    $key['PKTABLE_NAME'],
142
                    $key['FKCOLUMN_NAME'] => $key['PKCOLUMN_NAME'],
143
                ];
144
            }
145
        }
146
147
        return $table;
148
    }
149
150
    /**
151
     * @inheritDoc
152
     */
153
    protected function loadTablePrimaryKey($tableName)
154
    {
155
        $primaryKey = $this->db->getSlavePdo()->cubrid_schema(\PDO::CUBRID_SCH_PRIMARY_KEY, $tableName);
156
        if (empty($primaryKey)) {
157
            return null;
158
        }
159
160
        ArrayHelper::multisort($primaryKey, 'KEY_SEQ', SORT_ASC, SORT_NUMERIC);
161
        return new Constraint([
162
            'name' => $primaryKey[0]['KEY_NAME'],
163
            'columnNames' => ArrayHelper::getColumn($primaryKey, 'ATTR_NAME'),
164
        ]);
165
    }
166
167
    /**
168
     * @inheritDoc
169
     */
170
    protected function loadTableForeignKeys($tableName)
171
    {
172
        static $actionTypes = [
173
            0 => 'CASCADE',
174
            1 => 'RESTRICT',
175
            2 => 'NO ACTION',
176
            3 => 'SET NULL',
177
        ];
178
179
        $foreignKeys = $this->db->getSlavePdo()->cubrid_schema(\PDO::CUBRID_SCH_IMPORTED_KEYS, $tableName);
180
        $foreignKeys = ArrayHelper::index($foreignKeys, null, 'FK_NAME');
181
        ArrayHelper::multisort($foreignKeys, 'KEY_SEQ', SORT_ASC, SORT_NUMERIC);
182
        $result = [];
183
        foreach ($foreignKeys as $name => $foreignKey) {
184
            $result[] = new ForeignKeyConstraint([
185
                'name' => $name,
186
                'columnNames' => ArrayHelper::getColumn($foreignKey, 'FKCOLUMN_NAME'),
187
                'foreignTableName' => $foreignKey[0]['PKTABLE_NAME'],
188
                'foreignColumnNames' => ArrayHelper::getColumn($foreignKey, 'PKCOLUMN_NAME'),
189
                'onDelete' => isset($actionTypes[$foreignKey[0]['DELETE_RULE']]) ? $actionTypes[$foreignKey[0]['DELETE_RULE']] : null,
190
                'onUpdate' => isset($actionTypes[$foreignKey[0]['UPDATE_RULE']]) ? $actionTypes[$foreignKey[0]['UPDATE_RULE']] : null,
191
            ]);
192
        }
193
        return $result;
194
    }
195
196
    /**
197
     * @inheritDoc
198
     */
199
    protected function loadTableIndexes($tableName)
200
    {
201
        return $this->loadTableConstraints($tableName, 'indexes');
202
    }
203
204
    /**
205
     * @inheritDoc
206
     */
207
    protected function loadTableUniques($tableName)
208
    {
209
        return $this->loadTableConstraints($tableName, 'uniques');
210
    }
211
212
    /**
213
     * @inheritDoc
214
     * @throws NotSupportedException if this method is called.
215
     */
216
    protected function loadTableChecks($tableName)
0 ignored issues
show
Unused Code introduced by
The parameter $tableName is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
217
    {
218
        throw new NotSupportedException('CUBRID does not support check constraints.');
219
    }
220
221
    /**
222
     * @inheritDoc
223
     * @throws NotSupportedException if this method is called.
224
     */
225
    protected function loadTableDefaultValues($tableName)
0 ignored issues
show
Unused Code introduced by
The parameter $tableName is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
226
    {
227
        throw new NotSupportedException('CUBRID does not support default value constraints.');
228
    }
229
230
    /**
231
     * @inheritdoc
232
     */
233
    public function releaseSavepoint($name)
234
    {
235
        // does nothing as cubrid does not support this
236
    }
237
238
    /**
239
     * Quotes a table name for use in a query.
240
     * A simple table name has no schema prefix.
241
     * @param string $name table name
242
     * @return string the properly quoted table name
243
     */
244
    public function quoteSimpleTableName($name)
245
    {
246
        return strpos($name, '"') !== false ? $name : '"' . $name . '"';
247
    }
248
249
    /**
250
     * Quotes a column name for use in a query.
251
     * A simple column name has no prefix.
252
     * @param string $name column name
253
     * @return string the properly quoted column name
254
     */
255
    public function quoteSimpleColumnName($name)
256
    {
257
        return strpos($name, '"') !== false || $name === '*' ? $name : '"' . $name . '"';
258
    }
259
260
    /**
261
     * Creates a query builder for the CUBRID database.
262
     * @return QueryBuilder query builder instance
263
     */
264
    public function createQueryBuilder()
265
    {
266
        return new QueryBuilder($this->db);
267
    }
268
269
    /**
270
     * Loads the column information into a [[ColumnSchema]] object.
271
     * @param array $info column information
272
     * @return \yii\db\ColumnSchema the column schema object
273
     */
274
    protected function loadColumnSchema($info)
275
    {
276
        $column = $this->createColumnSchema();
277
278
        $column->name = $info['Field'];
279
        $column->allowNull = $info['Null'] === 'YES';
280
        $column->isPrimaryKey = false; // primary key will be set by loadTableSchema() later
281
        $column->autoIncrement = stripos($info['Extra'], 'auto_increment') !== false;
282
283
        $column->dbType = $info['Type'];
284
        $column->unsigned = strpos($column->dbType, 'unsigned') !== false;
285
286
        $column->type = self::TYPE_STRING;
287
        if (preg_match('/^([\w ]+)(?:\(([^\)]+)\))?$/', $column->dbType, $matches)) {
288
            $type = strtolower($matches[1]);
289
            $column->dbType = $type . (isset($matches[2]) ? "({$matches[2]})" : '');
290
            if (isset($this->typeMap[$type])) {
291
                $column->type = $this->typeMap[$type];
292
            }
293
            if (!empty($matches[2])) {
294
                if ($type === 'enum') {
295
                    $values = preg_split('/\s*,\s*/', $matches[2]);
296
                    foreach ($values as $i => $value) {
297
                        $values[$i] = trim($value, "'");
298
                    }
299
                    $column->enumValues = $values;
300
                } else {
301
                    $values = explode(',', $matches[2]);
302
                    $column->size = $column->precision = (int) $values[0];
303
                    if (isset($values[1])) {
304
                        $column->scale = (int) $values[1];
305
                    }
306
                    if ($column->size === 1 && $type === 'bit') {
307
                        $column->type = 'boolean';
308
                    } elseif ($type === 'bit') {
309
                        if ($column->size > 32) {
310
                            $column->type = 'bigint';
311
                        } elseif ($column->size === 32) {
312
                            $column->type = 'integer';
313
                        }
314
                    }
315
                }
316
            }
317
        }
318
319
        $column->phpType = $this->getColumnPhpType($column);
320
321
        if ($column->isPrimaryKey) {
322
            return $column;
323
        }
324
325
        if ($column->type === 'timestamp' && $info['Default'] === 'SYS_TIMESTAMP' ||
326
            $column->type === 'datetime' && $info['Default'] === 'SYS_DATETIME' ||
327
            $column->type === 'date' && $info['Default'] === 'SYS_DATE' ||
328
            $column->type === 'time' && $info['Default'] === 'SYS_TIME'
329
        ) {
330
            $column->defaultValue = new Expression($info['Default']);
331
        } elseif (isset($type) && $type === 'bit') {
332
            $column->defaultValue = hexdec(trim($info['Default'], 'X\''));
333
        } else {
334
            $column->defaultValue = $column->phpTypecast($info['Default']);
335
        }
336
337
        return $column;
338
    }
339
340
    /**
341
     * Determines the PDO type for the given PHP data value.
342
     * @param mixed $data the data whose PDO type is to be determined
343
     * @return int the PDO type
344
     * @see http://www.php.net/manual/en/pdo.constants.php
345
     */
346
    public function getPdoType($data)
347
    {
348
        static $typeMap = [
349
            // php type => PDO type
350
            'boolean' => \PDO::PARAM_INT, // PARAM_BOOL is not supported by CUBRID PDO
351
            'integer' => \PDO::PARAM_INT,
352
            'string' => \PDO::PARAM_STR,
353
            'resource' => \PDO::PARAM_LOB,
354
            'NULL' => \PDO::PARAM_NULL,
355
        ];
356
        $type = gettype($data);
357
358
        return isset($typeMap[$type]) ? $typeMap[$type] : \PDO::PARAM_STR;
359
    }
360
361
    /**
362
     * @inheritdoc
363
     * @see http://www.cubrid.org/manual/91/en/sql/transaction.html#database-concurrency
364
     */
365
    public function setTransactionIsolationLevel($level)
366
    {
367
        // translate SQL92 levels to CUBRID levels:
368
        switch ($level) {
369
            case Transaction::SERIALIZABLE:
370
                $level = '6'; // SERIALIZABLE
371
                break;
372
            case Transaction::REPEATABLE_READ:
373
                $level = '5'; // REPEATABLE READ CLASS with REPEATABLE READ INSTANCES
374
                break;
375
            case Transaction::READ_COMMITTED:
376
                $level = '4'; // REPEATABLE READ CLASS with READ COMMITTED INSTANCES
377
                break;
378
            case Transaction::READ_UNCOMMITTED:
379
                $level = '3'; // REPEATABLE READ CLASS with READ UNCOMMITTED INSTANCES
380
                break;
381
        }
382
        parent::setTransactionIsolationLevel($level);
383
    }
384
385
    /**
386
     * @inheritdoc
387
     */
388
    public function createColumnSchemaBuilder($type, $length = null)
389
    {
390
        return new ColumnSchemaBuilder($type, $length, $this->db);
391
    }
392
393
    /**
394
     * Loads multiple types of constraints and returns the specified ones.
395
     * @param string $tableName table name.
396
     * @param string $returnType return type:
397
     * - indexes
398
     * - uniques
399
     * @return mixed constraints.
400
     */
401
    private function loadTableConstraints($tableName, $returnType)
402
    {
403
        $constraints = $this->db->getSlavePdo()->cubrid_schema(\PDO::CUBRID_SCH_CONSTRAINT, $tableName);
404
        $constraints = ArrayHelper::index($constraints, null, ['TYPE', 'NAME']);
405
        ArrayHelper::multisort($constraints, 'KEY_ORDER', SORT_ASC, SORT_NUMERIC);
406
        $result = [
407
            'indexes' => [],
408
            'uniques' => [],
409
        ];
410
        foreach ($constraints as $type => $names) {
411
            foreach ($names as $name => $constraint) {
412
                $isUnique = in_array((int) $type, [0, 2], true);
413
                $result['indexes'][] = new IndexConstraint([
414
                    'isPrimary' => (bool) $constraint[0]['PRIMARY_KEY'],
415
                    'isUnique' => $isUnique,
416
                    'name' => $name,
417
                    'columnNames' => ArrayHelper::getColumn($constraint, 'ATTR_NAME'),
418
                ]);
419
                if ($isUnique) {
420
                    $result['uniques'][] = new Constraint([
421
                        'name' => $name,
422
                        'columnNames' => ArrayHelper::getColumn($constraint, 'ATTR_NAME'),
423
                    ]);
424
                }
425
            }
426
        }
427
        foreach ($result as $type => $data) {
428
            $this->setTableMetadata($tableName, $type, $data);
429
        }
430
        return $result[$returnType];
431
    }
432
}
433