Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

convert back to hstore from jsonb #3

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 9 additions & 16 deletions audit.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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
);

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down