pgschema icon indicating copy to clipboard operation
pgschema copied to clipboard

INCLUDE columns dropped when adding or rebuilding an index via CREATE INDEX CONCURRENTLY

Open iengai opened this issue 4 months ago • 0 comments

What happens

When an index that has an INCLUDE clause is added to a table that already exists, or an existing index is rebuilt, the generated plan uses CREATE INDEX CONCURRENTLY and leaves the INCLUDE clause out. The index that gets created has no covering columns.

Since the desired schema still declares the INCLUDE columns, the next plan flags the same index again and apply rebuilds it, again without the INCLUDE. It never settles.

Indexes created as part of a brand new table in the same plan keep their INCLUDE columns (that path uses a plain CREATE INDEX). So this only shows up when the target table already exists, which is the normal case for adding an index in production.

Tested on 1.9.0, 1.11.0 and 1.12.0, all the same. (1.8.0 has the older dump problem from #385 instead.)

Repro

docker run -d --name pg -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=repro -p 55432:5432 postgres:15
docker exec pg psql -U postgres -d repro -c "CREATE SCHEMA mini;"
export PGPASSWORD=postgres
CONN="--host localhost --port 55432 --user postgres --db repro --sslmode disable --schema mini"

# the table exists first, without the covering index
cat > base.sql <<'SQL'
CREATE TABLE IF NOT EXISTS t (id integer NOT NULL, a integer, b integer, CONSTRAINT t_pk PRIMARY KEY (id));
SQL

# desired state adds a covering index
cat > full.sql <<'SQL'
CREATE TABLE IF NOT EXISTS t (id integer NOT NULL, a integer, b integer, CONSTRAINT t_pk PRIMARY KEY (id));
CREATE INDEX IF NOT EXISTS t_cov ON t (a) INCLUDE (b);
SQL

pgschema apply $CONN --file base.sql --auto-approve
pgschema plan  $CONN --file full.sql --output-sql /dev/stdout
# -> CREATE INDEX CONCURRENTLY IF NOT EXISTS t_cov ON mini.t (a);   <-- INCLUDE (b) is missing

pgschema apply $CONN --file full.sql --auto-approve
docker exec pg psql -U postgres -d repro -c \
  "SELECT indexdef FROM pg_indexes WHERE indexname='t_cov';"
# -> CREATE INDEX t_cov ON mini.t USING btree (a)                   <-- INCLUDE (b) gone

pgschema plan  $CONN --file full.sql --output-sql /dev/stdout
# -> not empty: it wants to rebuild t_cov again

Expected

t_cov ends up as (a) INCLUDE (b), and the second plan reports no changes.

Actual

t_cov ends up as (a). Every plan wants to rebuild it and every apply rebuilds it, without ever adding the INCLUDE back.

Notes

This looks related to #385 / #390, but that fix was on the dump output and the diff detection. The CREATE INDEX CONCURRENTLY ... _pgschema_new string that the add/rebuild path emits still drops the INCLUDE. There doesn't seem to be a flag to turn the concurrent path off, so I couldn't find a way around it.

Environment

  • pgschema 1.11.0 and 1.12.0, darwin/arm64
  • PostgreSQL 15

iengai avatar Jul 07 '26 04:07 iengai