pg_dump serial datatype issues

auto-increment, pg-dump, postgresql

Solution

From docs:

The data types `smallserial`, `serial` and `bigserial` are not true types, but merely a notational convenience for creating unique identifier columns (similar to the AUTO_INCREMENT property supported by some other databases). In the current implementation, specifying:

CREATE TABLE tablename (
    colname SERIAL
);

is equivalent to specifying:

CREATE SEQUENCE tablename_colname_seq;
CREATE TABLE tablename (
    colname integer NOT NULL DEFAULT nextval('tablename_colname_seq')
);
ALTER SEQUENCE tablename_colname_seq OWNED BY tablename.colname;

Thus, we have created an integer column and arranged for its default values to be assigned from a sequence generator. A NOT NULL constraint is applied to ensure that a null value cannot be inserted. (In most cases you would also want to attach a UNIQUE or PRIMARY KEY constraint to prevent duplicate values from being inserted by accident, but this is not automatic.) Lastly, the sequence is marked as "owned by" the column, so that it will be dropped if the column or table is dropped.

Problem

Could someone explain to me why a PostgreSQL table created with the following scripts: ``` CREATE TABLE users ( "id" serial NOT NULL, "name" character varying(150) NOT NULL, "surname" character varying (250) NOT NULL, "dept_id" integer NOT NULL, CONSTRAINT users_pkey PRIMARY KEY ("id") ) ``` gets dumped by `pg_dump` in the following format: ``` CREATE TABLE users( "id" integer NOT NULL, "name" character varying(150) NOT NULL, "surname" character varying (250) NOT NULL, "dept_id" integer NOT NULL ); ALTER TABLE users OWNER TO postgres; CREATE SEQUENCE "users_id_seq" START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE "users_id_seq" OWNER TO postgres; ALTER SEQUENCE "users_id_seq" OWNED BY users."id"; ALTER TABLE ONLY users ADD CONSTRAINT users_pkey PRIMARY KEY ("id"); ``` Obviously the above is only a small extract from the dump file. Why does a `pg_dump` convert the datatypes serial to integer? When I restore the database from the dumped SQL file, it pretty much becomes useless because the autoincrementation stops working, and when adding new records from a front-end form, it fails with message along the lines 'id field cannot be empty', obviously because it is a primary key set to not null, but auto-incrementation should kick in and populate the field with the next value in the sequence. Am I missing something here?

Original source

Related problems