pg-schema-diff icon indicating copy to clipboard operation
pg-schema-diff copied to clipboard

[BUG] Functions with knowable dependencies are created before the tables they depend on

Open ellis opened this issue 3 months ago • 0 comments

Describe the bug

When pg-schema-diff generates a plan, functions defined with RETURNS SETOF "MyTable" are scheduled before the referenced table. The dependency exists in PostgreSQL's pg_depend, so the information is available.

Expected behavior

pg-schema-diff should detect table dependencies referenced by functions and ensure that the functions are created after their dependencies.

To Reproduce

  1. Add the schema below to a migration file.
  2. Run pg-schema-diff (plan/apply) against an empty database.
  3. Observe ERROR: relation "JobRun" does not exist because the function runs before the table is created.
-- File: schema.sql
CREATE TABLE "JobRun" (
  "runId"  BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
  "type"   TEXT NOT NULL,
  "status" TEXT NOT NULL
);

CREATE OR REPLACE FUNCTION "jobRunClaimNext"(p_types TEXT[])
RETURNS SETOF "JobRun"
LANGUAGE sql
AS $$
  SELECT r.*
  FROM "JobRun" AS r
  WHERE r."status" = 'PENDING'
    AND r."type" = ANY (p_types)
  LIMIT 1;
$$;

Context

pg-schema-diff version: v1.0.2 pg-schema-diff usage: CLI Postgres version: 17 pg_dump of database: N/A

Possible solution plan

I've never touched a line of Go code, so I passed the above info to Claude, and here's a summary of what it says:

  • function_sql_vertex_generator.go: Lines 81-100: GetAddAlterDependencies only tracks function-to-function dependencies via DependsOnFunctions
  • No mechanism to track table references in function bodies
  • Query pg_depend to find actual table dependencies (similar to GetViews)
  • Add a TableDependencies field to schema.Function (like View.TableDependencies)
  • Extend GetDependsOnFunctions query or create a new GetDependsOnTables query
  • Use these dependencies in GetAddAlterDependencies

Alternatively, if there were a way to impose order from the command line or via the naming of the .sql schemas, that would work too.

ellis avatar Oct 01 '25 09:10 ellis