pgschema icon indicating copy to clipboard operation
pgschema copied to clipboard

Statement order causes "relation does not exist" error

Open akhayyat opened this issue 3 months ago • 0 comments

Having a table and two functions, where the table depends on one function, and is dependent upon by the other function, appears to trip the ordering logic, since it attempts to execute all functions first.

Here is a minimal example that reproduces the issue:

CREATE FUNCTION random_id()
RETURNS bigint LANGUAGE sql AS $$
    SELECT CAST(1000000000 + floor(random() * 9000000000) AS bigint);
$$;

CREATE TABLE x (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    public_id text NOT NULL UNIQUE DEFAULT random_id(),
    name text NOT NULL UNIQUE,
    flag boolean NOT NULL DEFAULT FALSE
);

CREATE FUNCTION x_is_flagged(id bigint)
RETURNS boolean LANGUAGE sql STABLE AS $$
    SELECT x.flag FROM x WHERE x.id = id;
$$;

Output of apply:

Plan: 3 to add.

Summary by type:
  functions: 2 to add
  tables: 1 to add

Functions:
  + random_id
  + x_is_flagged

Tables:
  + x

DDL to be executed:
--------------------------------------------------

CREATE OR REPLACE FUNCTION random_id()
RETURNS bigint
LANGUAGE sql
VOLATILE
AS $$
    select CAST(1000000000 + floor(random() * 9000000000) AS bigint);
$$;

CREATE OR REPLACE FUNCTION x_is_flagged(
    id bigint
)
RETURNS boolean
LANGUAGE sql
STABLE
AS $$
    SELECT x.flag FROM x WHERE x.id = id;
$$;

CREATE TABLE IF NOT EXISTS x (
    id bigint GENERATED ALWAYS AS IDENTITY,
    public_id text DEFAULT random_id() NOT NULL,
    name text NOT NULL,
    flag boolean DEFAULT false NOT NULL,
    CONSTRAINT x_pkey PRIMARY KEY (id),
    CONSTRAINT x_name_key UNIQUE (name),
    CONSTRAINT x_public_id_key UNIQUE (public_id)
);

Do you want to apply these changes? (yes/no): yes

Applying changes...

Executing group 1/1...
  Executing 3 statements in implicit transaction
Error: failed to execute concatenated statements in group 1: ERROR: relation "x" does not exist (SQLSTATE 42P01)```

Executing the SQL statements in the order in which they are written at the top succeeds.

akhayyat avatar Aug 06 '26 03:08 akhayyat