From 61e7abbe51d3a34ece716501cecbd0eb93d65a32 Mon Sep 17 00:00:00 2001 From: Brent Roose Date: Fri, 13 Dec 2024 09:19:40 +0100 Subject: [PATCH] feat(database): alter table with only indices (#852) --- .../QueryStatements/AlterTableStatement.php | 24 +++++++++++-------- .../AlterTableStatementTest.php | 10 ++++++++ 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/src/Tempest/Database/src/QueryStatements/AlterTableStatement.php b/src/Tempest/Database/src/QueryStatements/AlterTableStatement.php index 6e9744f25..96cbce3a2 100644 --- a/src/Tempest/Database/src/QueryStatements/AlterTableStatement.php +++ b/src/Tempest/Database/src/QueryStatements/AlterTableStatement.php @@ -89,16 +89,20 @@ public function drop(QueryStatement $statement): self public function compile(DatabaseDialect $dialect): string { - $alterTable = sprintf( - 'ALTER TABLE %s %s;', - new TableName($this->tableName), - arr($this->statements) - ->map(fn (QueryStatement $queryStatement) => str($queryStatement->compile($dialect))->trim()->replace(' ', ' ')) - ->filter(fn (StringHelper $line) => $line->isNotEmpty()) - ->implode(', ' . PHP_EOL . ' ') - ->wrap(before: PHP_EOL . ' ', after: PHP_EOL) - ->toString(), - ); + if ($this->statements !== []) { + $alterTable = sprintf( + 'ALTER TABLE %s %s;', + new TableName($this->tableName), + arr($this->statements) + ->map(fn (QueryStatement $queryStatement) => str($queryStatement->compile($dialect))->trim()->replace(' ', ' ')) + ->filter(fn (StringHelper $line) => $line->isNotEmpty()) + ->implode(', ' . PHP_EOL . ' ') + ->wrap(before: PHP_EOL . ' ', after: PHP_EOL) + ->toString(), + ); + } else { + $alterTable = ''; + } if ($this->createIndexStatements !== []) { $createIndices = PHP_EOL . arr($this->createIndexStatements) diff --git a/tests/Integration/Database/QueryStatements/AlterTableStatementTest.php b/tests/Integration/Database/QueryStatements/AlterTableStatementTest.php index 74247c975..68292e709 100644 --- a/tests/Integration/Database/QueryStatements/AlterTableStatementTest.php +++ b/tests/Integration/Database/QueryStatements/AlterTableStatementTest.php @@ -71,6 +71,16 @@ public function test_it_can_alter_a_table_definition(): void $this->assertSame('test@example.com', $user->email); } + public function test_alter_for_only_indexes(): void + { + $statement = new AlterTableStatement('table') + ->index('foo') + ->unique('bar') + ->compile(DatabaseDialect::SQLITE); + + $this->assertStringNotContainsString('ALTER TABLE', $statement); + } + private function getAlterTableMigration(): mixed { return new class () implements DatabaseMigration {