#2492·atlas

Postgres serial and long table name

Author: louisdussarpsCreated Jan 31, 2024Updated Sep 29, 2026

Hello, I am utilizing Atlas Go to inspect a PostgreSQL schema, aiming to apply the schema elsewhere in an empty database. However, I encountered a scenario that leads to inconsistency in the schema inspection and apply process

Problem and Reproduction Steps:

Consider the following schema: :

sql
CREATE SCHEMA IF NOT EXISTS "public";
COMMENT ON SCHEMA "public" IS 'standard public schema';
CREATE TABLE "public"."a_long_name_that_contains_more_than_56_char_and_less_63_" (
  "id" serial NOT NULL
);
CREATE TABLE "public"."a_long_name_that_contains_more_than_56_char_and_less_63_bis" (
  "id" serial NOT NULL
);

Applying this schema to an empty database and then executing atlas schema inspect results in:

sql
-- Add new schema named "public"
CREATE SCHEMA IF NOT EXISTS "public";
-- Set comment to schema: "public"
COMMENT ON SCHEMA "public" IS 'standard public schema';
-- Create "a_long_name_that_contains_more_than_56_char_and_less_63_" table
CREATE TABLE "public"."a_long_name_that_contains_more_than_56_char_and_less_63_" (
  "id" serial NOT NULL
);
-- Create "a_long_name_that_contains_more_than_56_char_and_less_63_bis" table
CREATE TABLE "public"."a_long_name_that_contains_more_than_56_char_and_less_63_bis" (
  "id" integer NOT NULL DEFAULT nextval('a_long_name_that_contains_more_than_56_char_and_less_63_id_seq1'::regclass)
);

Note that the second serial is mentioned as nextval(sequence) instead of "serial". This discrepancy causes issues when attempting to reapply the schema, resulting in the following error during atlas schema apply:

ERROR: relation "a_long_name_that_contains_more_than_56_char_and_less_63_id_seq1" does not exist

Reason

By default, PostgreSQL limits the number of identifier characters to 63. When the serial keyword is used, it creates a sequence named "table_name_field_name_seq." If the table_name is too long, PostgreSQL truncates the name, risking name collisions and generating sequences with names like "table_name_truncated_field_name_seq1." However, Atlas fails to identify such sequences as serial. https://github.com/ariga/atlas/blob/5c84752894fc61594f9281d74c1e6f72b6f27ba3/sql/postgres/inspect.go#L747C1-L747C116

go
var reNextval = regexp.MustCompile(`(?i) *nextval\('(?:"?[\w$]+"?\.)?"?([\w$]+_[\w$]+_seq)"?'(?:::regclass)*\) *$`)

Solution

To address this issue, the regular expression in the Atlas code can be modified to:

go
var reNextval = regexp.MustCompile(`(?i) *nextval\('(?:"?[\w$]+"?\.)?"?([\w$]+_[\w$]+_seq[0-9]*)"?'(?:::regclass)*\) *$`)