PostgreSQL – Force Create Foreign Key Without Reference

foreign keypostgresql

I have two tables foo and bar, bar has column a that references foo.id as a foreign key. When creating table bar before foo, the error column "a" referenced in foreign key constraint does not exist is given. This is obvious and intended. However, the creation of these two tables are handled by two different entities that of which I cannot control. It's guaranteed that no data will be added to either table until both are successfully created, but the creation itself may happen out-of-order. Is there a way to force the creation of bar even though foo does not exist?

Best Answer

As a quick fix. you can add a semaphore that prevents the creation of bar before foo exists. Pseudocode:

WHILE true:
    n = (select count(1) 
         from information_schema.tables 
         where table_name = 'foo')
    if n == 1:
        break
    sleep 1

create table bar ...  

In the long run, consider how you should handle dependencies between different parts of the system, that are created independently of each other