Skip to content

Instantly share code, notes, and snippets.

@mandrews
Forked from mfenniak/gist:3008378
Created March 18, 2014 18:32
Show Gist options
  • Select an option

  • Save mandrews/9626410 to your computer and use it in GitHub Desktop.

Select an option

Save mandrews/9626410 to your computer and use it in GitHub Desktop.
CREATE OR REPLACE FUNCTION hstore_merge(left HSTORE, right HSTORE) RETURNS HSTORE AS $$
SELECT $1 || $2;
$$ LANGUAGE SQL;
CREATE AGGREGATE hstore_merge (HSTORE) (
SFUNC = hstore_merge,
STYPE = HSTORE,
INITCOND = ''
);
-- Example usage:
-- Assume you have a table:
--
-- CREATE TABLE audit_record (
-- object_id UUID,
-- modified_values HSTORE,
-- timestamp TIMESTAMP
-- )
--
-- where-in you store every modification to a record as an HSTORE
-- containing the fields modified at a specific time, but not
-- the fields that weren't modified. You could use hstore_merge
-- to generate a snapshot of the object at any point in time:
--
-- SELECT
-- hstore_merge(modified_values) OVER (PARTITION BY object_id ORDER BY timestamp) AS values
-- FROM
-- audit_record
-- WHERE
-- object_id = :object_id AND
-- timestamp <= :timestamp
-- ORDER BY timestamp DESC
-- LIMIT 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment