Skip to content
This repository has been archived by the owner on Aug 3, 2024. It is now read-only.

Commit

Permalink
replaced invalid constraint with on insert trigger
Browse files Browse the repository at this point in the history
  • Loading branch information
dvalnn committed Feb 23, 2024
1 parent ca63058 commit d4507ae
Showing 1 changed file with 21 additions and 7 deletions.
28 changes: 21 additions & 7 deletions migrations/003_t_orders.sql
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,27 @@ CREATE TABLE IF NOT EXISTS orders(
FOREIGN KEY(work_piece) REFERENCES pieces(id)
ON DELETE CASCADE,
FOREIGN KEY(client_id) REFERENCES clients(id)
ON DELETE CASCADE
ON DELETE CASCADE,

UNIQUE(client_id, order_number)
UNIQUE(client_id, order_number),

CONSTRAINT check_work_piece_kind CHECK (
work_piece IN (
SELECT id FROM pieces WHERE kind = 'final product'
)
)
);

CREATE FUNCTION check_work_piece_kind() RETURNS trigger AS
$$
BEGIN
IF NOT EXISTS (
SELECT 1
FROM pieces
WHERE id = NEW.work_piece AND kind = 'final product'
) THEN
RAISE EXCEPTION 'Work piece must be a final product.';
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER check_work_piece_kind_trigger
BEFORE INSERT ON your_table
FOR EACH ROW EXECUTE PROCEDURE check_work_piece_kind();

0 comments on commit d4507ae

Please sign in to comment.