Created
November 26, 2019 14:59
-
-
Save othercodes/eeb9f5639719552e0da279356dbf2d0e to your computer and use it in GitHub Desktop.
Search value in ALL tables from the database.
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
// https://stackoverflow.com/questions/5350088/how-to-search-a-specific-value-in-all-tables-postgresql | |
CREATE OR REPLACE FUNCTION search_columns( | |
needle text, | |
haystack_tables name[] default '{}', | |
haystack_schema name[] default '{}' | |
) | |
RETURNS table(schemaname text, tablename text, columnname text, rowctid text) | |
AS $$ | |
begin | |
FOR schemaname,tablename,columnname IN | |
SELECT c.table_schema,c.table_name,c.column_name | |
FROM information_schema.columns c | |
JOIN information_schema.tables t ON | |
(t.table_name=c.table_name AND t.table_schema=c.table_schema) | |
WHERE (c.table_name=ANY(haystack_tables) OR haystack_tables='{}') | |
AND (c.table_schema=ANY(haystack_schema) OR haystack_schema='{}') | |
AND t.table_type='BASE TABLE' | |
LOOP | |
EXECUTE format('SELECT ctid FROM %I.%I WHERE cast(%I as text)=%L', | |
schemaname, | |
tablename, | |
columnname, | |
needle | |
) INTO rowctid; | |
IF rowctid is not null THEN | |
RETURN NEXT; | |
END IF; | |
END LOOP; | |
END; | |
$$ language plpgsql; | |
// usage | |
select * from search_columns('wtf'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment