pgschema icon indicating copy to clipboard operation
pgschema copied to clipboard

CREATE INDEX CONCURRENTLY emitted on partitioned parents (apply fails with SQLSTATE 0A000)

Open kallanb opened this issue 7 months ago • 0 comments

Type: bug Severity: apply-blocking Affects: v1.9.0, current main

Summary

pgschema's online-DDL rewrite emits CREATE INDEX CONCURRENTLY for any new index on an existing table, including indexes whose target is a partitioned parent (pg_class.relkind = 'p'). PostgreSQL rejects CREATE INDEX CONCURRENTLY on partitioned parents — see PG 17 docs, CREATE INDEX: "Concurrent builds for indexes on partitioned tables are currently not supported." Result: pgschema apply fails with SQLSTATE 0A000.

Repro

Verified empirically against pgschema v1.9.0 + PostgreSQL 17 on 2026-04-28.

Step 1 — initial state:

-- schema.sql (initial)
CREATE TABLE events (
    id        bigint NOT NULL,
    occurred  timestamptz NOT NULL,
    payload   jsonb,
    PRIMARY KEY (id, occurred)
) PARTITION BY RANGE (occurred);

CREATE TABLE events_2026_04 PARTITION OF events
    FOR VALUES FROM ('2026-04-01') TO ('2026-05-01');

pgschema apply succeeds. Verify events.relkind = 'p'.

Step 2 — add an index on the partitioned parent:

CREATE INDEX events_payload_idx ON events USING gin (payload);

Step 3 — pgschema plan emits (verbatim):

CREATE INDEX CONCURRENTLY IF NOT EXISTS events_payload_idx ON events USING gin (payload);

Step 4 — pgschema apply --auto-approve fails (verbatim):

Executing group 1/6...
  Executing 2 statements in implicit transaction

Executing group 2/6...
  Executing 1 statements in implicit transaction
Error: failed to execute concatenated statements in group 2: ERROR: cannot create index on partitioned table "events" concurrently (SQLSTATE 0A000)

Expected

For partitioned parents, emit CREATE INDEX (without CONCURRENTLY). The brief AccessExclusiveLock on the parent during a non-concurrent build is acceptable; the alternative (CREATE INDEX ON ONLY <parent> followed by per-child CONCURRENTLY then ATTACH PARTITION) is more complex and not what users expect from declarative SQL.

Root cause

internal/plan/rewrite.go:110-129 — generateIndexRewrite unconditionally calls generateIndexSQL(index, true) (the second arg is isConcurrent). generateIndexSQL at line 384-393 unconditionally appends CONCURRENTLY whenever that flag is true. No IsPartitioned check.

The IR already carries the information needed: ir.Table.IsPartitioned exists and is correctly consulted in internal/diff/table.go:628 for table emit. The index path just doesn't read it.

Suggested fix (~5 lines)

In generateIndexRewrite, look up index.Table in the schema's IR. If Table.IsPartitioned == true, emit a synchronous CREATE INDEX as a single step (no CONCURRENTLY, no wait directive) instead of the concurrent + wait pair. Alternatively: pass IsPartitioned through the diff's Source so the rewrite can branch without an extra IR lookup.

kallanb avatar Apr 28 '26 06:04 kallanb