My app has the requirement that every table has a "created_by" column that references to the id column of user table. Even the user table. That means the created_by column would be a circular reference for the user table, so I made created_by default to 0 in this table, and first inserted user with id=0 will be created by himself.
But now I am facing another related issue with the creation of the schema, where referenced column are circular references. This is the simplified schema now:
SET CONSTRAINTS ALL DEFERRED; CREATE TABLE public.user( id int8 NOT NULL, store_id int8, created_by int8 NOT NULL DEFAULT 0, CONSTRAINT user_pk PRIMARY KEY (id), CONSTRAINT user_created_by FOREIGN KEY (created_by) REFERENCES public.user(id) ON DELETE SET DEFAULT, CONSTRAINT user_store_id FOREIGN KEY (store_id) REFERENCES public.store(id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED ) CREATE TABLE public.store( id int8 NOT NULL, created_by int8 NOT NULL, CONSTRAINT store_pk PRIMARY KEY (id), CONSTRAINT store_created_by FOREIGN KEY (created_by) REFERENCES public.user(id) ON DELETE CASCADE ) I get the error that "public.store" table does not exist in the user table creation statement.
This runs in a transaction, and I was under impression that you can defer constraint checks after the transaction ends by using the DEFERRED keywords, but for some reason it does not work. Why is the check is still made in the first create table query?