2024-05-27 11:30:12 +02:00

48 lines
1.4 KiB
SQL

/*
Warnings:
- Added the required column `office_uid` to the `customers` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE "customers" ADD COLUMN "office_uid" VARCHAR(255) NOT NULL;
-- Set the office_uid for existing rows based on the office with "idNot" = '0000'
UPDATE customers
SET office_uid = (
SELECT uid
FROM offices
WHERE "idNot" = '0000'
);
-- Alter the column to be NOT NULL
ALTER TABLE customers
ALTER COLUMN office_uid SET NOT NULL;
-- Create a temporary table to store the mapping
CREATE TEMPORARY TABLE customer_office_update AS
SELECT c.uid AS customer_uid, of.office_uid
FROM customers c
JOIN "_OfficeFolderHasCustomers" ofhc ON c.uid = ofhc."A"
JOIN office_folders of ON ofhc."B" = of.uid;
-- Update customers with the corresponding office_uid
UPDATE customers
SET office_uid = (
SELECT office_uid
FROM customer_office_update
WHERE customer_office_update.customer_uid = customers.uid
);
-- Drop the temporary table
DROP TABLE customer_office_update;
-- Add the foreign key constraint
ALTER TABLE customers
ADD CONSTRAINT fk_customers_office
FOREIGN KEY (office_uid) REFERENCES offices(uid)
ON DELETE CASCADE;
-- AddForeignKey
ALTER TABLE "customers" ADD CONSTRAINT "customers_office_uid_fkey" FOREIGN KEY ("office_uid") REFERENCES "offices"("uid") ON DELETE CASCADE ON UPDATE CASCADE;