Created
April 6, 2016 14:52
-
-
Save gintsmurans/6b2ea70bab4fd1b42a46cf16fcde310c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
CREATE OR REPLACE FUNCTION jsonb_array_search(json_arr jsonb, col TEXT, search_for TEXT) RETURNS boolean | |
LANGUAGE plpgsql IMMUTABLE AS $$ | |
DECLARE | |
rec jsonb; | |
len int; | |
ret boolean = false; | |
BEGIN | |
-- If json_arr is not an array, return false | |
BEGIN | |
len := jsonb_array_length(json_arr); | |
EXCEPTION WHEN OTHERS THEN | |
RETURN false; | |
END; | |
-- Do the search | |
FOR rec in SELECT * FROM jsonb_array_elements(json_arr) | |
LOOP | |
CASE WHEN rec ? col AND rec->>col ILIKE search_for THEN | |
ret = true; | |
EXIT; | |
ELSE | |
END CASE; | |
END LOOP; | |
RETURN ret; | |
END $$; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment