-
Notifications
You must be signed in to change notification settings - Fork 611
/
Schema.php
379 lines (337 loc) · 11.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
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\db\pgsql;
use Craft;
use craft\db\Connection;
use craft\db\ExpressionBuilder;
use craft\db\ExpressionInterface;
use craft\db\TableSchema;
use craft\helpers\App;
use mikehaertl\shellcommand\Command as ShellCommand;
use yii\db\Exception;
/**
* @inheritdoc
* @method TableSchema|null getTableSchema($name, $refresh = false) Obtains the schema information for the named table.
* @property Connection $db
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 3.0.0
*/
class Schema extends \yii\db\pgsql\Schema
{
/**
* @var int The maximum length that objects' names can be.
*/
public int $maxObjectNameLength = 63;
/**
* Returns whether a table supports 4-byte characters.
*
* @param string $table The table to check
* @return bool
* @since 5.0.0
*/
public function supportsMb4(string $table): bool
{
return true;
}
/**
* 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(): QueryBuilder
{
return new QueryBuilder($this->db, [
'expressionBuilders' => [
ExpressionInterface::class => ExpressionBuilder::class,
],
'separator' => "\n",
]);
}
/**
* Quotes a database name for use in a query.
*
* @param string $name
* @return string
*/
public function quoteDatabaseName(string $name): string
{
return '"' . $name . '"';
}
/**
* Releases an existing savepoint.
*
* @param string $name The savepoint name.
* @throws Exception
*/
public function releaseSavepoint($name): void
{
try {
parent::releaseSavepoint($name);
} catch (Exception $e) {
// Specifically look for a "No such savepoint" error.
/** @phpstan-ignore-next-line */
if (in_array($e->getCode(), ['25P01', '3B001'], true)) {
Craft::warning('Tried to release a savepoint, but it does not exist: ' . $e->getMessage(), __METHOD__);
} else {
throw $e;
}
}
}
/**
* Rolls back to a previously created savepoint.
*
* @param string $name The savepoint name.
* @throws Exception
*/
public function rollBackSavepoint($name): void
{
try {
parent::rollBackSavepoint($name);
} catch (Exception $e) {
// Specifically look for a "No such savepoint" error.
if ($e->getCode() == 3 && isset($e->errorInfo[0]) && isset($e->errorInfo[1]) && $e->errorInfo[0] === '3B001' && $e->errorInfo[1] == 7) {
Craft::warning('Tried to roll back a savepoint, but it does not exist: ' . $e->getMessage(), __METHOD__);
} else {
throw $e;
}
}
}
/**
* @inheritdoc
*/
public function getLastInsertID($sequenceName = ''): string
{
if ($sequenceName !== '') {
if (!str_contains($sequenceName, '.')) {
$sequenceName = $this->defaultSchema . '.' . $this->getRawTableName($sequenceName);
}
$sequenceName .= '_id_seq';
}
return parent::getLastInsertID($sequenceName);
}
/**
* Returns the default backup command to execute.
*
* @param string[]|null $ignoreTables The table names whose data should be excluded from the backup
* @return string The command to execute
*/
public function getDefaultBackupCommand(?array $ignoreTables = null): string
{
$command = (new ShellCommand('pg_dump'))
->addArg('--dbname=', '{database}')
->addArg('--host=', '{server}')
->addArg('--port=', '{port}')
->addArg('--username=', '{user}')
->addArg('--if-exists')
->addArg('--clean')
->addArg('--no-owner')
->addArg('--no-privileges')
->addArg('--no-acl')
->addArg('--file=', '{file}')
->addArg('--schema=', '{schema}');
$ignoreTables = $ignoreTables ?? Craft::$app->getDb()->getIgnoredBackupTables();
$format = Craft::$app->getConfig()->getGeneral()->backupCommandFormat;
$commandFromConfig = Craft::$app->getConfig()->getGeneral()->backupCommand;
foreach ($ignoreTables as $table) {
$table = $this->getRawTableName($table);
$command->addArg('--exclude-table-data', "{schema}.$table");
}
if ($format) {
$command->addArg('--format=', $format);
}
if ($commandFromConfig instanceof \Closure) {
$command = $commandFromConfig($command);
}
return $this->_pgpasswordCommand() . $command->getExecCommand();
}
/**
* Returns the default database restore command to execute.
*
* @return string The command to execute
*/
public function getDefaultRestoreCommand(): string
{
$command = (new ShellCommand($this->usePgRestore() ? 'pg_restore' : 'psql'))
->addArg('--dbname=', '{database}')
->addArg('--host=', '{server}')
->addArg('--port=', '{port}')
->addArg('--username=', '{user}')
->addArg('--no-password');
$commandFromConfig = Craft::$app->getConfig()->getGeneral()->restoreCommand;
// If we're using pg_restore, we can't use STDIN, as it may be a directory
if ($this->usePgRestore()) {
$command->addArg('{file}');
}
if ($commandFromConfig instanceof \Closure) {
$command = $commandFromConfig($command);
}
return $this->_pgpasswordCommand()
. $command->getExecCommand()
. ($this->usePgRestore() ? '' : ' < "{file}"');
}
/**
* Returns all indexes for the given table. Each array element is of the following structure:
*
* ```php
* [
* 'IndexName' => [
* 'columns' => ['col1' [, ...]],
* 'unique' => false
* ],
* ]
* ```
*
* @param string $tableName The name of the table to get the indexes for.
* @return array All indexes for the given table.
*/
public function findIndexes(string $tableName): array
{
$tableName = Craft::$app->getDb()->getSchema()->getRawTableName($tableName);
$table = Craft::$app->getDb()->getSchema()->getTableSchema($tableName);
$indexes = [];
$rows = $this->getIndexInformation($table);
foreach ($rows as $row) {
$column = $row['columnname'];
if (!empty($column) && $column[0] === '"') {
// postgres will quote names that are not lowercase-only
// https://github.com/yiisoft/yii2/issues/10613
$column = substr($column, 1, -1);
}
$indexes[$row['indexname']]['columns'][] = $column;
$indexes[$row['indexname']]['unique'] = (bool)$row['isunique'];
}
return $indexes;
}
/**
* Loads the metadata for the specified table.
*
* @param string $name table name
* @return TableSchema|null driver dependent table metadata. Null if the table does not exist.
*/
public function loadTableSchema($name): ?TableSchema
{
$table = new TableSchema();
$this->resolveTableNames($table, $name);
if ($this->findColumns($table)) {
$this->findConstraints($table);
return $table;
}
return null;
}
/**
* Whether `pg_restore` should be used by default for the backup command.
*
* @return bool
* @since 4.9.0
*/
public function usePgRestore(): bool
{
return in_array(Craft::$app->getConfig()->getGeneral()->backupCommandFormat, [
'custom',
'directory',
], true);
}
/**
* Collects extra foreign key information details for the given table.
*
* @param TableSchema $table the table metadata
*/
protected function findConstraints($table): void
{
parent::findConstraints($table);
// Modified from parent to get extended FK information.
$tableName = $this->quoteValue($table->name);
$tableSchema = $this->quoteValue($table->schemaName);
$sql = <<<SQL
SELECT
ct.conname AS constraint_name,
a.attname AS column_name,
fc.relname AS foreign_table_name,
fns.nspname AS foreign_table_schema,
fa.attname AS foreign_column_name,
ct.confupdtype AS update_type,
ct.confdeltype AS delete_type
from
(SELECT ct.conname, ct.conrelid, ct.confrelid, ct.conkey, ct.contype, ct.confkey, generate_subscripts(ct.conkey, 1) AS s, ct.confupdtype, ct.confdeltype
FROM pg_constraint ct
) AS ct
INNER JOIN pg_class c ON c.oid=ct.conrelid
INNER JOIN pg_namespace ns ON c.relnamespace=ns.oid
INNER JOIN pg_attribute a ON a.attrelid=ct.conrelid AND a.attnum = ct.conkey[ct.s]
LEFT JOIN pg_class fc ON fc.oid=ct.confrelid
LEFT JOIN pg_namespace fns ON fc.relnamespace=fns.oid
LEFT JOIN pg_attribute fa ON fa.attrelid=ct.confrelid AND fa.attnum = ct.confkey[ct.s]
WHERE
ct.contype='f'
AND c.relname=$tableName
AND ns.nspname=$tableSchema
ORDER BY
fns.nspname, fc.relname, a.attnum
SQL;
$extendedConstraints = $this->db->createCommand($sql)->queryAll();
foreach ($extendedConstraints as $key => $extendedConstraint) {
// Find out what to do on update.
$updateAction = match ($extendedConstraint['update_type']) {
'a' => 'NO ACTION',
'r' => 'RESTRICT',
'c' => 'CASCADE',
'n' => 'SET NULL',
default => 'DEFAULT',
};
// Find out what to do on update.
$deleteAction = match ($extendedConstraint['delete_type']) {
'a' => 'NO ACTION',
'r' => 'RESTRICT',
'c' => 'CASCADE',
'n' => 'SET NULL',
default => 'DEFAULT',
};
$table->addExtendedForeignKey($key, [
'updateType' => $updateAction,
'deleteType' => $deleteAction,
]);
}
}
/**
* Gets information about given table indexes.
*
* @param TableSchema $table The table metadata
* @return array Index and column names
*/
protected function getIndexInformation(TableSchema $table): array
{
$sql = 'SELECT
i.relname as indexname,
pg_get_indexdef(idx.indexrelid, k + 1, TRUE) AS columnname,
indisunique as isunique
FROM (
SELECT *, generate_subscripts(indkey, 1) AS k
FROM pg_index
) idx
INNER JOIN pg_class i ON i.oid = idx.indexrelid
INNER JOIN pg_class c ON c.oid = idx.indrelid
INNER JOIN pg_namespace ns ON c.relnamespace = ns.oid
WHERE c.relname = :tableName AND ns.nspname = :schemaName
AND idx.indisprimary = FALSE
ORDER BY i.relname, k';
return $this->db->createCommand($sql, [
':schemaName' => $table->schemaName,
':tableName' => $table->name,
])->queryAll();
}
/**
* Returns the PGPASSWORD command for backup/restore actions.
*
* @return string
*/
private function _pgpasswordCommand(): string
{
return App::isWindows() ? 'set PGPASSWORD="{password}" && ' : 'PGPASSWORD="{password}" ';
}
}