I write PSQL script and using variables (for psql –variable key=value commandline syntax).
This works perfectly for top level scope like select * from :key, but I create functions with the script and need variable value inside them.
So, the syntax like
create function foo() returns void as
$$
declare
begin
grant select on my_table to group :user;
end;
$$
language plpgsql;
fails at :user.
As far as I understand psql variables is a plain macro substitution feature, but it doesn’t process function bodies.
Are there any escaping syntax for such cases? Surrounding :user with $$ works regarding substitution, but psql fails at $$.
Are there any other way to do this besides standalone macro processing (sed, awk, etc)?
PSQL
SETvariables aren’t interpolated inside dollar-quoted strings. I don’t know this for certain, but I think there’s no escape or other trickery to turn onSETvariable interpolation in there.One might think you could wedge an unquoted
:userbetween two dollar-quoted stretches of PL/pgSQL to get the desired effect. But this doesn’t seem to work… I think the syntax requires a single string and not an expression concatenating strings. Might be mistaken on that.Anyway, that doesn’t matter. There’s another approach (as Pasco noted): write the stored procedure to accept a PL/pgSQL argument. Here’s what that would look like.
Notes on this function:
EXECUTEgenerates an appropriateGRANTon each invocation using on our procedure argument. The PG manual section called “Executing Dynamic Commands” explainsEXECUTEin detail.usermust be double quoted. Double quotes force it to be interpreted as an identifier.Once you define the function like this, you can call it using interpolated PSQL variables. Here’s an outline.
psql --variable user="'whoever'" --file=myscript.sql. Single quotes are required around the username!select foo(:user);. This is where we rely on those single quotes we put in the value ofuser.Although this seems to work, it strikes me as rather squirrely. I thought
SETvariables were intended for runtime configuration. Carrying data around inSETseems odd.Edit: here’s a concrete reason to not use
SETvariables. From the manpage: “These assignments are done during a very early stage of startup, so variables reserved for internal purposes might get overwritten later.” If Postgres decided to use a variable nameduser(or whatever you pick), it could overwrite your script argument with something you never intended. In fact, psql already takesUSERfor itself — this only works becauseSETis case sensitive. This very nearly broke things from the start!