gpt4 book ai didi

postgresql - 使数据库中的所有表都未登录

转载 作者:行者123 更新时间:2023-11-29 12:55:42 25 4
gpt4 key购买 nike

我想通过使所有表UNLOGGED 来减少本地测试执行时间。我想编写 sql 脚本,它将在所有转换后运行并使它们UNLOGGED。但我发现问题 - 表与 FK 相互关联,所以 postgresql 禁止 make table UNLOGGED(通过 ALTER)如果它与其他表相关还不是 UNLOGGED

有没有更好的方法然后以正确的顺序列出所有 ALTER - 我有超过 150 个表?例如,将其应用于数据库级别。

最佳答案

恐怕您必须按正确的顺序更改它们。您可以选择https://www.postgresql.org/docs/current/static/catalog-pg-constraint.html并首先循环引用表,然后更改其余部分:

begin;
do
$$
declare
_r record;
_t text;
begin
for _r in (
select relname,conrelid
from pg_constraint
join pg_class c on c.oid = conrelid
where confkey is not null
order by conrelid desc
-- Order by oid with logic that you should start from latest added objects to earliest - of course it does not garantee anything
) loop
_t := format('alter table %I set unlogged',_r.relname);
raise info '%',_t;
execute _t;
end loop;

for _r in (select tablename from pg_tables where tablename like 's%' and schemaname = 'public') loop
_t := format('alter table %I set unlogged',_r.tablename);
raise info '%',_t;
execute _t;
end loop;

end;
$$
;
rollback;

如果你有递归 FK,无论如何它都会失败:

t=# create table s134(i int primary key, e int);
CREATE TABLE
t=# create table s135(i int references s134(i), e int primary key);
CREATE TABLE
t=# alter table s134 add constraint c1 foreign key (e) references s135(e);
ALTER TABLE
t=# alter table s134 set unlogged;
ERROR: could not change table "s134" to unlogged because it references logged table "s135"
t=# alter table s135 set unlogged;
ERROR: could not change table "s135" to unlogged because it references logged table "s134"

但我相信你不会以任何方式实现这一目标。

另外不要忘记,在不正常关机或失败后,未记录的表将被截断。

最后你说“在所有转换之后”——如果你创建、转换等,也许你应该不记录地创建它们?..

关于postgresql - 使数据库中的所有表都未登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43975050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com