Files
tonehaus/migrations/Version20251114113000.php
boris cd04fa5212
All checks were successful
CI - Build Tonehaus Docker image / tonehaus-ci-build (push) Successful in 2m17s
CRUD Albums + Spotify API requests into DB.
2025-11-20 19:54:31 +00:00

63 lines
1.8 KiB
PHP

<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20251114113000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Normalize reviews: add album_id FK, backfill from albums.spotify_id';
}
public function up(Schema $schema): void
{
// Add nullable album_id first
$this->addSql('ALTER TABLE reviews ADD album_id INT DEFAULT NULL');
$this->addSql('ALTER TABLE reviews ADD CONSTRAINT FK_6970EF78E0C31AF9 FOREIGN KEY (album_id) REFERENCES albums (id) ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE');
$this->addSql('CREATE INDEX IDX_6970EF78E0C31AF9 ON reviews (album_id)');
// Backfill using existing spotify_album_id if both columns exist
// Some environments may not have the legacy column; guard with DO blocks
$this->addSql(<<<'SQL'
DO $$
BEGIN
IF EXISTS (
SELECT 1
FROM information_schema.columns
WHERE table_name='reviews' AND column_name='spotify_album_id'
) THEN
UPDATE reviews r
SET album_id = a.id
FROM albums a
WHERE a.spotify_id = r.spotify_album_id
AND r.album_id IS NULL;
END IF;
END $$;
SQL);
// Optionally set NOT NULL if all rows are linked
$this->addSql(<<<'SQL'
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM reviews WHERE album_id IS NULL) THEN
ALTER TABLE reviews ALTER COLUMN album_id SET NOT NULL;
END IF;
END $$;
SQL);
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE reviews DROP CONSTRAINT FK_6970EF78E0C31AF9');
$this->addSql('DROP INDEX IF EXISTS IDX_6970EF78E0C31AF9');
$this->addSql('ALTER TABLE reviews DROP COLUMN album_id');
}
}