I want to pass a table name as a parameter in a Postgres function. I tried this code:
CREATE OR REPLACE FUNCTION some_f(param character varying) RETURNS integer
AS $$
BEGIN
IF EXISTS (select * from quote_ident($1) where quote_ident($1).id=1) THEN
return 1;
END IF;
return 0;
END;
$$ LANGUAGE plpgsql;
select some_f('table_name');
And I got this:
ERROR: syntax error at or near "."
LINE 4: ...elect * from quote_ident($1) where quote_ident($1).id=1)...
^
********** Error **********
ERROR: syntax error at or near "."
And here is the error I got when changed to this select * from quote_ident($1) tab where tab.id=1:
ERROR: column tab.id does not exist
LINE 1: ...T EXISTS (select * from quote_ident($1) tab where tab.id...
Probably, quote_ident($1) works, because without the where quote_ident($1).id=1 part I get 1, which means something is selected. Why may the first quote_ident($1) work and the second one not at the same time? And how could this be solved?
For only few, known tables names, it’s typically simpler to avoid dynamic SQL and spell out the few code variants in separate functions or in a
CASEconstruct.That said, your given code can be simplified and improved:
Call with schema-qualified name (see below):
Or:
Major points
Use an
OUTparameter to simplify the function. You can assign the result of the dynamicSELECTdirectly and be done. No need for additional variables and code.EXISTSdoes exactly what you want. You gettrueif the row exists orfalseotherwise. There are various ways to do this,EXISTSis typically most efficient.To return
integerlike your original, cast thebooleanresult tointegerand useOUT result integerinstead. But rather just return boolean as demonstrated.I use the object identifier type
regclassas input type for_tbl. That is more convenient here thantextinput andquote_ident(_tbl)orformat('%I', _tbl)because:.. it prevents SQL injection just as well.
.. it fails immediately and more gracefully if the table name is invalid / does not exist / is invisible to the current user.
.. it works with schema-qualified table names, where a plain
quote_ident(_tbl)orformat(%I)would fail to resolve the ambiguity. You would have to pass and escape schema and table names separately.A
regclassparameter is only applicable for existing tables, obviously.I still use
format()because it simplifies the syntax (and to demonstrate how it’s used), but with%sinstead of%I. For more complex queries,format()helps more. For the simple example we could just concatenate:No need to table-qualify the
idcolumn while there is only a single table in theFROMlist – no ambiguity possible. (Dynamic) SQL commands insideEXECUTEhave a separate scope, function variables or parameters are not visible – as opposed to plain SQL commands in the function body.Here’s why you always escape user input for dynamic SQL properly:
fiddle – demonstrating SQL injection
Old sqlfiddle