Last active
December 16, 2016 04:00
-
-
Save ttfkam/1703496382490553da15c2abbe212a40 to your computer and use it in GitHub Desktop.
Array slice for PostgreSQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Copyright 2016, Miles Elam <[email protected]> | |
-- MIT License, http://www.opensource.org/licenses/mit-license.php | |
CREATE OR REPLACE FUNCTION splice(target anyarray, start integer, to_insert anyarray) | |
RETURNS anyarray LANGUAGE 'sql' IMMUTABLE LEAKPROOF STRICT AS $$ | |
SELECT target[0:start - 1] | |
|| to_insert | |
|| target[start:array_length(target, 1)] | |
$$; | |
COMMENT ON FUNCTION splice(anyarray, integer, anyarray) | |
IS 'E.g., SELECT splice(''{6,9,4,2,5}''::integer[], 3, ''{3,1}''::integer[]); | |
returns {6,9,3,1,4,2,5}'; | |
CREATE OR REPLACE FUNCTION splice(target anyarray, start integer, to_insert anyelement) | |
RETURNS anyarray LANGUAGE 'sql' IMMUTABLE LEAKPROOF STRICT AS $$ | |
SELECT splice(target, start, ARRAY[to_insert]); | |
$$; | |
COMMENT ON FUNCTION splice(anyarray, integer, anyelement) | |
IS 'E.g., SELECT splice(''{6,9,4,2,5}''::integer[], 3, 1); | |
returns {6,9,1,4,2,5}'; | |
CREATE OR REPLACE FUNCTION splice(target anyarray, start integer, delete_count integer, to_insert anyarray) | |
RETURNS anyarray LANGUAGE 'sql' IMMUTABLE LEAKPROOF STRICT AS $$ | |
SELECT target[0:start - 1] | |
|| to_insert | |
|| target[start + delete_count:array_length(target, 1)] | |
$$; | |
COMMENT ON FUNCTION splice(anyarray, integer, integer, anyarray) | |
IS 'E.g., SELECT splice(''{6,9,4,2,5}''::integer[], 3, ''{3,1}''::integer[]); | |
returns {6,9,3,1,5}'; | |
CREATE OR REPLACE FUNCTION splice(target anyarray, start integer, delete_count integer, to_insert anyelement) | |
RETURNS anyarray LANGUAGE 'sql' IMMUTABLE LEAKPROOF STRICT AS $$ | |
SELECT splice(target, start, delete_count, ARRAY[to_insert]); | |
$$; | |
COMMENT ON FUNCTION splice(anyarray, integer, integer, anyelement) | |
IS 'E.g., SELECT splice(''{6,9,4,2,5}''::integer[], 3, 2, 1); | |
returns {6,9,1,5}'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment