gpt4 book ai didi

postgresql - 如何在 Postgres 中实现清除 os 软删除记录?

转载 作者:行者123 更新时间:2023-11-29 14:37:47 25 4
gpt4 key购买 nike

在我的 Postgres 9.4 数据库中,我有以下触发器/函数,它实现了“软删除”功能:

ALTER TABLE my_schema.my_table
ADD COLUMN delete_ind integer


CREATE OR REPLACE FUNCTION trigger_mytable_soft_delete()
RETURNS trigger AS $$
DECLARE
command text := ' SET delete_ind = 1 WHERE uuid_col = $1';
BEGIN
EXECUTE 'UPDATE "my_schema"."my_table"' || TG_TABLE_NAME || command USING OLD.uuid_col;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;


CREATE TRIGGER my_table_soft_delete_trigger
BEFORE DELETE ON "my_schema"."my_table"
FOR EACH ROW EXECUTE PROCEDURE trigger_mytable_soft_delete();

上面的代码为我提供了“软删除”功能,但是,它也阻止我实际删除/清除那些已标记为已删除的行。

新的期望行为是让这个删除函数检查 delete_ind 字段的值,如果它已经设置为 1,则实际永久清除该行。

正确的条件语法是什么,它要么设置 delete_ind 的值。或者根据 delete_ind 列的当前值实际删除有问题的行?

最佳答案

可以通过对您的函数进行相对较小的修改来完成:

CREATE OR REPLACE FUNCTION trigger_mytable_soft_delete()  
RETURNS trigger AS
$$
BEGIN
if OLD.delete_ind = 1 then
/* Delete proceeds, you just needs to *do nothing*
except for returning the OLD row as it were */
RETURN OLD ;
else
/* instead of deleting, set a flag */
UPDATE my_schema.my_table
SET deleted_ind = 1
WHERE uuid_col = old.uuid_col ;

/* This will skip the process of this row.
It will also avoid subsequent triggers to be fired, and the row will
not be counted on the rows-affected count. If more triggers need
to be processed, make sure this is the last in the chain.
*/
RETURN NULL ;
end if ;
END;
$$
LANGUAGE plpgsql;

(如果你的函数是一张一张表使用的,可以硬编码,不需要Dynamic SQL)


旁注:如果列 delete_ind将仅用作标志,其含义最好通过将其声明为boolean not null来传达。而不是 integer .

关于postgresql - 如何在 Postgres 中实现清除 os 软删除记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41772683/

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