forked from cebe/yii2-openapi
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMigrationRecordBuilder.php
More file actions
401 lines (351 loc) · 16.4 KB
/
Copy pathMigrationRecordBuilder.php
File metadata and controls
401 lines (351 loc) · 16.4 KB
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
<?php
/**
* @copyright Copyright (c) 2018 Carsten Brandt <mail@cebe.cc> and contributors
* @license https://github.com/cebe/yii2-openapi/blob/master/LICENSE
*/
namespace cebe\yii2openapi\lib\migrations;
use cebe\yii2openapi\generator\ApiGenerator;
use cebe\yii2openapi\lib\ColumnToCode;
use Yii;
use yii\db\ColumnSchema;
use yii\db\Schema;
use yii\helpers\VarDumper;
use function implode;
use function sprintf;
use function str_replace;
final class MigrationRecordBuilder
{
public const INDENT = ' ';
public const DROP_INDEX = MigrationRecordBuilder::INDENT . "\$this->dropIndex('%s', '%s');";
public const DROP_FK = MigrationRecordBuilder::INDENT . "\$this->dropForeignKey('%s', '%s');";
public const DROP_PK = MigrationRecordBuilder::INDENT . "\$this->dropPrimaryKey('%s', '%s');";
public const ADD_TABLE = MigrationRecordBuilder::INDENT . "\$this->createTable('%s', %s);";
public const ADD_UNIQUE = MigrationRecordBuilder::INDENT . "\$this->createIndex('%s', '%s', %s, true);";
public const ADD_INDEX = MigrationRecordBuilder::INDENT . "\$this->createIndex('%s', '%s', %s, %s);";
public const DROP_COLUMN = MigrationRecordBuilder::INDENT . "\$this->dropColumn('%s', '%s');";
public const ADD_ENUM = MigrationRecordBuilder::INDENT . "\$this->execute('CREATE TYPE \"enum_%s_%s\" AS ENUM(%s)');";
public const DROP_ENUM = MigrationRecordBuilder::INDENT . "\$this->execute('DROP TYPE \"enum_%s_%s\"');";
public const DROP_TABLE = MigrationRecordBuilder::INDENT . "\$this->dropTable('%s');";
public const ADD_FK = MigrationRecordBuilder::INDENT . "\$this->addForeignKey('%s', '%s', '%s', '%s', '%s');";
public const ADD_FK_WITH_JUST_ON_DELETE = MigrationRecordBuilder::INDENT . "\$this->addForeignKey('%s', '%s', '%s', '%s', '%s', '%s');";
public const ADD_FK_WITH_ON_UPDATE = MigrationRecordBuilder::INDENT . "\$this->addForeignKey('%s', '%s', '%s', '%s', '%s', %s, '%s');";
public const ADD_PK = MigrationRecordBuilder::INDENT . "\$this->addPrimaryKey('%s', '%s', '%s');";
public const ADD_COLUMN = MigrationRecordBuilder::INDENT . "\$this->addColumn('%s', '%s', %s);";
public const ALTER_COLUMN = MigrationRecordBuilder::INDENT . "\$this->alterColumn('%s', '%s', %s);";
public const ADD_COLUMN_RAW = MigrationRecordBuilder::INDENT . "\$this->db->createCommand('ALTER TABLE %s ADD COLUMN %s %s')->execute();";
public const ALTER_COLUMN_RAW = MigrationRecordBuilder::INDENT . "\$this->db->createCommand('ALTER TABLE %s MODIFY %s %s')->execute();";
public const ALTER_COLUMN_RAW_PGSQL = MigrationRecordBuilder::INDENT . "\$this->db->createCommand('ALTER TABLE %s ALTER COLUMN \"%s\" SET DATA TYPE %s')->execute();";
public const ADD_COMMENT_ON_COLUMN = MigrationRecordBuilder::INDENT . "\$this->addCommentOnColumn('%s', '%s', %s);";
public const DROP_COMMENT_FROM_COLUMN = MigrationRecordBuilder::INDENT . "\$this->dropCommentFromColumn('%s', '%s');";
public const RENAME_COLUMN = MigrationRecordBuilder::INDENT . "\$this->renameColumn('%s', '%s', '%s');";
/**
* @var \yii\db\Schema
*/
private $dbSchema;
/**
* @var bool
* Only required for PgSQL alter column for set null/set default related statement
*/
public $isBuiltInType = false;
public function __construct(Schema $dbSchema)
{
$this->dbSchema = $dbSchema;
}
/**
* @param string $tableAlias
* @param array|ColumnSchema $columns
* @return string
* @throws \yii\base\InvalidConfigException
*/
public function createTable(string $tableAlias, array $columns):string
{
$codeColumns = [];
foreach ($columns as $columnName => $cebeDbColumnSchema) {
if (static::isXDbTypePresent($cebeDbColumnSchema)) {
$name = static::quote($columnName);
$codeColumns[] = $name.' '.$this->columnToCode($tableAlias, $cebeDbColumnSchema, false)->getCode();
} else {
$codeColumns[$columnName] = $this->columnToCode($tableAlias, $cebeDbColumnSchema, false)->getCode();
}
}
$codeColumns = static::makeString($codeColumns);
return sprintf(self::ADD_TABLE, $tableAlias, $codeColumns);
}
/**
* @throws \yii\base\InvalidConfigException
*/
public function addColumn(string $tableAlias, ColumnSchema $column, ?string $position = null):string
{
// $converter = $this->columnToCode($column, false, false, $position);
if (is_string($column->xDbType) && !empty($column->xDbType)) {
$converter = $this->columnToCode($tableAlias, $column, false, false, false, false, $position);
$name = static::quote($column->name);
return sprintf(self::ADD_COLUMN_RAW, $tableAlias, $name, ColumnToCode::escapeQuotes($converter->getCode()));
}
$converter = $this->columnToCode($tableAlias, $column, false, false, false, false, $position);
return sprintf(self::ADD_COLUMN, $tableAlias, $column->name, $converter->getCode(true));
}
/**
* @throws \yii\base\InvalidConfigException
*/
public function addDbColumn(string $tableAlias, ColumnSchema $column, ?string $position = null):string
{
if (property_exists($column, 'xDbType') && is_string($column->xDbType) && !empty($column->xDbType)) {
$converter = $this->columnToCode($tableAlias, $column, true, false, false, false, $position);
$name = static::quote($column->name);
return sprintf(self::ADD_COLUMN_RAW, $tableAlias, $column->name, ColumnToCode::escapeQuotes($converter->getCode()));
}
$converter = $this->columnToCode($tableAlias, $column, true, false, false, false, $position);
return sprintf(self::ADD_COLUMN, $tableAlias, $column->name, $converter->getCode(true));
}
/**
* @throws \yii\base\InvalidConfigException
*/
public function alterColumn(string $tableAlias, ColumnSchema $column, ?string $position = null):string
{
if (property_exists($column, 'xDbType') && is_string($column->xDbType) && !empty($column->xDbType)) {
$converter = $this->columnToCode($tableAlias, $column, true, false, true, true, $position);
return sprintf(
ApiGenerator::isPostgres() ? self::ALTER_COLUMN_RAW_PGSQL : self::ALTER_COLUMN_RAW,
$tableAlias,
$column->name,
ColumnToCode::escapeQuotes($converter->getCode())
);
}
$converter = $this->columnToCode($tableAlias, $column, true, false, false, false, $position);
return sprintf(self::ALTER_COLUMN, $tableAlias, $column->name, $converter->getCode(true));
}
/**
* @throws \yii\base\InvalidConfigException
*/
public function alterColumnType(
string $tableAlias,
ColumnSchema $column,
bool $addUsing = false,
?string $position = null
):string {
if (property_exists($column, 'xDbType') && is_string($column->xDbType) && !empty($column->xDbType)) {
$converter = $this->columnToCode($tableAlias, $column, false, false, true, true, $position);
$this->isBuiltInType = $converter->isBuiltinType;
return sprintf(
ApiGenerator::isPostgres() ? self::ALTER_COLUMN_RAW_PGSQL : self::ALTER_COLUMN_RAW,
$tableAlias,
$column->name,
rtrim(ltrim($converter->getAlterExpression($addUsing), "'"), "'")
);
}
$converter = $this->columnToCode($tableAlias, $column, false, false, false, false, $position);
$this->isBuiltInType = $converter->isBuiltinType;
return sprintf(self::ALTER_COLUMN, $tableAlias, $column->name, $converter->getAlterExpression($addUsing));
}
/**
* This method is only used in Pgsql
* @throws \yii\base\InvalidConfigException
*/
public function alterColumnTypeFromDb(
string $tableAlias,
ColumnSchema $column,
bool $addUsing = false,
?string $position = null
) :string {
if (property_exists($column, 'xDbType') && is_string($column->xDbType) && !empty($column->xDbType)) {
$converter = $this->columnToCode($tableAlias, $column, true, false, true, true, $position);
$this->isBuiltInType = $converter->isBuiltinType;
return sprintf(
ApiGenerator::isPostgres() ? self::ALTER_COLUMN_RAW_PGSQL : self::ALTER_COLUMN_RAW,
$tableAlias,
$column->name,
rtrim(ltrim($converter->getAlterExpression($addUsing), "'"), "'")
);
}
$converter = $this->columnToCode($tableAlias, $column, true, false, false, false, $position);
$this->isBuiltInType = $converter->isBuiltinType;
return sprintf(self::ALTER_COLUMN, $tableAlias, $column->name, $converter->getAlterExpression($addUsing));
}
/**
* @throws \yii\base\InvalidConfigException
*/
public function setColumnDefault(string $tableAlias, ColumnSchema $column):string
{
$default = $this->columnToCode($tableAlias, $column, false, true)->getDefaultValue();
if ($default === null) {
return '';
}
return sprintf(self::ALTER_COLUMN, $tableAlias, $column->name, '"SET DEFAULT '.$default.'"');
}
/**
* @throws \yii\base\InvalidConfigException
*/
public function setColumnDefaultFromDb(string $tableAlias, ColumnSchema $column):string
{
$default = $this->columnToCode($tableAlias, $column, true, true)->getDefaultValue();
if ($default === null) {
return '';
}
return sprintf(self::ALTER_COLUMN, $tableAlias, $column->name, '"SET DEFAULT '.$default.'"');
}
public function dropColumnDefault(string $tableAlias, ColumnSchema $column):string
{
return sprintf(self::ALTER_COLUMN, $tableAlias, $column->name, '"DROP DEFAULT"');
}
public function setColumnNotNull(string $tableAlias, ColumnSchema $column):string
{
return sprintf(self::ALTER_COLUMN, $tableAlias, $column->name, '"SET NOT NULL"');
}
public function dropColumnNotNull(string $tableAlias, ColumnSchema $column):string
{
return sprintf(self::ALTER_COLUMN, $tableAlias, $column->name, '"DROP NOT NULL"');
}
public function createEnum(string $tableAlias, string $columnName, array $values):string
{
$rawTableName = $this->dbSchema->getRawTableName($tableAlias);
return sprintf(self::ADD_ENUM, $rawTableName, $columnName, ColumnToCode::enumToString($values));
}
public function addFk(string $fkName, string $tableAlias, string $fkCol, string $refTable, string $refCol, ?string $onDelete = null, ?string $onUpdate = null):string
{
if ($onUpdate === null && $onDelete === null) {
return sprintf(self::ADD_FK, $fkName, $tableAlias, $fkCol, $refTable, $refCol);
} elseif ($onDelete !== null && $onUpdate === null) {
return sprintf(self::ADD_FK_WITH_JUST_ON_DELETE, $fkName, $tableAlias, $fkCol, $refTable, $refCol, $onDelete);
} elseif ($onUpdate !== null) {
return sprintf(
self::ADD_FK_WITH_ON_UPDATE,
$fkName,
$tableAlias,
$fkCol,
$refTable,
$refCol,
$onDelete === null ? 'null' : "'$onDelete'",
$onUpdate
);
}
throw new \Exception('Cannot add foreign key');
}
public function addUniqueIndex(string $tableAlias, string $indexName, array $columns):string
{
return sprintf(
self::ADD_UNIQUE,
$indexName,
$tableAlias,
count($columns) === 1 ? "'{$columns[0]}'" : '["'.implode('", "', $columns).'"]'
);
}
public function addIndex(string $tableAlias, string $indexName, array $columns, ?string $using = null):string
{
$indexType = $using === null ? 'false' : "'".ColumnToCode::escapeQuotes($using)."'";
if ($using && (stripos($using, '(') !== false) && ApiGenerator::isPostgres()) {
// if `$using` is `gin(to_tsvector('english', search::text))`
$r = explode('(', $using, 2);
$indexType = "'".$r[0]."'"; # `gin`
$columnDbIndexExpression = substr($r[1], 0, -1); # to_tsvector('english', search::text)
$columns = [ColumnToCode::escapeQuotes($columnDbIndexExpression)];
}
return sprintf(
self::ADD_INDEX,
$indexName,
$tableAlias,
count($columns) === 1 ? "'". $columns[0]."'" : '["'.implode('", "', $columns).'"]',
$indexType
);
}
public function addPrimaryKey(string $tableAlias, array $columns, string $pkName= null):string
{
$pkName = $pkName ?? ('pk_'. implode('_', $columns));
return sprintf(self::ADD_PK, $pkName, $tableAlias, implode(',', $columns));
}
public function dropPrimaryKey(string $tableAlias, array $columns, string $pkName = null):string
{
$pkName = $pkName ?? ('pk_'. implode('_', $columns));
return sprintf(self::DROP_PK, $pkName, $tableAlias);
}
public function dropTable(string $tableAlias):string
{
return sprintf(self::DROP_TABLE, $tableAlias);
}
public function dropEnum(string $tableAlias, string $columnName):string
{
$rawTableName = $this->dbSchema->getRawTableName($tableAlias);
return sprintf(self::DROP_ENUM, $rawTableName, $columnName);
}
public function dropFk(string $fkName, string $tableAlias):string
{
return sprintf(self::DROP_FK, $fkName, $tableAlias);
}
public function dropColumn(string $tableAlias, string $columnName):string
{
return sprintf(self::DROP_COLUMN, $tableAlias, $columnName);
}
public function dropIndex(string $tableAlias, string $indexName):string
{
return sprintf(self::DROP_INDEX, $indexName, $tableAlias);
}
/**
* @throws \yii\base\InvalidConfigException
*/
private function columnToCode(
string $tableAlias,
ColumnSchema $column,
bool $fromDb = false,
bool $alter = false,
bool $raw = false,
bool $alterByXDbType = false,
?string $position = null
): ColumnToCode {
return Yii::createObject(ColumnToCode::class, [
$this->dbSchema,
$tableAlias,
$column,
$fromDb,
$alter,
$raw,
$alterByXDbType,
$position
]);
}
// https://github.com/cebe/yii2-openapi/issues/127
public static function quote(string $columnName): string
{
if (ApiGenerator::isPostgres()) {
return '"'.$columnName.'"';
}
return $columnName;
}
/**
* Convert code columns array to comlpete syntactically correct PHP code string which will be written to migration file
*/
public static function makeString(array $codeColumns): string
{
$finalStr = ''.PHP_EOL;
foreach ($codeColumns as $key => $column) {
if (is_string($key)) {
if (substr($column, 0, 5) === '$this') {
$finalStr .= VarDumper::export($key).' => '.$column.','.PHP_EOL;
} else {
$finalStr .= VarDumper::export($key).' => '.VarDumper::export($column).','.PHP_EOL;
}
} else {
$finalStr .= VarDumper::export($key).' => '.VarDumper::export($column).','.PHP_EOL;
}
}
$codeColumns = str_replace([PHP_EOL], [PHP_EOL . self::INDENT.' '], $finalStr);
$codeColumns = trim($codeColumns);
$codeColumns = '['.PHP_EOL.self::INDENT.' '.$codeColumns.PHP_EOL . self::INDENT.']';
return $codeColumns;
}
public function addCommentOnColumn($table, string $column, string $comment): string
{
return sprintf(self::ADD_COMMENT_ON_COLUMN, $table, $column, var_export($comment, true));
}
public function dropCommentFromColumn($table, string $column): string
{
return sprintf(self::DROP_COMMENT_FROM_COLUMN, $table, $column);
}
public function renameColumn(string $table, string $fromColumn, string $toColumn): string
{
return sprintf(self::RENAME_COLUMN, $table, $fromColumn, $toColumn);
}
public static function isXDbTypePresent(ColumnSchema $columnSchema): bool
{
return (!empty($columnSchema->xDbType) && is_string($columnSchema->xDbType));
}
}