bobeff bobeff - 2 months ago 15
SQL Question

Implementing history of PostgreSQL table

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

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


I want the history table to look like:

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


I need a trigger and a stored procedure which on every change (insertion or update) in
ps_couneters
to insert in
ps_counters_history
, but in addition to prevent
ps_counters_history
to became too big I want partitioning of
ps_counters_history
table on every month.

Answer

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