如何在 Postgresql 中备份序列?
How to backup Sequences in Postgresql?
我们可以将序列备份并在其他数据库中使用吗?
下面SQL将return列出SQL可以在目标上执行的语句以重置序列
的值
SELECT 'ALTER SEQUENCE ' || c.relname || ' RESTART WITH ' || nextval(c.relname::regclass) || ';'
FROM pg_class c WHERE c.relkind = 'S';
SELECT 'ALTER SEQUENCE ' || s.relname || ' RESTART WITH ' || t.reltuples + 1 || ';'
FROM pg_class s
JOIN pg_depend d ON d.objid = s.oid
JOIN pg_class t ON d.objid = s.oid AND d.refobjid = t.oid
JOIN pg_attribute a ON (d.refobjid, d.refobjsubid) = (a.attrelid, a.attnum)
JOIN pg_namespace n ON n.oid = s.relnamespace
WHERE s.relkind = 'S' AND n.nspname = 'public'
使用pg_dump
不要编写自己的序列转储代码。而是使用 PostgreSQL 的 pg_dump
和 pg_dumpall
CREATE TABLE foo ( id serial PRIMARY KEY, other int );
INSERT INTO foo (other) VALUES (1),(2),(3);
然后用pg_dump
或pg_dumpall
,
转储
$ pg_dump -t foo | grep -i pg_catalog.setval | grep "'public.foo"
SELECT pg_catalog.setval('public.foo_id_seq', 3, true);
序列是 PostgreSQL 特定的。这会转储 PostgreSQL 代码。这个问题很旧,但是您可以将序列迁移到 IDENTITY COLUMNS
而不是使用序列。然后他们将在其他 SQL 兼容的数据库中工作。
迁移到标识列
CREATE TABLE foo (
id int PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
other int
);
INSERT INTO foo (other) VALUES (1),(2),(3);
然后你可以转储它,
pg_dump -t foo | perl -nE'print if /GENERATED BY/ .. /\);/'
你会得到类似的东西,
ALTER TABLE public.foo ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY (
SEQUENCE NAME public.foo_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1
);
这将几乎与MySQL, SQL Server, and Oracle
一起工作
我们可以将序列备份并在其他数据库中使用吗?
下面SQL将return列出SQL可以在目标上执行的语句以重置序列
的值SELECT 'ALTER SEQUENCE ' || c.relname || ' RESTART WITH ' || nextval(c.relname::regclass) || ';'
FROM pg_class c WHERE c.relkind = 'S';
SELECT 'ALTER SEQUENCE ' || s.relname || ' RESTART WITH ' || t.reltuples + 1 || ';'
FROM pg_class s
JOIN pg_depend d ON d.objid = s.oid
JOIN pg_class t ON d.objid = s.oid AND d.refobjid = t.oid
JOIN pg_attribute a ON (d.refobjid, d.refobjsubid) = (a.attrelid, a.attnum)
JOIN pg_namespace n ON n.oid = s.relnamespace
WHERE s.relkind = 'S' AND n.nspname = 'public'
使用pg_dump
不要编写自己的序列转储代码。而是使用 PostgreSQL 的 pg_dump
和 pg_dumpall
CREATE TABLE foo ( id serial PRIMARY KEY, other int );
INSERT INTO foo (other) VALUES (1),(2),(3);
然后用pg_dump
或pg_dumpall
,
$ pg_dump -t foo | grep -i pg_catalog.setval | grep "'public.foo"
SELECT pg_catalog.setval('public.foo_id_seq', 3, true);
序列是 PostgreSQL 特定的。这会转储 PostgreSQL 代码。这个问题很旧,但是您可以将序列迁移到 IDENTITY COLUMNS
而不是使用序列。然后他们将在其他 SQL 兼容的数据库中工作。
迁移到标识列
CREATE TABLE foo (
id int PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
other int
);
INSERT INTO foo (other) VALUES (1),(2),(3);
然后你可以转储它,
pg_dump -t foo | perl -nE'print if /GENERATED BY/ .. /\);/'
你会得到类似的东西,
ALTER TABLE public.foo ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY (
SEQUENCE NAME public.foo_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1
);
这将几乎与MySQL, SQL Server, and Oracle
一起工作