Skip to content

Instantly share code, notes, and snippets.

@genme
Created March 21, 2014 08:02
Show Gist options
  • Save genme/9681671 to your computer and use it in GitHub Desktop.
Save genme/9681671 to your computer and use it in GitHub Desktop.
CREATE OR REPLACE FUNCTION contents.reduce_dim(ANYARRAY)
RETURNS SETOF ANYARRAY AS
$function$
DECLARE
s $1%TYPE;
BEGIN
FOREACH s SLICE 1 IN ARRAY $1 LOOP
RETURN NEXT s;
END LOOP;
RETURN;
END;
$function$
LANGUAGE plpgsql IMMUTABLE;
CREATE AGGREGATE compound_array (
BASETYPE = ANYARRAY,
STYPE = ANYARRAY,
SFUNC = ARRAY_CAT,
INITCOND = '{}'
);
CREATE OR REPLACE FUNCTION contents.except_dim(a ANYARRAY, b ANYARRAY)
RETURNS ANYARRAY AS
$function$
DECLARE
c $1%TYPE;
BEGIN
WITH merge AS (
SELECT
contents.reduce_dim(a) AS dim
EXCEPT
SELECT
contents.reduce_dim(b) AS dim
)
SELECT
compound_array(ARRAY [dim])
FROM merge
INTO c;
RETURN c;
END;
$function$
LANGUAGE plpgsql IMMUTABLE;
CREATE OR REPLACE FUNCTION contents.intersect_dim(a ANYARRAY, b ANYARRAY)
RETURNS ANYARRAY AS
$function$
DECLARE
c $1%TYPE;
BEGIN
WITH merge AS (
SELECT
contents.reduce_dim(a) AS dim
INTERSECT
SELECT
contents.reduce_dim(b) AS dim
)
SELECT
compound_array(ARRAY [dim])
FROM merge
INTO c;
RETURN c;
END;
$function$
LANGUAGE plpgsql IMMUTABLE;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment