pgschema icon indicating copy to clipboard operation
pgschema copied to clipboard

Wrong order when using function for default value

Open vmsp opened this issue 1 year ago • 0 comments

I have this db/schema.sql:

create function nanoid(size int default 21) returns text
language plpgsql leakproof parallel safe as $$
declare
  alphabet constant text :=
    'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
  bytes bytea := gen_random_bytes(size);
  result text := '';
  i int;
  idx int;
begin
  for i in 0..(size - 1) loop
    idx := (get_byte(bytes, i) & 63) + 1;
    result := result || substr(alphabet, idx, 1);
  end loop;
  return result;
end; $$;

create table whatever (
  pid text unique not null default nanoid() unique
);

And when I run go tool pgschema apply --file db/schema.sql on an empty database I get this:

Plan: 2 to add.

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

Functions:
  + nanoid

Tables:
  + whatever

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

CREATE TABLE IF NOT EXISTS whatever (
    pid text DEFAULT public.nanoid() NOT NULL,
    CONSTRAINT whatever_pid_key UNIQUE (pid)
);

CREATE OR REPLACE FUNCTION nanoid(
    size integer DEFAULT 21
)
RETURNS text
LANGUAGE plpgsql
SECURITY INVOKER
VOLATILE
AS $$
declare
  alphabet constant text :=
    'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
  bytes bytea := gen_random_bytes(size);
  result text := '';
  i int;
  idx int;
begin
  for i in 0..(size - 1) loop
    idx := (get_byte(bytes, i) & 63) + 1;
    result := result || substr(alphabet, idx, 1);
  end loop;
  return result;
end;
$$;

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

Applying changes...

Executing group 1/1...
  Executing 2 statements in implicit transaction
Error: failed to execute concatenated statements in group 1: ERROR: function public.nanoid() does not exist (SQLSTATE 42883)

I also just noticed that leakproof parallel safe is missing from the plan.

Thanks!

vmsp avatar Nov 27 '25 15:11 vmsp