gpt4 book ai didi

sql - PostgreSQL表的实现历史

转载 作者:太空狗 更新时间:2023-10-30 01:55:55 28 4
gpt4 key购买 nike

我想实现 PostgreSQL 表的变化历史。该表按以下方式定义:

CREATE TABLE "ps_counters"
(
"psid" integer NOT NULL,
"counter" bigint[] NOT NULL
);

我希望历史表看起来像:

CREATE TABLE "ps_counters_history"
(
"timestamp" timestamp NOT NULL,
"psid" integer NOT NULL,
"counter" bigint[] NOT NULL
);

我需要一个触发器和一个存储过程,在 ps_couneters 中的每次更改(插入或更新)时插入到 ps_counters_history 中,但除了防止 ps_counters_history 变得太大我想每个月对 ps_counters_history 表进行分区。

最佳答案

我设法实现了它。

CREATE TABLE "ps_counters_history"
(
"id" serial PRIMARY KEY,
"timestamp" timestamp NOT NULL DEFAULT clock_timestamp(),
"psid" integer NOT NULL,
"counter" bigint[] NOT NULL
);

CREATE OR REPLACE FUNCTION ps_counters_history_trigger()
RETURNS trigger AS
$BODY$
DECLARE
table_name text;
BEGIN
table_name := 'ps_counters_history_' || to_char(CURRENT_DATE, 'yyyy_mm');
IF NOT EXISTS (SELECT 1 FROM pg_class WHERE relname = table_name)
THEN
EXECUTE 'CREATE TABLE IF NOT EXISTS ' || table_name ||
' () INHERITS (ps_counters_history);';
END IF;
EXECUTE 'INSERT INTO ' || table_name ||
'(psid, counter) VALUES ($1.psid, $1.counter);' USING NEW;
RETURN NEW;
END
$BODY$
LANGUAGE plpgsql;

CREATE TRIGGER ps_counters_history_trigger
AFTER INSERT OR UPDATE ON ps_counters FOR EACH ROW
EXECUTE PROCEDURE ps_counters_history_trigger();

关于sql - PostgreSQL表的实现历史,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38954139/

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