snippetsqlMinor
How to pass parameters to sql script via psql \i command
Viewed 0 times
scriptpasssqlpsqlviahowcommandparameters
Problem
The psql
Example: say you have this simple script
I've tried
but got this error
I know that running this on terminal will work, but I'm already inside psql.
\i command is able to execute a given SQL script but I need a way to pass parameters to the script.Example: say you have this simple script
select * from :table LIMIT 1;
I've tried
my_db=> \i my-script.sql -v table="core.product"but got this error
psql:my-script.sql:1: ERROR: syntax error at or near ":"
LINE 1: select * from :table LIMIT 1;
^
\i: extra argument "-v" ignored
\i: extra argument "table="core.product"" ignoredI know that running this on terminal will work, but I'm already inside psql.
psql -v table="core.product" -f my-script.sqlSolution
Use
Read about SQL interpolation in the manual here:
Ideally, your script would read:
With schema and table double-quoted separately, for identifier-interpolation.
Then set schema and table in psql without quotes like:
Just the bare, case-sensitive names.
Finally, execute:
This way, the script is safe against SQL injection.
\set to set a variable inside psql.Read about SQL interpolation in the manual here:
- https://www.postgresql.org/docs/current/app-psql.html#APP-PSQL-INTERPOLATION
Ideally, your script would read:
SELECT * FROM :"my_schema".:"my_table" LIMIT 1;With schema and table double-quoted separately, for identifier-interpolation.
Then set schema and table in psql without quotes like:
my_db=>\set my_schema core
my_db=>\set my_table productJust the bare, case-sensitive names.
Finally, execute:
my_db=>\i my-script.sqlThis way, the script is safe against SQL injection.
Code Snippets
SELECT * FROM :"my_schema".:"my_table" LIMIT 1;my_db=>\set my_schema core
my_db=>\set my_table productmy_db=>\i my-script.sqlContext
StackExchange Database Administrators Q#300276, answer score: 5
Revisions (0)
No revisions yet.