diff --git a/src/Tempest/Database/src/QueryStatements/AlterTableStatement.php b/src/Tempest/Database/src/QueryStatements/AlterTableStatement.php index 3f26d3377..6e9744f25 100644 --- a/src/Tempest/Database/src/QueryStatements/AlterTableStatement.php +++ b/src/Tempest/Database/src/QueryStatements/AlterTableStatement.php @@ -16,6 +16,7 @@ final class AlterTableStatement implements QueryStatement public function __construct( private readonly string $tableName, private array $statements = [], + private array $createIndexStatements = [], ) {} /** @param class-string<\Tempest\Database\DatabaseModel> $modelClass */ @@ -61,7 +62,7 @@ public function constraint(string $constraintName, ?QueryStatement $statement = public function unique(string ...$columns): self { - $this->statements[] = new UniqueStatement( + $this->createIndexStatements[] = new UniqueStatement( tableName: $this->tableName, columns: $columns, ); @@ -71,7 +72,7 @@ public function unique(string ...$columns): self public function index(string ...$columns): self { - $this->statements[] = new IndexStatement( + $this->createIndexStatements[] = new IndexStatement( tableName: $this->tableName, columns: $columns, ); @@ -88,7 +89,7 @@ public function drop(QueryStatement $statement): self public function compile(DatabaseDialect $dialect): string { - return sprintf( + $alterTable = sprintf( 'ALTER TABLE %s %s;', new TableName($this->tableName), arr($this->statements) @@ -98,5 +99,16 @@ public function compile(DatabaseDialect $dialect): string ->wrap(before: PHP_EOL . ' ', after: PHP_EOL) ->toString(), ); + + if ($this->createIndexStatements !== []) { + $createIndices = PHP_EOL . arr($this->createIndexStatements) + ->map(fn (QueryStatement $queryStatement) => str($queryStatement->compile($dialect))->trim()->replace(' ', ' ')) + ->implode(';' . PHP_EOL) + ->append(';'); + } else { + $createIndices = ''; + } + + return $alterTable . $createIndices; } } diff --git a/src/Tempest/Database/src/QueryStatements/CreateTableStatement.php b/src/Tempest/Database/src/QueryStatements/CreateTableStatement.php index ceed0c67e..fe46888e2 100644 --- a/src/Tempest/Database/src/QueryStatements/CreateTableStatement.php +++ b/src/Tempest/Database/src/QueryStatements/CreateTableStatement.php @@ -243,11 +243,15 @@ public function compile(DatabaseDialect $dialect): string ->toString(), ); - $createIndices = arr($this->indexStatements) - ->map(fn (QueryStatement $queryStatement) => str($queryStatement->compile($dialect))->trim()->replace(' ', ' ')) - ->implode(';' . PHP_EOL) - ->append(';'); -var_dump($createTable . PHP_EOL . $createIndices); - return $createTable . PHP_EOL . $createIndices; + if ($this->indexStatements !== []) { + $createIndices = PHP_EOL . arr($this->indexStatements) + ->map(fn (QueryStatement $queryStatement) => str($queryStatement->compile($dialect))->trim()->replace(' ', ' ')) + ->implode(';' . PHP_EOL) + ->append(';'); + } else { + $createIndices = ''; + } + + return $createTable . $createIndices; } }