Skip to content

Commit 74608e7

Browse files
authored
Updated TableOperation::apply() to remove non-existent columns from added indexes (#20)
1 parent f535ab5 commit 74608e7

2 files changed

Lines changed: 38 additions & 18 deletions

File tree

src/Operation/TableOperation.php

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -299,29 +299,31 @@ public function apply(TableOperation $operation)
299299

300300
$indexes[$indexOperation->getName()] = $indexOperation;
301301
}
302+
}
302303

303-
// Remove non-existent columns from indexes
304-
foreach ($indexes as $name => $index) {
305-
$indexColumns = [];
306-
foreach ($index->getColumns() as $indexColumn) {
307-
foreach ($columns as $column) {
308-
if ($column->getName() === $indexColumn) {
309-
$indexColumns[] = $indexColumn;
310-
}
311-
}
312-
}
304+
// Remove non-existent columns from indexes
305+
foreach ($indexes as $name => $index) {
306+
$indexColumns = [];
313307

314-
if (empty($indexColumns)) {
315-
continue;
308+
foreach ($index->getColumns() as $indexColumn) {
309+
foreach ($columns as $column) {
310+
if ($column->getName() === $indexColumn) {
311+
$indexColumns[] = $indexColumn;
312+
}
316313
}
314+
}
317315

318-
$indexes[$name] = new IndexOperation(
319-
$index->getName(),
320-
$index->getOperation(),
321-
$indexColumns,
322-
$index->getOptions()
323-
);
316+
if ($index->getOperation() === IndexOperation::ADD && empty($indexColumns)) {
317+
unset($indexes[$name]);
318+
continue;
324319
}
320+
321+
$indexes[$name] = new IndexOperation(
322+
$index->getName(),
323+
$index->getOperation(),
324+
$indexColumns,
325+
$index->getOptions()
326+
);
325327
}
326328

327329
return new TableOperation(

tests/Operation/TableOperationTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,4 +171,22 @@ public function testReverseDrop()
171171

172172
$this->assertEquals($create, $operation);
173173
}
174+
175+
public function testDropColumnReferencedByIndex()
176+
{
177+
$base = new TableOperation('users_roles', TableOperation::CREATE, [
178+
new ColumnOperation('user_id', ColumnOperation::ADD, ['type' => 'uuid']),
179+
new ColumnOperation('role', ColumnOperation::ADD, ['type' => 'string']),
180+
new ColumnOperation('deleted_at', ColumnOperation::ADD, ['type' => 'datetime'])
181+
], [
182+
new IndexOperation('user_role', IndexOperation::ADD, ['user_id', 'role', 'deleted_at'], [])
183+
]);
184+
185+
$alter = new TableOperation('users_roles', TableOperation::ALTER, [
186+
new ColumnOperation('deleted_at', ColumnOperation::DROP, [])
187+
], []);
188+
189+
$operation = $base->apply($alter);
190+
$this->assertNotContains('deleted_at', $operation->getIndexOperations()[0]->getColumns());
191+
}
174192
}

0 commit comments

Comments
 (0)