Skip to content

replace table name in query with GET parameter #52

Answered by lovasoa
ersi33 asked this question in Q&A
Discussion options

You must be logged in to vote

Indeed, postgres does not support variable table names in prepared statements (nor do any other database). It's mostly a good thing, both for security reasons, as you mentioned (most people don't want to give open access to all tables, including internal ones, to everyone) and for performance reasons (Postgres needs to know which table it will be querying to make a good query plan).

If you don't care about any of that and just want to give everyone access to everything, you can create a postgres function with an EXECUTE statement.

In your migrations:

CREATE FUNCTION select_all_from(tablename text, OUT table_as_array jsonb)
AS '
BEGIN
	EXECUTE format(''SELECT json_agg(row_to_json(%I)) FROM…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@ersi33
Comment options

Answer selected by lovasoa
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants