Last active
January 29, 2025 18:50
-
-
Save a-c-m/2a5078e9aca0b98135e67c0d1336ad3f to your computer and use it in GitHub Desktop.
PG function to autocomplete fields
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 dynamic_autocomplete( | |
table_name TEXT, | |
field_name TEXT, | |
search_input TEXT | |
) RETURNS TABLE(count INT, value TEXT) | |
LANGUAGE plpgsql AS | |
$$ | |
DECLARE | |
query TEXT; | |
BEGIN | |
-- Construct the dynamic SQL query | |
query := format( | |
'SELECT COUNT(*)::INT, MIN(%I)::TEXT AS value | |
FROM %I | |
WHERE LOWER(%I) LIKE LOWER(''%%%s%%'') | |
GROUP BY LOWER(%I) | |
ORDER BY COUNT(*) DESC;', | |
field_name, table_name, field_name, search_input, field_name | |
); | |
-- Execute the query and return results | |
RETURN QUERY EXECUTE query; | |
END; | |
$$; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment