forked from keygenqt/Vertica
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSchema.php
661 lines (607 loc) · 22.5 KB
/
Schema.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\vertica;
use Yii;
use yii\base\Object;
use yii\base\NotSupportedException;
use yii\base\InvalidCallException;
use yii\caching\Cache;
use yii\caching\TagDependency;
/**
* Schema is the base class for concrete DBMS-specific schema classes.
*
* Schema represents the database schema information that is DBMS specific.
*
* @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the
* sequence object. This property is read-only.
* @property QueryBuilder $queryBuilder The query builder for this connection. This property is read-only.
* @property string[] $tableNames All table names in the database. This property is read-only.
* @property TableSchema[] $tableSchemas The metadata for all tables in the database. Each array element is an
* instance of [[TableSchema]] or its child class. This property is read-only.
* @property string $transactionIsolationLevel The transaction isolation level to use for this transaction.
* This can be one of [[Transaction::READ_UNCOMMITTED]], [[Transaction::READ_COMMITTED]],
* [[Transaction::REPEATABLE_READ]] and [[Transaction::SERIALIZABLE]] but also a string containing DBMS specific
* syntax to be used after `SET TRANSACTION ISOLATION LEVEL`. This property is write-only.
*
* @author Qiang Xue <[email protected]>
* @since 2.0
*/
abstract class Schema extends Object
{
/**
* The followings are the supported abstract column data types.
*/
/**
* @var string AUTO_INCREMENT
*/
const TYPE_PK = 'AUTO_INCREMENT NOT NULL PRIMARY KEY';
// Binary types
/**
* @var string 1 to 65000 Fixed-length binary string NULLS LAST
*/
const TYPE_BINARY = 'BINARY';
/**
* @var string 1 to 65000 Variable-length binary string NULLS LAST
*/
const TYPE_VARBINARY = 'VARBINARY';
/**
* @var string 1 to 65000 Variable-length binary string (synonym for VARBINARY) NULLS LAST
*/
const TYPE_BYTEA = 'BYTEA';
/**
* @var string 1 to 65000 Variable-length binary string (synonym for VARBINARY) NULLS LAST
*/
const TYPE_RAW = 'RAW';
// Boolean types
/**
* @var string 1 True or False or NULL NULLS LAST
*/
const TYPE_BOOLEAN = 'BOOLEAN';
// Character types
/**
* @var string 1 to 65000 Fixed-length character string NULLS LAST
*/
const TYPE_CHAR = 'CHAR';
/**
* @var string 1 to 65000 Variable-length character string NULLS LAST
*/
const TYPE_VARCHAR = 'VARCHAR';
// Date/time types
/**
* @var string 8 Represents a month, day, and year NULLS FIRST
*/
const TYPE_DATE = 'DATE';
/**
* @var string 8 Represents a date and time with or without timezone (synonym for TIMESTAMP) NULLS FIRST
*/
const TYPE_DATETIME = 'DATETIME';
/**
* @var string 8 Represents a date and time with or without timezone (synonym for TIMESTAMP) NULLS FIRST
*/
const TYPE_SMALLDATETIME = 'SMALLDATETIME';
/**
* @var string 8 Represents a time of day without timezone NULLS FIRST
*/
const TYPE_TIME = 'TIME';
/**
* @var string null
*/
const TYPE_TIMEZONE = 'TIMEZONE';
/**
* @var string 8 Represents a date and time without timezone NULLS FIRST
*/
const TYPE_TIMESTAMP = 'TIMESTAMP';
/**
* @var string 8 Represents a date and time with timezone NULLS FIRST
*/
const TYPE_TIMESTAMP_WITH = 'TIMESTAMP WITH';
/**
* @var string 8 Measures the difference between two points in time NULLS FIRST
*/
const TYPE_INTERVAL = 'INTERVAL';
// Approximate numeric types
/**
* @var string 8 Signed 64-bit IEEE floating point number, requiring 8 bytes of storage NULLS LAST
*/
const TYPE_DOUBLE_PRECISION = 'DOUBLE PRECISION';
/**
* @var string 8 Signed 64-bit IEEE floating point number, requiring 8 bytes of storage NULLS LAST
*/
const TYPE_FLOAT = 'FLOAT';
/**
* @var string 8 Signed 64-bit IEEE floating point number, requiring 8 bytes of storage NULLS LAST
*/
const TYPE_FLOAT8 = 'FLOAT8';
/**
* @var string 8 Signed 64-bit IEEE floating point number, requiring 8 bytes of storage NULLS LAST
*/
const TYPE_REAL = 'REAL';
// Exact numeric types
/**
* @var string 8 Signed 64-bit integer, requiring 8 bytes of storage NULLS FIRST
*/
const TYPE_INTEGER = 'INTEGER';
/**
* @var string 8 Signed 64-bit integer, requiring 8 bytes of storage NULLS FIRST
*/
const TYPE_INT = 'INT';
/**
* @var string 8 Signed 64-bit integer, requiring 8 bytes of storage NULLS FIRST
*/
const TYPE_BIGINT = 'BIGINT';
/**
* @var string 8 Signed 64-bit integer, requiring 8 bytes of storage NULLS FIRST
*/
const TYPE_INT8 = 'INT8';
/**
* @var string 8 Signed 64-bit integer, requiring 8 bytes of storage NULLS FIRST
*/
const TYPE_SMALLINT = 'SMALLINT';
/**
* @var string 8 Signed 64-bit integer, requiring 8 bytes of storage NULLS FIRST
*/
const TYPE_TINYINT = 'TINYINT';
/**
* @var string 8+ 8 bytes for the first 18 digits of precision, plus 8 bytes for each additional 19 digits NULLS FIRST
*/
const TYPE_DECIMAL = 'DECIMAL';
/**
* @var string 8+ 8 bytes for the first 18 digits of precision, plus 8 bytes for each additional 19 digits NULLS FIRST
*/
const TYPE_NUMERIC = 'NUMERIC';
/**
* @var string 8+ 8 bytes for the first 18 digits of precision, plus 8 bytes for each additional 19 digits NULLS FIRST
*/
const TYPE_NUMBER = 'NUMBER';
/**
* @var string 8+ 8 bytes for the first 18 digits of precision, plus 8 bytes for each additional 19 digits NULLS FIRST
*/
const TYPE_MONEY = 'MONEY';
/**
* @var Connection the database connection
*/
public $db;
/**
* @var string the default schema name used for the current session.
*/
public $defaultSchema;
/**
* @var array map of DB errors and corresponding exceptions
* If left part is found in DB error message exception class from the right part is used.
*/
public $exceptionMap = [
'SQLSTATE[23' => 'yii\db\IntegrityException',
];
/**
* @var array list of ALL table names in the database
*/
private $_tableNames = [];
/**
* @var array list of loaded table metadata (table name => TableSchema)
*/
private $_tables = [];
/**
* @var QueryBuilder the query builder for this database
*/
private $_builder;
/**
* @return \yii\db\ColumnSchema
* @throws \yii\base\InvalidConfigException
*/
protected function createColumnSchema()
{
return Yii::createObject('yii\db\ColumnSchema');
}
/**
* Loads the metadata for the specified table.
* @param string $name table name
* @return TableSchema DBMS-dependent table metadata, null if the table does not exist.
*/
abstract protected function loadTableSchema($name);
/**
* Obtains the metadata for the named table.
* @param string $name table name. The table name may contain schema name if any. Do not quote the table name.
* @param boolean $refresh whether to reload the table schema even if it is found in the cache.
* @return TableSchema table metadata. Null if the named table does not exist.
*/
public function getTableSchema($name, $refresh = false)
{
if (array_key_exists($name, $this->_tables) && !$refresh) {
return $this->_tables[$name];
}
$db = $this->db;
$realName = $this->getRawTableName($name);
if ($db->enableSchemaCache && !in_array($name, $db->schemaCacheExclude, true)) {
/* @var $cache Cache */
$cache = is_string($db->schemaCache) ? Yii::$app->get($db->schemaCache, false) : $db->schemaCache;
if ($cache instanceof Cache) {
$key = $this->getCacheKey($name);
if ($refresh || ($table = $cache->get($key)) === false) {
$this->_tables[$name] = $table = $this->loadTableSchema($realName);
if ($table !== null) {
$cache->set($key, $table, $db->schemaCacheDuration, new TagDependency([
'tags' => $this->getCacheTag(),
]));
}
} else {
$this->_tables[$name] = $table;
}
return $this->_tables[$name];
}
}
return $this->_tables[$name] = $this->loadTableSchema($realName);
}
/**
* Returns the cache key for the specified table name.
* @param string $name the table name
* @return mixed the cache key
*/
protected function getCacheKey($name)
{
return [
__CLASS__,
$this->db->dsn,
$this->db->username,
$name,
];
}
/**
* Returns the cache tag name.
* This allows [[refresh()]] to invalidate all cached table schemas.
* @return string the cache tag name
*/
protected function getCacheTag()
{
return md5(serialize([
__CLASS__,
$this->db->dsn,
$this->db->username,
]));
}
/**
* Returns the metadata for all tables in the database.
* @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema name.
* @param boolean $refresh whether to fetch the latest available table schemas. If this is false,
* cached data may be returned if available.
* @return TableSchema[] the metadata for all tables in the database.
* Each array element is an instance of [[TableSchema]] or its child class.
*/
public function getTableSchemas($schema = '', $refresh = false)
{
$tables = [];
foreach ($this->getTableNames($schema, $refresh) as $name) {
if ($schema !== '') {
$name = $schema . '.' . $name;
}
if (($table = $this->getTableSchema($name, $refresh)) !== null) {
$tables[] = $table;
}
}
return $tables;
}
/**
* Returns all table names in the database.
* @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema name.
* If not empty, the returned table names will be prefixed with the schema name.
* @param boolean $refresh whether to fetch the latest available table names. If this is false,
* table names fetched previously (if available) will be returned.
* @return string[] all table names in the database.
*/
public function getTableNames($schema = '', $refresh = false)
{
if (!isset($this->_tableNames[$schema]) || $refresh) {
$this->_tableNames[$schema] = $this->findTableNames($schema);
}
return $this->_tableNames[$schema];
}
/**
* @return QueryBuilder the query builder for this connection.
*/
public function getQueryBuilder()
{
if ($this->_builder === null) {
$this->_builder = $this->createQueryBuilder();
}
return $this->_builder;
}
/**
* Determines the PDO type for the given PHP data value.
* @param mixed $data the data whose PDO type is to be determined
* @return integer the PDO type
* @see http://www.php.net/manual/en/pdo.constants.php
*/
public function getPdoType($data)
{
static $typeMap = [
// php type => PDO type
'boolean' => \PDO::PARAM_BOOL,
'integer' => \PDO::PARAM_INT,
'string' => \PDO::PARAM_STR,
'resource' => \PDO::PARAM_LOB,
'NULL' => \PDO::PARAM_NULL,
];
$type = gettype($data);
return isset($typeMap[$type]) ? $typeMap[$type] : \PDO::PARAM_STR;
}
/**
* Refreshes the schema.
* This method cleans up all cached table schemas so that they can be re-created later
* to reflect the database schema change.
*/
public function refresh()
{
/* @var $cache Cache */
$cache = is_string($this->db->schemaCache) ? Yii::$app->get($this->db->schemaCache, false) : $this->db->schemaCache;
if ($this->db->enableSchemaCache && $cache instanceof Cache) {
TagDependency::invalidate($cache, $this->getCacheTag());
}
$this->_tableNames = [];
$this->_tables = [];
}
/**
* Creates a query builder for the database.
* This method may be overridden by child classes to create a DBMS-specific query builder.
* @return QueryBuilder query builder instance
*/
public function createQueryBuilder()
{
return new QueryBuilder($this->db);
}
/**
* Returns all table names in the database.
* This method should be overridden by child classes in order to support this feature
* because the default implementation simply throws an exception.
* @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
* @return array all table names in the database. The names have NO schema name prefix.
* @throws NotSupportedException if this method is called
*/
protected function findTableNames($schema = '')
{
throw new NotSupportedException(get_class($this) . ' does not support fetching all table names.');
}
/**
* Returns all unique indexes for the given table.
* Each array element is of the following structure:
*
* ~~~
* [
* 'IndexName1' => ['col1' [, ...]],
* 'IndexName2' => ['col2' [, ...]],
* ]
* ~~~
*
* This method should be overridden by child classes in order to support this feature
* because the default implementation simply throws an exception
* @param TableSchema $table the table metadata
* @return array all unique indexes for the given table.
* @throws NotSupportedException if this method is called
*/
public function findUniqueIndexes($table)
{
throw new NotSupportedException(get_class($this) . ' does not support getting unique indexes information.');
}
/**
* Returns the ID of the last inserted row or sequence value.
* @param string $sequenceName name of the sequence object (required by some DBMS)
* @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
* @throws InvalidCallException if the DB connection is not active
* @see http://www.php.net/manual/en/function.PDO-lastInsertId.php
*/
public function getLastInsertID($sequenceName = '')
{
if ($this->db->isActive) {
return $this->db->pdo->lastInsertId($sequenceName);
} else {
throw new InvalidCallException('DB Connection is not active.');
}
}
/**
* @return boolean whether this DBMS supports [savepoint](http://en.wikipedia.org/wiki/Savepoint).
*/
public function supportsSavepoint()
{
return $this->db->enableSavepoint;
}
/**
* Creates a new savepoint.
* @param string $name the savepoint name
*/
public function createSavepoint($name)
{
$this->db->createCommand("SAVEPOINT $name")->execute();
}
/**
* Releases an existing savepoint.
* @param string $name the savepoint name
*/
public function releaseSavepoint($name)
{
$this->db->createCommand("RELEASE SAVEPOINT $name")->execute();
}
/**
* Rolls back to a previously created savepoint.
* @param string $name the savepoint name
*/
public function rollBackSavepoint($name)
{
$this->db->createCommand("ROLLBACK TO SAVEPOINT $name")->execute();
}
/**
* Sets the isolation level of the current transaction.
* @param string $level The transaction isolation level to use for this transaction.
* This can be one of [[Transaction::READ_UNCOMMITTED]], [[Transaction::READ_COMMITTED]], [[Transaction::REPEATABLE_READ]]
* and [[Transaction::SERIALIZABLE]] but also a string containing DBMS specific syntax to be used
* after `SET TRANSACTION ISOLATION LEVEL`.
* @see http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels
*/
public function setTransactionIsolationLevel($level)
{
$this->db->createCommand("SET TRANSACTION ISOLATION LEVEL $level;")->execute();
}
/**
* Quotes a string value for use in a query.
* Note that if the parameter is not a string, it will be returned without change.
* @param string $str string to be quoted
* @return string the properly quoted string
* @see http://www.php.net/manual/en/function.PDO-quote.php
*/
public function quoteValue($str)
{
if (!is_string($str)) {
return $str;
}
if (($value = $this->db->getSlavePdo()->quote($str)) !== false) {
return $value;
} else {
// the driver doesn't support quote (e.g. oci)
return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
}
}
/**
* Quotes a table name for use in a query.
* If the table name contains schema prefix, the prefix will also be properly quoted.
* If the table name is already quoted or contains '(' or '{{',
* then this method will do nothing.
* @param string $name table name
* @return string the properly quoted table name
* @see quoteSimpleTableName()
*/
public function quoteTableName($name)
{
if (strpos($name, '(') !== false || strpos($name, '{{') !== false) {
return $name;
}
if (strpos($name, '.') === false) {
return $this->quoteSimpleTableName($name);
}
$parts = explode('.', $name);
foreach ($parts as $i => $part) {
$parts[$i] = $this->quoteSimpleTableName($part);
}
return implode('.', $parts);
}
/**
* Quotes a column name for use in a query.
* If the column name contains prefix, the prefix will also be properly quoted.
* If the column name is already quoted or contains '(', '[[' or '{{',
* then this method will do nothing.
* @param string $name column name
* @return string the properly quoted column name
* @see quoteSimpleColumnName()
*/
public function quoteColumnName($name)
{
if (strpos($name, '(') !== false || strpos($name, '[[') !== false || strpos($name, '{{') !== false) {
return $name;
}
if (($pos = strrpos($name, '.')) !== false) {
$prefix = $this->quoteTableName(substr($name, 0, $pos)) . '.';
$name = substr($name, $pos + 1);
} else {
$prefix = '';
}
return $prefix . $this->quoteSimpleColumnName($name);
}
/**
* Quotes a simple table name for use in a query.
* A simple table name should contain the table name only without any schema prefix.
* If the table name is already quoted, this method will do nothing.
* @param string $name table name
* @return string the properly quoted table name
*/
public function quoteSimpleTableName($name)
{
return strpos($name, "'") !== false ? $name : "'" . $name . "'";
}
/**
* Quotes a simple column name for use in a query.
* A simple column name should contain the column name only without any prefix.
* If the column name is already quoted or is the asterisk character '*', this method will do nothing.
* @param string $name column name
* @return string the properly quoted column name
*/
public function quoteSimpleColumnName($name)
{
return strpos($name, '"') !== false || $name === '*' ? $name : '"' . $name . '"';
}
/**
* Returns the actual name of a given table name.
* This method will strip off curly brackets from the given table name
* and replace the percentage character '%' with [[Connection::tablePrefix]].
* @param string $name the table name to be converted
* @return string the real name of the given table name
*/
public function getRawTableName($name)
{
if (strpos($name, '{{') !== false) {
$name = preg_replace('/\\{\\{(.*?)\\}\\}/', '\1', $name);
return str_replace('%', $this->db->tablePrefix, $name);
} else {
return $name;
}
}
/**
* Extracts the PHP type from abstract DB type.
* @param ColumnSchema $column the column schema information
* @return string PHP type name
*/
protected function getColumnPhpType($column)
{
static $typeMap = [
// abstract type => php type
'smallint' => 'integer',
'integer' => 'integer',
'bigint' => 'integer',
'boolean' => 'boolean',
'float' => 'double',
'binary' => 'resource',
];
if (isset($typeMap[$column->type])) {
if ($column->type === 'bigint') {
return PHP_INT_SIZE == 8 && !$column->unsigned ? 'integer' : 'string';
} elseif ($column->type === 'integer') {
return PHP_INT_SIZE == 4 && $column->unsigned ? 'string' : 'integer';
} else {
return $typeMap[$column->type];
}
} else {
return 'string';
}
}
/**
* Converts a DB exception to a more concrete one if possible.
*
* @param \Exception $e
* @param string $rawSql SQL that produced exception
* @return Exception
*/
public function convertException(\Exception $e, $rawSql)
{
if ($e instanceof Exception) {
return $e;
}
$exceptionClass = '\yii\db\Exception';
foreach ($this->exceptionMap as $error => $class) {
if (strpos($e->getMessage(), $error) !== false) {
$exceptionClass = $class;
}
}
$message = $e->getMessage() . "\nThe SQL being executed was: $rawSql";
$errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
return new $exceptionClass($message, $errorInfo, (int) $e->getCode(), $e);
}
/**
* Returns a value indicating whether a SQL statement is for read purpose.
* @param string $sql the SQL statement
* @return boolean whether a SQL statement is for read purpose.
*/
public function isReadQuery($sql)
{
$pattern = '/^\s*(SELECT|SHOW|DESCRIBE)\b/i';
return preg_match($pattern, $sql) > 0;
}
}