2018-11-13 08:58:55 +03:00
CREATE OR REPLACE function hdb_views.{{QUALIFIED_TRIGGER_NAME}}() RETURNS trigger
2018-09-05 14:26:46 +03:00
LANGUAGE plpgsql
AS $$
DECLARE
id text;
2018-10-25 10:22:51 +03:00
_old record;
_new record;
_data json;
payload json;
2019-01-28 09:12:52 +03:00
session_variables json;
server_version_num int;
2018-09-05 14:26:46 +03:00
BEGIN
id := gen_random_uuid();
2019-01-28 09:12:52 +03:00
server_version_num := current_setting('server_version_num');
IF server_version_num >= 90600 THEN
session_variables := current_setting('hasura.user', 't');
ELSE
BEGIN
session_variables := current_setting('hasura.user');
EXCEPTION WHEN OTHERS THEN
session_variables := NULL;
END;
END IF;
2018-10-25 10:22:51 +03:00
IF TG_OP = 'UPDATE' THEN
_old := {{OLD_ROW}};
_new := {{NEW_ROW}};
ELSE
/* initialize _old and _new with dummy values */
_old := row((select 1));
_new := row((select 1));
END IF;
2018-09-05 14:26:46 +03:00
_data := json_build_object(
2018-10-25 10:22:51 +03:00
'old', {{OLD_PAYLOAD_EXPRESSION}},
'new', {{NEW_PAYLOAD_EXPRESSION}}
2018-09-05 14:26:46 +03:00
);
payload := json_build_object(
'op', TG_OP,
2019-01-28 09:12:52 +03:00
'data', _data,
'session_variables', session_variables
2018-09-05 14:26:46 +03:00
)::text;
2018-10-25 10:22:51 +03:00
IF (TG_OP <> 'UPDATE') OR (_old <> _new) THEN
INSERT INTO
2019-03-25 20:10:52 +03:00
hdb_catalog.event_log (id, schema_name, table_name, trigger_name, payload)
2018-10-25 10:22:51 +03:00
VALUES
2019-03-25 20:10:52 +03:00
(id, TG_TABLE_SCHEMA, TG_TABLE_NAME, '{{NAME}}', payload);
2018-10-25 10:22:51 +03:00
END IF;
2018-09-05 14:26:46 +03:00
RETURN NULL;
END;
$$;
2018-11-13 08:58:55 +03:00
DROP TRIGGER IF EXISTS {{QUALIFIED_TRIGGER_NAME}} ON {{QUALIFIED_TABLE}};
CREATE TRIGGER {{QUALIFIED_TRIGGER_NAME}} AFTER {{OPERATION}} ON {{QUALIFIED_TABLE}} FOR EACH ROW EXECUTE PROCEDURE hdb_views.{{QUALIFIED_TRIGGER_NAME}}();