Skip to content

fix(postgres): move identity sequences past records' ids - #1071

Open
jayhemnani9910 wants to merge 1 commit into
holistics:masterfrom
jayhemnani9910:fix/postgres-records-sync-identity
Open

jayhemnani9910 wants to merge 1 commit into
holistics:masterfrom
jayhemnani9910:fix/postgres-records-sync-identity

Conversation

@jayhemnani9910

Copy link
Copy Markdown
Contributor

Seeding a table that has an auto-increment id with Records gives SQL that loads fine, but the app's first normal insert then fails:

Table users {
  id integer [pk, increment]
  email varchar
}
Records users(id, email) {
  1, 'a@x.com'
  2, 'b@x.com'
}

dbml2sql --postgres writes "id" INTEGER GENERATED BY DEFAULT AS IDENTITY and INSERT INTO "users" ("id", "email") VALUES (1, ...), (2, ...). In PostgreSQL 18, INSERT INTO users (email) VALUES ('c@x.com') then fails with duplicate key value violates unique constraint "users_pkey" because the identity is still at 1. The same happens with serial.

Explicit values don't advance the identity sequence. Each INSERT that sets an increment column is now followed by:

SELECT setval(pg_get_serial_sequence('"users"', 'id'), (SELECT MAX("id") FROM "users"));

This is what pg_dump does. It works for both identity and serial columns, and for tables in a schema.

Test: a new insert_records_increment fixture (identity in public, serial in a schema). It fails on master, and the dbml-core suite passes (527 tests). I loaded its output into PostgreSQL 18: on master the next insert into users fails and shop.orders hands out id 1. With this change they get 3 and 11.

The SQL Server and Oracle exports have the same problem in a different form (they need SET IDENTITY_INSERT and GENERATED BY DEFAULT, respectively). I left those out because I could only test PostgreSQL.

AI tools assisted with this contribution.

Records that set an increment column's value left its identity or
serial sequence at 1, so the next insert without an id failed with a
duplicate key. Each INSERT that sets one is now followed by a setval to
the column's max.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant