Skip to content

Instantly share code, notes, and snippets.

@andrewxhill
Last active August 29, 2015 14:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewxhill/0645add72c093f2f4908 to your computer and use it in GitHub Desktop.
Save andrewxhill/0645add72c093f2f4908 to your computer and use it in GitHub Desktop.
Create a table to store changes from any of your tables in a log table.
--
-- Create a table in your CartoDB editor called 'version_control'
-- Run the following SQL in your editor to create the needed columns
--
ALTER TABLE version_control ADD COLUMN data json;
ALTER TABLE version_control ADD COLUMN source_id integer;
ALTER TABLE version_control ADD COLUMN table_name text;
ALTER TABLE version_control ADD COLUMN tg_op text;
--
-- Add the following function in your CartoDB account from any SQL interface
--
CREATE OR REPLACE FUNCTION axh_version_control() RETURNS TRIGGER AS $$
BEGIN
IF (TG_OP = 'DELETE') THEN
INSERT INTO version_control(the_geom, tg_op, data, source_id, table_name)
SELECT OLD.the_geom, 'DELETE', row_to_json(OLD), OLD.cartodb_id, TG_TABLE_NAME::text;
RETURN OLD;
ELSIF (TG_OP = 'UPDATE') THEN
INSERT INTO version_control(the_geom, tg_op, data, source_id, table_name)
SELECT NEW.the_geom, 'UPDATE', row_to_json(NEW), NEW.cartodb_id, TG_TABLE_NAME::text;
RETURN NEW;
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
--
-- Add a trigger to any table that you want to store change history
-- The following adds the trigger, simply change the table name from
-- 'your_important_table' to the name of the table you want to track
--
CREATE TRIGGER axh_version_trigger
AFTER UPDATE OR DELETE ON your_important_table
FOR EACH ROW EXECUTE PROCEDURE axh_version_control();
--
-- To extract a record from the version_control table you can filter
-- and then explode the JSON record like this
--
SELECT (json_populate_record(null::fake_data, data)).* FROM version_control LIMIT 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment