From 739b3f3d8d278005c51803f74254dd82ee0cbb71 Mon Sep 17 00:00:00 2001 From: Andrew Stoerkel Date: Mon, 20 May 2024 14:37:28 -0400 Subject: [PATCH] change snapshot_of for postgres --- history/backends/postgres.py | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/history/backends/postgres.py b/history/backends/postgres.py index a78308d..4cca967 100644 --- a/history/backends/postgres.py +++ b/history/backends/postgres.py @@ -10,7 +10,8 @@ _ctid integer := TG_ARGV[0]::integer; _pk_name text := TG_ARGV[1]; _record_snap boolean := TG_ARGV[2]::boolean; - _fields text[] := TG_ARGV[3:]; + _snap_of text := TG_ARGV[3]; + _fields text[] := TG_ARGV[4:]; _old jsonb := to_jsonb(OLD); _new jsonb := to_jsonb(NEW); _snapshot jsonb; @@ -22,9 +23,15 @@ END IF; IF _record_snap THEN - SELECT jsonb_object_agg(key, value) INTO _snapshot - FROM jsonb_each(_new) - WHERE key = ANY(_fields); + IF _snap_of == 'OLD' THEN + SELECT jsonb_object_agg(key, value) INTO _snapshot + FROM jsonb_each(_old) + WHERE key = ANY(_fields); + ELSEIF _snap_of == 'NEW' THEN + SELECT jsonb_object_agg(key, value) INTO _snapshot + FROM jsonb_each(_new) + WHERE key = ANY(_fields); + END IF; END IF; IF (TG_OP = 'UPDATE') THEN @@ -133,9 +140,9 @@ def create_trigger(self, model, trigger_type): return tr_name, [] self.execute( """ - CREATE TRIGGER {tr_name} AFTER {trans_type} ON {table} - FOR EACH ROW EXECUTE PROCEDURE - history_record({ctid}, '{pk_col}', {snapshots}{field_list}); + CREATE TRIGGER {tr_name} AFTER {trans_type} ON {table} + FOR EACH ROW EXECUTE PROCEDURE + history_record({ctid}, '{pk_col}', {snapshots}, '{snap_of}', {field_list}); """.format( tr_name=tr_name, trans_type=trigger_type.name.upper(), @@ -143,7 +150,8 @@ def create_trigger(self, model, trigger_type): ctid=ct.pk, pk_col=model._meta.pk.column, snapshots=int(conf.SNAPSHOTS), - field_list=", '" + "', '".join(field_names) + "'", + snap_of=trigger_type.snapshot_of, + field_list="'" + "', '".join(field_names) + "'", ) ) return tr_name, field_names