'idiomatic way to atomically create a table that as a record that is associated to other tables

I am coming from graph databases and postgres is still super foreign to me.

I have the following tables

CREATE TYPE runnerenum AS ENUM ('runner');

CREATE TABLE IF NOT EXISTS collections (
  collectionid UUID PRIMARY KEY,
  name VARCHAR(256) UNIQUE NOT NULL,
  runner runnerenum NOT NULL,
  runconfig JSONB 
);

CREATE TABLE IF NOT EXISTS namedexprs(
  namedexprid UUID PRIMARY KEY,
  name VARCHAR(256) UNIQUE NOT NULL,
  -- exprid UUID NOT NULL REFERENCES expressions(exprid),
  collectionid UUID NOT NULL REFERENCES collections(collectionid) ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS expressions(
  exprid UUID PRIMARY KEY,
  ast JSONB NOT NULL,
  namedexprid UUID NOT NULL REFERENCES namedexprs(namedexprid) ON DELETE CASCADE
);

My question is what is the idiomatic way to create a collections atomically (while also creating associated expressions and namedexprs). Currently I am executing three separate queries and getting errors because of a foreign key violation.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source