Implementing history of PostgreSQL table

前端 未结 1 1648
故里飘歌
故里飘歌 2021-01-19 06:26

I want to implement history of changes of PostgreSQL table. The table is defined the following way:

CREATE TABLE \"ps_counters\"
(
    \"psid\" integer NOT N         


        
1条回答
  •  礼貌的吻别
    2021-01-19 06:54

    I managed to implement it.

    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();
    

    0 讨论(0)
提交回复
热议问题