/
PostgresSchema.php
492 lines (455 loc) · 13.3 KB
/
PostgresSchema.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
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\Database\Schema;
use Cake\Database\Exception;
use Cake\Database\Schema\Table;
/**
* Schema management/reflection features for Postgres.
*/
class PostgresSchema extends BaseSchema {
/**
* {@inheritDoc}
*/
public function listTablesSql($config) {
$sql = 'SELECT table_name as name FROM information_schema.tables WHERE table_schema = ? ORDER BY name';
$schema = empty($config['schema']) ? 'public' : $config['schema'];
return [$sql, [$schema]];
}
/**
* {@inheritDoc}
*/
public function describeColumnSql($tableName, $config) {
$sql =
'SELECT DISTINCT table_schema AS schema, column_name AS name, data_type AS type,
is_nullable AS null, column_default AS default,
character_maximum_length AS char_length,
d.description as comment,
ordinal_position
FROM information_schema.columns c
INNER JOIN pg_catalog.pg_namespace ns ON (ns.nspname = table_schema)
INNER JOIN pg_catalog.pg_class cl ON (cl.relnamespace = ns.oid AND cl.relname = table_name)
LEFT JOIN pg_catalog.pg_index i ON (i.indrelid = cl.oid AND i.indkey[0] = c.ordinal_position)
LEFT JOIN pg_catalog.pg_description d on (cl.oid = d.objoid AND d.objsubid = c.ordinal_position)
WHERE table_name = ? AND table_schema = ? AND table_catalog = ?
ORDER BY ordinal_position';
$schema = empty($config['schema']) ? 'public' : $config['schema'];
return [$sql, [$tableName, $schema, $config['database']]];
}
/**
* Convert a column definition to the abstract types.
*
* The returned type will be a type that
* Cake\Database\Type can handle.
*
* @param string $column The column type + length
* @throws \Cake\Database\Exception when column cannot be parsed.
* @return array Array of column information.
*/
protected function _convertColumn($column) {
preg_match('/([a-z\s]+)(?:\(([0-9,]+)\))?/i', $column, $matches);
if (empty($matches)) {
throw new Exception(sprintf('Unable to parse column type from "%s"', $column));
}
$col = strtolower($matches[1]);
$length = null;
if (isset($matches[2])) {
$length = (int)$matches[2];
}
if (in_array($col, array('date', 'time', 'boolean'))) {
return ['type' => $col, 'length' => null];
}
if (strpos($col, 'timestamp') !== false) {
return ['type' => 'timestamp', 'length' => null];
}
if ($col === 'serial' || $col === 'integer') {
return ['type' => 'integer', 'length' => 10];
}
if ($col === 'bigserial' || $col === 'bigint') {
return ['type' => 'biginteger', 'length' => 20];
}
if ($col === 'smallint') {
return ['type' => 'integer', 'length' => 5];
}
if ($col === 'inet') {
return ['type' => 'string', 'length' => 39];
}
if ($col === 'uuid') {
return ['type' => 'uuid', 'length' => null];
}
if ($col === 'char' || $col === 'character') {
return ['type' => 'string', 'fixed' => true, 'length' => $length];
}
if (strpos($col, 'char') !== false) {
return ['type' => 'string', 'length' => $length];
}
if (strpos($col, 'text') !== false) {
return ['type' => 'text', 'length' => null];
}
if ($col === 'bytea') {
return ['type' => 'binary', 'length' => null];
}
if ($col === 'real' || strpos($col, 'double') !== false) {
return ['type' => 'float', 'length' => null];
}
if (
strpos($col, 'numeric') !== false ||
strpos($col, 'money') !== false ||
strpos($col, 'decimal') !== false
) {
return ['type' => 'decimal', 'length' => null];
}
return ['type' => 'text', 'length' => null];
}
/**
* {@inheritDoc}
*/
public function convertColumnDescription(Table $table, $row) {
$field = $this->_convertColumn($row['type']);
if ($field['type'] === 'boolean') {
if ($row['default'] === 'true') {
$row['default'] = 1;
}
if ($row['default'] === 'false') {
$row['default'] = 0;
}
}
$field += [
'default' => $this->_defaultValue($row['default']),
'null' => $row['null'] === 'YES' ? true : false,
'comment' => $row['comment']
];
$field['length'] = $row['char_length'] ?: $field['length'];
$table->addColumn($row['name'], $field);
}
/**
* Manipulate the default value.
*
* Postgres includes sequence data and casting information in default values.
* We need to remove those.
*
* @param string $default The default value.
* @return string|null
*/
protected function _defaultValue($default) {
if (is_numeric($default) || $default === null) {
return $default;
}
// Sequences
if (strpos($default, 'nextval') === 0) {
return null;
}
// Remove quotes and postgres casts
return preg_replace(
"/^'(.*)'(?:::.*)$/",
"$1",
$default
);
}
/**
* {@inheritDoc}
*/
public function describeIndexSql($tableName, $config) {
$sql = 'SELECT
c2.relname,
i.indisprimary,
i.indisunique,
i.indisvalid,
pg_catalog.pg_get_indexdef(i.indexrelid, 0, true) AS statement
FROM pg_catalog.pg_class AS c,
pg_catalog.pg_class AS c2,
pg_catalog.pg_index AS i
WHERE c.oid = (
SELECT c.oid
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace
WHERE c.relname = ?
AND n.nspname = ?
)
AND c.oid = i.indrelid
AND i.indexrelid = c2.oid
ORDER BY i.indisprimary DESC, i.indisunique DESC, c2.relname';
$schema = 'public';
if (!empty($config['schema'])) {
$schema = $config['schema'];
}
return [$sql, [$tableName, $schema]];
}
/**
* {@inheritDoc}
*/
public function convertIndexDescription(Table $table, $row) {
$type = Table::INDEX_INDEX;
$name = $row['relname'];
if ($row['indisprimary']) {
$name = $type = Table::CONSTRAINT_PRIMARY;
}
if ($row['indisunique'] && $type === Table::INDEX_INDEX) {
$type = Table::CONSTRAINT_UNIQUE;
}
preg_match('/\(([^\)]+)\)/', $row['statement'], $matches);
$columns = $this->_convertColumnList($matches[1]);
if ($type === Table::CONSTRAINT_PRIMARY || $type === Table::CONSTRAINT_UNIQUE) {
$table->addConstraint($name, [
'type' => $type,
'columns' => $columns
]);
// If there is only one column in the primary key and it is integery,
// make it autoincrement.
$columnDef = $table->column($columns[0]);
if (
count($columns) === 1 &&
in_array($columnDef['type'], ['integer', 'biginteger']) &&
$type === Table::CONSTRAINT_PRIMARY
) {
$columnDef['autoIncrement'] = true;
$table->addColumn($columns[0], $columnDef);
}
return;
}
$table->addIndex($name, [
'type' => $type,
'columns' => $columns
]);
}
/**
* Convert a column list into a clean array.
*
* @param string $columns comma separated column list.
* @return array
*/
protected function _convertColumnList($columns) {
$columns = explode(', ', $columns);
foreach ($columns as &$column) {
$column = trim($column, '"');
}
return $columns;
}
/**
* {@inheritDoc}
*/
public function describeForeignKeySql($tableName, $config) {
$sql = "SELECT
r.conname AS name,
r.confupdtype AS update_type,
r.confdeltype AS delete_type,
pg_catalog.pg_get_constraintdef(r.oid, true) AS definition
FROM pg_catalog.pg_constraint AS r
WHERE r.conrelid = (
SELECT c.oid
FROM pg_catalog.pg_class AS c,
pg_catalog.pg_namespace AS n
WHERE c.relname = ?
AND n.nspname = ?
AND n.oid = c.relnamespace
)
AND r.contype = 'f'";
$schema = empty($config['schema']) ? 'public' : $config['schema'];
return [$sql, [$tableName, $schema]];
}
/**
* {@inheritDoc}
*/
public function convertForeignKeyDescription(Table $table, $row) {
preg_match('/REFERENCES ([^\)]+)\(([^\)]+)\)/', $row['definition'], $matches);
$tableName = $matches[1];
$column = $matches[2];
preg_match('/FOREIGN KEY \(([^\)]+)\) REFERENCES/', $row['definition'], $matches);
$columns = $this->_convertColumnList($matches[1]);
$data = [
'type' => Table::CONSTRAINT_FOREIGN,
'columns' => $columns,
'references' => [$tableName, $column],
'update' => $this->_convertOnClause($row['update_type']),
'delete' => $this->_convertOnClause($row['delete_type']),
];
$name = $row['name'];
$table->addConstraint($name, $data);
}
/**
* {@inheritDoc}
*/
protected function _convertOnClause($clause) {
if ($clause === 'r') {
return Table::ACTION_RESTRICT;
}
if ($clause === 'a') {
return Table::ACTION_NO_ACTION;
}
if ($clause === 'c') {
return Table::ACTION_CASCADE;
}
return Table::ACTION_SET_NULL;
}
/**
* {@inheritDoc}
*/
public function columnSql(Table $table, $name) {
$data = $table->column($name);
$out = $this->_driver->quoteIdentifier($name);
$typeMap = [
'boolean' => ' BOOLEAN',
'binary' => ' BYTEA',
'float' => ' FLOAT',
'decimal' => ' DECIMAL',
'text' => ' TEXT',
'date' => ' DATE',
'time' => ' TIME',
'datetime' => ' TIMESTAMP',
'timestamp' => ' TIMESTAMP',
'uuid' => ' UUID',
];
if (isset($typeMap[$data['type']])) {
$out .= $typeMap[$data['type']];
}
if ($data['type'] === 'integer' || $data['type'] === 'biginteger') {
$type = $data['type'] === 'integer' ? ' INTEGER' : ' BIGINT';
if ([$name] === $table->primaryKey() || $data['autoIncrement'] === true) {
$type = $data['type'] === 'integer' ? ' SERIAL' : ' BIGSERIAL';
unset($data['null'], $data['default']);
}
$out .= $type;
}
if ($data['type'] === 'string') {
$isFixed = !empty($data['fixed']);
$type = ' VARCHAR';
if ($isFixed) {
$type = ' CHAR';
}
$out .= $type;
if (isset($data['length']) && $data['length'] != 36) {
$out .= '(' . (int)$data['length'] . ')';
}
}
if ($data['type'] === 'float' && isset($data['precision'])) {
$out .= '(' . (int)$data['precision'] . ')';
}
if ($data['type'] === 'decimal' &&
(isset($data['length']) || isset($data['precision']))
) {
$out .= '(' . (int)$data['length'] . ',' . (int)$data['precision'] . ')';
}
if (isset($data['null']) && $data['null'] === false) {
$out .= ' NOT NULL';
}
if (isset($data['null']) && $data['null'] === true) {
$out .= ' DEFAULT NULL';
unset($data['default']);
}
if (isset($data['default']) && $data['type'] !== 'timestamp') {
$out .= ' DEFAULT ' . $this->_driver->schemaValue($data['default']);
}
return $out;
}
/**
* {@inheritDoc}
*/
public function indexSql(Table $table, $name) {
$data = $table->index($name);
$columns = array_map(
[$this->_driver, 'quoteIdentifier'],
$data['columns']
);
return sprintf('CREATE INDEX %s ON %s (%s)',
$this->_driver->quoteIdentifier($name),
$this->_driver->quoteIdentifier($table->name()),
implode(', ', $columns)
);
}
/**
* {@inheritDoc}
*/
public function constraintSql(Table $table, $name) {
$data = $table->constraint($name);
$out = 'CONSTRAINT ' . $this->_driver->quoteIdentifier($name);
if ($data['type'] === Table::CONSTRAINT_PRIMARY) {
$out = 'PRIMARY KEY';
}
if ($data['type'] === Table::CONSTRAINT_UNIQUE) {
$out .= ' UNIQUE';
}
return $this->_keySql($out, $data);
}
/**
* Helper method for generating key SQL snippets.
*
* @param string $prefix The key prefix
* @param array $data Key data.
* @return string
*/
protected function _keySql($prefix, $data) {
$columns = array_map(
[$this->_driver, 'quoteIdentifier'],
$data['columns']
);
if ($data['type'] === Table::CONSTRAINT_FOREIGN) {
return $prefix . sprintf(
' FOREIGN KEY (%s) REFERENCES %s (%s) ON UPDATE %s ON DELETE %s DEFERRABLE INITIALLY IMMEDIATE',
implode(', ', $columns),
$this->_driver->quoteIdentifier($data['references'][0]),
$this->_driver->quoteIdentifier($data['references'][1]),
$this->_foreignOnClause($data['update']),
$this->_foreignOnClause($data['delete'])
);
}
return $prefix . ' (' . implode(', ', $columns) . ')';
}
/**
* {@inheritDoc}
*/
public function createTableSql(Table $table, $columns, $constraints, $indexes) {
$content = array_merge($columns, $constraints);
$content = implode(",\n", array_filter($content));
$tableName = $this->_driver->quoteIdentifier($table->name());
$temporary = $table->temporary() ? ' TEMPORARY ' : ' ';
$out = [];
$out[] = sprintf("CREATE%sTABLE %s (\n%s\n)", $temporary, $tableName, $content);
foreach ($indexes as $index) {
$out[] = $index;
}
foreach ($table->columns() as $column) {
$columnData = $table->column($column);
if (isset($columnData['comment'])) {
$out[] = sprintf('COMMENT ON COLUMN %s.%s IS %s',
$tableName,
$this->_driver->quoteIdentifier($column),
$this->_driver->schemaValue($columnData['comment'])
);
}
}
return $out;
}
/**
* {@inheritDoc}
*/
public function truncateTableSql(Table $table) {
$name = $this->_driver->quoteIdentifier($table->name());
return [
sprintf('TRUNCATE %s RESTART IDENTITY CASCADE', $name)
];
}
/**
* Generate the SQL to drop a table.
*
* @param \Cake\Database\Schema\Table $table Table instance
* @return array SQL statements to drop a table.
*/
public function dropTableSql(Table $table) {
$sql = sprintf(
'DROP TABLE %s CASCADE',
$this->_driver->quoteIdentifier($table->name())
);
return [$sql];
}
}