I know that PostgreSQL tables that use a SERIAL
primary key end up with an implicit index, sequence and constraint being created by PostgreSQL. The question is how to rename these implicit objects when the table is renamed. Below is my attempt at figuring this out with specific questions at the end.
Given a table such as:
CREATE TABLE foo (
pkey SERIAL PRIMARY KEY,
value INTEGER
);
Postgres outputs:
NOTICE: CREATE TABLE will create implicit sequence "foo_pkey_seq" for serial column "foo.pkey"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "foo_pkey" for table "foo"
Query returned successfully with no result in 52 ms.
pgAdmin III SQL pane shows the following DDL script for the table (decluttered):
CREATE TABLE foo (
pkey serial NOT NULL,
value integer,
CONSTRAINT foo_pkey PRIMARY KEY (pkey )
);
ALTER TABLE foo OWNER TO postgres;
Now rename the table:
ALTER table foo RENAME TO bar;
Query returned successfully with no result in 17 ms.
pgAdmin III:
CREATE TABLE bar (
pkey integer NOT NULL DEFAULT nextval('foo_pkey_seq'::regclass),
value integer,
CONSTRAINT foo_pkey PRIMARY KEY (pkey )
);
ALTER TABLE bar OWNER TO postgres;
Note the extra DEFAULT nextval('foo_pkey_seq'::regclass),
this means that renaming the table does not rename the sequence for the primary keys but now we have this explicit nextval()
.
Now rename the sequence:
I want to keep the database naming consistent so I tried:
ALTER SEQUENCE foo_pkey_seq RENAME TO bar_pkey_seq;
Query returned successfully with no result in 17 ms.
pgAdmin III:
CREATE TABLE bar (
pkey serial NOT NULL,
value integer,
CONSTRAINT foo_pkey PRIMARY KEY (pkey )
);
ALTER TABLE bar OWNER TO postgres;
The DEFAULT nextval('foo_pkey_seq'::regclass),
is gone.
QUESTIONS
- Why did the
DEFAULT nextval('foo_pkey_seq'::regclass)
statement appear and disappear? - Is there a way to rename the table and have the primary key sequence renamed at the same time?
- Is it safe to rename the table then sequence while clients are connected to the database, are there any concurrency issues?
- How does postgres know which sequence to use? Is there a database trigger being used internally? Is there anything else to rename other than the table and the sequence?
- What about the implicit index created by a primary key? Should that be renamed? If so, how can that be done?
- What about the constraint name above? It is still
foo_pkey
. How is a constraint renamed?