forked from cebe/yii2-openapi
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMysqlMigrationBuilder.php
305 lines (267 loc) · 12 KB
/
MysqlMigrationBuilder.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
<?php
/**
* @copyright Copyright (c) 2018 Carsten Brandt <[email protected]> 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 cebe\yii2openapi\lib\items\DbIndex;
use yii\base\NotSupportedException;
use yii\db\ColumnSchema;
use yii\db\IndexConstraint;
use yii\db\Schema;
use yii\helpers\ArrayHelper;
final class MysqlMigrationBuilder extends BaseMigrationBuilder
{
/**
* @throws \yii\base\InvalidConfigException
*/
protected function buildColumnChanges(ColumnSchema $current, ColumnSchema $desired, array $changed):void
{
$positionCurrent = $positionDesired = null;
if (in_array('position', $changed, true)) {
$positionDesired = $this->findPosition($desired, false, true);
$positionCurrent = $this->findPosition($desired, true, true);
$key = array_search('position', $changed, true);
unset($changed[$key]);
}
$newColumn = clone $current;
foreach ($changed as $attr) {
$newColumn->$attr = $desired->$attr;
}
$this->migration->addUpCode($this->recordBuilder->alterColumn($this->model->getTableAlias(), $newColumn, $positionDesired))
->addDownCode($this->recordBuilder->alterColumn($this->model->getTableAlias(), $current, $positionCurrent));
}
protected function compareColumns(ColumnSchema $current, ColumnSchema $desired):array
{
$changedAttributes = [];
$tableAlias = $this->model->getTableAlias();
$this->modifyCurrent($current);
$this->modifyDesired($desired);
$this->modifyDesiredInContextOfCurrent($current, $desired);
// Why this is needed? Often manually created ColumnSchema instance have dbType 'varchar' with size 255 and ColumnSchema fetched from db have 'varchar(255)'. So varchar !== varchar(255). such normal mistake was leading to errors. So desired column is saved in temporary table and it is fetched from that temp. table and then compared with current ColumnSchema
$desiredFromDb = $this->tmpSaveNewCol($tableAlias, $desired);
$this->modifyDesiredInContextOfDesiredFromDb($desired, $desiredFromDb);
$this->modifyDesired($desiredFromDb);
$this->modifyDesiredInContextOfCurrent($current, $desiredFromDb);
$this->modifyDesiredFromDbInContextOfDesired($desired, $desiredFromDb);
foreach (['type', 'size', 'allowNull', 'defaultValue', 'enumValues'
, 'dbType', 'phpType'
, 'precision', 'scale', 'unsigned'
] as $attr) {
if ($attr === 'defaultValue') {
if ($this->isDefaultValueChanged($current, $desiredFromDb)) {
$changedAttributes[] = $attr;
}
} else {
if ($current->$attr !== $desiredFromDb->$attr) {
$changedAttributes[] = $attr;
}
}
}
if (property_exists($desired, 'isPositionChanged') && $desired->isPositionChanged) {
$changedAttributes[] = 'position';
}
return $changedAttributes;
}
protected function createEnumMigrations():void
{
// execute via default
}
protected function isDbDefaultSize(ColumnSchema $current):bool
{
$defaults = [
Schema::TYPE_PK => 11,
Schema::TYPE_BIGPK => 20,
Schema::TYPE_CHAR => 1,
Schema::TYPE_STRING => 255,
Schema::TYPE_TINYINT => 3,
Schema::TYPE_SMALLINT => 6,
Schema::TYPE_INTEGER => 11,
Schema::TYPE_BIGINT => 20,
Schema::TYPE_DECIMAL => 10,
Schema::TYPE_BOOLEAN => 1,
Schema::TYPE_MONEY => 19,
];
return isset($defaults[$current->type]);
}
/**
* @return array|DbIndex[]
*/
protected function findTableIndexes():array
{
$dbIndexes = [];
try {
/**@var IndexConstraint[] $indexes */
$indexes = $this->db->getSchema()->getTableIndexes($this->tableSchema->name);
$fkIndexes = array_keys($this->tableSchema->foreignKeys);
foreach ($indexes as $index) {
if (!$index->isPrimary && !in_array($index->name, $fkIndexes, true)) {
$dbIndexes[] = DbIndex::fromConstraint($this->model->tableName, $index);
}
}
return ArrayHelper::index($dbIndexes, 'name');
} catch (NotSupportedException $e) {
return [];
}
}
public static function getColumnSchemaBuilderClass(): string
{
if (ApiGenerator::isMariaDb()) {
return \SamIT\Yii2\MariaDb\ColumnSchemaBuilder::class;
} else {
throw new \Exception('Unknown database');
}
return \yii\db\mysql\ColumnSchemaBuilder::class;
}
public function modifyCurrent(ColumnSchema $current): void
{
/** @var $current \yii\db\mysql\ColumnSchema */
if ($current->phpType === 'integer' && $current->defaultValue !== null) {
$current->defaultValue = (int)$current->defaultValue;
}
}
public function modifyDesired(ColumnSchema $desired): void
{
/** @var $desired \cebe\yii2openapi\db\ColumnSchema|\yii\db\mysql\ColumnSchema */
if ($desired->phpType === 'int' && $desired->defaultValue !== null) {
$desired->defaultValue = (int)$desired->defaultValue;
}
if ($decimalAttributes = ColumnToCode::isDecimalByDbType($desired->dbType)) {
$desired->precision = $decimalAttributes['precision'];
$desired->scale = $decimalAttributes['scale'];
}
}
public function modifyDesiredInContextOfCurrent(ColumnSchema $current, ColumnSchema $desired): void
{
/** @var $current \yii\db\mysql\ColumnSchema */
/** @var $desired \cebe\yii2openapi\db\ColumnSchema|\yii\db\mysql\ColumnSchema */
if ($current->dbType === 'tinyint(1)' && $desired->type === 'boolean') {
if (is_bool($desired->defaultValue) || is_string($desired->defaultValue)) {
$desired->defaultValue = (int)$desired->defaultValue;
}
}
if ($current->type === $desired->type && !$desired->size && $this->isDbDefaultSize($current)) {
$desired->size = $current->size;
}
}
/**
* {@inheritDoc}
*/
public function findPosition(ColumnSchema $column, bool $forDrop = false, bool $forAlter = false): ?string
{
$columnNames = array_keys($forDrop ? $this->tableSchema->columns : $this->newColumns);
$key = array_search($column->name, $columnNames);
if ($key > 0) {
$prevColName = $columnNames[$key - 1];
if (($key === count($columnNames) - 1) && !$forAlter) {
return null;
}
if (array_key_exists($prevColName, $forDrop ? $this->tableSchema->columns : $this->newColumns)) {
if ($forDrop && !$forAlter) {
// if the previous column is the last one in the want names then no need for AFTER
$cols = array_keys($this->newColumns);
if ($prevColName === array_pop($cols)) {
return null;
}
}
if ($forAlter && $forDrop) {
if (!array_key_exists($prevColName, $this->newColumns)) {
return null;
}
}
return self::POS_AFTER . ' ' . $prevColName;
}
return null;
// if no `$columnSchema` is found, previous column does not exist. This happens when 'after column' is not yet added in migration or added after currently undertaken column
} elseif ($key === 0) {
return self::POS_FIRST;
}
return null;
}
public function setColumnsPositions()
{
$i = 0;
$haveColumns = $this->tableSchema->columns;
$wantNames = array_keys($this->newColumns);
$haveNames = array_keys($haveColumns);
// Part 1/2 compute from and to position
foreach ($this->newColumns as $name => $column) {
/** @var \cebe\yii2openapi\db\ColumnSchema $column */
$column->toPosition = [
'index' => $i + 1,
'after' => $i === 0 ? null : $wantNames[$i - 1],
'before' => $i === (count($wantNames) - 1) ? null : $wantNames[$i + 1],
];
if (isset($haveColumns[$name])) {
$index = array_search($name, $haveNames) + 1;
$column->fromPosition = [
'index' => $index,
'after' => $haveNames[$index - 2] ?? null,
'before' => $haveNames[$index] ?? null,
];
}
$i++;
}
// Part 2/2 compute is position is really changed
// check if only new columns are added without any explicit position change
$namesForCreate = array_diff($wantNames, $haveNames);
$wantNamesWoNewCols = array_values(array_diff($wantNames, $namesForCreate));
if ($namesForCreate && $haveNames === $wantNamesWoNewCols) {
return;
}
// check if only existing columns are deleted without any explicit position change
$namesForDrop = array_diff($haveNames, $wantNames);
$haveNamesWoDropCols = array_values(array_diff($haveNames, $namesForDrop));
if ($namesForDrop && $wantNames === $haveNamesWoDropCols) {
return;
}
// check both above simultaneously
if ($namesForCreate && $namesForDrop && ($wantNamesWoNewCols === $haveNamesWoDropCols)) {
return;
}
$takenIndices = $nonRedundantIndices = []; # $nonRedundantIndices are the wanted ones which are created by moving of one or more columns. Example: if a column is moved from 2nd to 8th position then we will consider only one column is moved ignoring index/position change(-1) of 4rd to 8th column (4->3, 5->4 ...). So migration for this unwanted indices changes won't be generated. `$takenIndices` might have redundant indices
foreach ($this->newColumns as $column) {
/** @var \cebe\yii2openapi\db\ColumnSchema $column */
if (!$column->fromPosition || !$column->toPosition) {
continue;
}
if (is_int(array_search([$column->toPosition['index'], $column->fromPosition['index']], $takenIndices))) {
continue;
}
if ($column->fromPosition === $column->toPosition) {
continue;
}
if ($column->fromPosition['index'] === $column->toPosition['index']) {
continue;
}
$column->isPositionChanged = true;
$takenIndices[] = [$column->fromPosition['index'], $column->toPosition['index']];
// -------
if (($column->fromPosition['before'] !== $column->toPosition['before']) &&
($column->fromPosition['after'] !== $column->toPosition['after'])
) {
$nonRedundantIndices[] = [$column->fromPosition['index'], $column->toPosition['index']];
}
}
foreach ($this->newColumns as $column) {
/** @var \cebe\yii2openapi\db\ColumnSchema $column */
if (!isset($column->toPosition['index'], $column->fromPosition['index'])) {
continue;
}
$condition = (abs($column->toPosition['index'] - $column->fromPosition['index']) === count($nonRedundantIndices));
if (($column->fromPosition['before'] === $column->toPosition['before'])
&& $condition
) {
$column->isPositionChanged = false;
continue;
}
if (($column->fromPosition['after'] === $column->toPosition['after'])
&& $condition
) {
$column->isPositionChanged = false;
}
}
}
}