65 lines
2.6 KiB
SQL
65 lines
2.6 KiB
SQL
-- Convert single constructeur relation to many-to-many for machines, composants et pièces
|
|
|
|
-- Machines → Constructeurs
|
|
ALTER TABLE "machines" DROP CONSTRAINT IF EXISTS "machines_constructeurId_fkey";
|
|
|
|
CREATE TABLE "_MachineConstructeurs" (
|
|
"A" TEXT NOT NULL,
|
|
"B" TEXT NOT NULL,
|
|
CONSTRAINT "_MachineConstructeurs_A_fkey" FOREIGN KEY ("A") REFERENCES "machines"("id") ON DELETE CASCADE ON UPDATE CASCADE,
|
|
CONSTRAINT "_MachineConstructeurs_B_fkey" FOREIGN KEY ("B") REFERENCES "constructeurs"("id") ON DELETE CASCADE ON UPDATE CASCADE
|
|
);
|
|
|
|
CREATE UNIQUE INDEX "_MachineConstructeurs_AB_unique" ON "_MachineConstructeurs"("A", "B");
|
|
CREATE INDEX "_MachineConstructeurs_B_index" ON "_MachineConstructeurs"("B");
|
|
|
|
INSERT INTO "_MachineConstructeurs" ("A", "B")
|
|
SELECT "id", "constructeurId"
|
|
FROM "machines"
|
|
WHERE "constructeurId" IS NOT NULL
|
|
ON CONFLICT DO NOTHING;
|
|
|
|
ALTER TABLE "machines" DROP COLUMN IF EXISTS "constructeurId";
|
|
|
|
-- Composants → Constructeurs
|
|
ALTER TABLE "composants" DROP CONSTRAINT IF EXISTS "composants_constructeurId_fkey";
|
|
|
|
CREATE TABLE "_ComposantConstructeurs" (
|
|
"A" TEXT NOT NULL,
|
|
"B" TEXT NOT NULL,
|
|
CONSTRAINT "_ComposantConstructeurs_A_fkey" FOREIGN KEY ("A") REFERENCES "composants"("id") ON DELETE CASCADE ON UPDATE CASCADE,
|
|
CONSTRAINT "_ComposantConstructeurs_B_fkey" FOREIGN KEY ("B") REFERENCES "constructeurs"("id") ON DELETE CASCADE ON UPDATE CASCADE
|
|
);
|
|
|
|
CREATE UNIQUE INDEX "_ComposantConstructeurs_AB_unique" ON "_ComposantConstructeurs"("A", "B");
|
|
CREATE INDEX "_ComposantConstructeurs_B_index" ON "_ComposantConstructeurs"("B");
|
|
|
|
INSERT INTO "_ComposantConstructeurs" ("A", "B")
|
|
SELECT "id", "constructeurId"
|
|
FROM "composants"
|
|
WHERE "constructeurId" IS NOT NULL
|
|
ON CONFLICT DO NOTHING;
|
|
|
|
ALTER TABLE "composants" DROP COLUMN IF EXISTS "constructeurId";
|
|
|
|
-- Pièces → Constructeurs
|
|
ALTER TABLE "pieces" DROP CONSTRAINT IF EXISTS "pieces_constructeurId_fkey";
|
|
|
|
CREATE TABLE "_PieceConstructeurs" (
|
|
"A" TEXT NOT NULL,
|
|
"B" TEXT NOT NULL,
|
|
CONSTRAINT "_PieceConstructeurs_A_fkey" FOREIGN KEY ("A") REFERENCES "pieces"("id") ON DELETE CASCADE ON UPDATE CASCADE,
|
|
CONSTRAINT "_PieceConstructeurs_B_fkey" FOREIGN KEY ("B") REFERENCES "constructeurs"("id") ON DELETE CASCADE ON UPDATE CASCADE
|
|
);
|
|
|
|
CREATE UNIQUE INDEX "_PieceConstructeurs_AB_unique" ON "_PieceConstructeurs"("A", "B");
|
|
CREATE INDEX "_PieceConstructeurs_B_index" ON "_PieceConstructeurs"("B");
|
|
|
|
INSERT INTO "_PieceConstructeurs" ("A", "B")
|
|
SELECT "id", "constructeurId"
|
|
FROM "pieces"
|
|
WHERE "constructeurId" IS NOT NULL
|
|
ON CONFLICT DO NOTHING;
|
|
|
|
ALTER TABLE "pieces" DROP COLUMN IF EXISTS "constructeurId";
|