sql >> Database teknologi >  >> RDS >> PostgreSQL

Hvordan logger man dataændringer i postgresql?

Meget generisk triggerfunktion, fundet der:https://www. cybertec-postgresql.com/da/tracking-changes-in-postgresql/

Tabel til at gemme historikken:

CREATE SCHEMA logging;
CREATE TABLE logging.t_history (
        id             serial,
        tstamp         timestamp DEFAULT now(),
        schemaname     text,
        tabname        text,
        operation      text,
        who            text DEFAULT current_user,
        new_val        json,
        old_val        json
);

Udløseren:

CREATE FUNCTION change_trigger() RETURNS trigger AS $$
       BEGIN
         IF TG_OP = 'INSERT'
         THEN INSERT INTO logging.t_history (
                tabname, schemaname, operation, new_val
              ) VALUES (
                TG_RELNAME, TG_TABLE_SCHEMA, TG_OP, row_to_json(NEW)
              );
           RETURN NEW;
         ELSIF  TG_OP = 'UPDATE'
         THEN
           INSERT INTO logging.t_history (
             tabname, schemaname, operation, new_val, old_val
           )
           VALUES (TG_RELNAME, TG_TABLE_SCHEMA, TG_OP, row_to_json(NEW), row_to_json(OLD));
           RETURN NEW;
         ELSIF TG_OP = 'DELETE'
         THEN
           INSERT INTO logging.t_history
             (tabname, schemaname, operation, old_val)
             VALUES (
               TG_RELNAME, TG_TABLE_SCHEMA, TG_OP, row_to_json(OLD)
             );
             RETURN OLD;
         END IF;
       END;
$$ LANGUAGE 'plpgsql' SECURITY DEFINER;

Anvend triggeren:

CREATE TRIGGER t BEFORE INSERT OR UPDATE OR DELETE ON your_table
        FOR EACH ROW EXECUTE PROCEDURE change_trigger();


  1. Hvordan CEILING() fungerer i MariaDB

  2. hvordan henter man data fra to tabeller i mysql?

  3. kan ikke oprette forbindelse til Postgres (pg) database fra mit Ruby Script ved hjælp af gem pg (Dette er ikke skinner, bare ren rubin)

  4. Regneark vs. databaser:Er det tid til at skifte? Del 1