From d98e4d92a10a86c8cc80603d02180d4d1b01685b Mon Sep 17 00:00:00 2001
From: chmnata <46324452+chmnata@users.noreply.github.com>
Date: Mon, 6 Jan 2020 15:47:06 -0500
Subject: [PATCH] convert back to hstore from jsonb

because the jsonb operator that can - text[] requires postgres 10+
---
 audit.sql | 25 +++++++++----------------
 1 file changed, 9 insertions(+), 16 deletions(-)

diff --git a/audit.sql b/audit.sql
index 67b61b9..d96e3db 100644
--- a/audit.sql
+++ b/audit.sql
@@ -9,8 +9,8 @@ CREATE TABLE gis.logged_actions (
     application_name text,
     client_query text,
     action TEXT NOT NULL CHECK (action IN ('I','D','U', 'T')),
-    row_data jsonb,
-    changed_fields jsonb,
+    row_data hstore,
+    changed_fields hstore,
     statement_only boolean not null
 );
 
@@ -41,8 +41,8 @@ DECLARE
     audit_row gis.logged_actions;
     include_values boolean;
     log_diffs boolean;
-    h_old jsonb;
-    h_new jsonb;
+    h_old hstore;
+    h_new hstore;
     excluded_cols text[] = ARRAY[]::text[];
 BEGIN
     IF TG_WHEN <> 'AFTER' THEN
@@ -73,23 +73,16 @@ BEGIN
     END IF;
     
     IF (TG_OP = 'UPDATE' AND TG_LEVEL = 'ROW') THEN
-        audit_row.row_data = row_to_json(OLD)::JSONB - excluded_cols;
-        
-        --Computing differences
-		SELECT 
-			jsonb_object_agg(tmp_new_row.key, tmp_new_row.value) AS new_data
-			INTO audit_row.changed_fields
-		FROM jsonb_each_text(row_to_json(NEW)::JSONB) AS tmp_new_row 
-		    JOIN jsonb_each_text(audit_row.row_data) AS tmp_old_row ON (tmp_new_row.key = tmp_old_row.key AND tmp_new_row.value IS DISTINCT FROM tmp_old_row.value);
-        
-        IF audit_row.changed_fields = '{}'::JSONB THEN
+        audit_row.row_data = hstore(OLD.*) - excluded_cols;
+        audit_row.changed_fields =  (hstore(NEW.*) - audit_row.row_data) - excluded_cols;
+        IF audit_row.changed_fields = hstore('') THEN
             -- All changed fields are ignored. Skip this update.
             RETURN NULL;
         END IF;
     ELSIF (TG_OP = 'DELETE' AND TG_LEVEL = 'ROW') THEN
-        audit_row.row_data = row_to_json(OLD)::JSONB - excluded_cols;
+        audit_row.row_data = hstore(OLD.*) - excluded_cols;
     ELSIF (TG_OP = 'INSERT' AND TG_LEVEL = 'ROW') THEN
-        audit_row.row_data = row_to_json(NEW)::JSONB - excluded_cols;
+        audit_row.row_data = hstore(NEW.*) - excluded_cols;
     ELSIF (TG_LEVEL = 'STATEMENT' AND TG_OP IN ('INSERT','UPDATE','DELETE','TRUNCATE')) THEN
         audit_row.statement_only = 't';
     ELSE