Thursday, January 04, 2007

Fix autonumbering sequences when backing a single table in postgres

yea, the sequences are never really captured on a database dump of just one table, need to do an entire backup.
in general, when i want to move a 1 table, i use the \d table_name;
then i write / copy the structure,
then create it with another psql to other db.

in general, when i want to move a 1 table, i use the \d table_name;
then i write / copy the structure,
then create it with another psql to other db.

So to fix id problems when backing a table :
select max (id) from table;

alter sequence my_sequence restart maxid+1;


the thing about a table is in the general can have (constraints, such as primary keys, foreign keys, that reference other tables), indexes(for finding data faster), triggers (calls a stored procedure), and rules (that rewrite operations based on data, like triggers)
but most people just have tables, maybe with a primary key default nextval('a_sequnce'), so it is a lot simpler
so in psql
\d tablename
dumps the structure of the table to the text console
---------
well like here
\d task
Table "task.task"
Column | Type | Modifiers
----------------+-------------------+---------------------------------------------------
id | bigint | not null default nextval('task_id_seq'::regclass)
entry_date | date |
completed_date | date |
project_id | bigint |
name | character varying |
description | text |
parent_id | bigint |
Indexes:
"task_pk" PRIMARY KEY, btree (id)
Foreign-key constraints:
"_parent_id" FOREIGN KEY (parent_id) REFERENCES task(id)
"_project_id" FOREIGN KEY (project_id) REFERENCES project(id)
this shows me the table "task" contains id, entry_date, completed_date,,...
and their types, an then i see the constriants, like what foreign key it references, so i know that this table depends on another table.
i then have a couple minutes in a text editor and make this into
CREATE TABLE TASK (ID BIGINT NOT NULL DEFAULT NEXTVAL('task_id_seq'),
entry_date date,
etc.
then use that to create teh table in new db.
i guess it is hte manual old-school way to d it.
then when the new table exists,
(in both new, and old databases,)
i can type
psql -h host1 -U user1 -c "copy task to stdout csv" | psql -h host2 -U user2 -c "copy task from stdin csv"
or i guess you can do a copy out to a file first, and then copy into the second db by cat the file.
like how you would install that country data, i emailed to you.
for more info on the copy command, "\h copy" from the psql prompt
lol, see, thats why i never use a "GUI", becuse the command line is always better than any GUI.
so then after i get the table created, i do the create sequence task_id_seq start nnnnn;
actually, if you ran the sql propertly, it doesnt let you create the table without having the sequence ther..
so i would then have the sequence manually created, and to start at next higher value.

No comments: