PostgreSQL Dynamic
SQL
▌Introduction
This is a sample of using EXECUTE to execute the dynamic SQL, which its parameters come
from psql arguments.
▌Environment
▋PostgreSQL 11
▌Implement
▋The original SQL
Here is the original SQL we want to
execute. The SQL will create a foreign data wrapper for dblink(cross database
query) from database Demo to database postgres.
▋create_dblink_wrapper.sql
▋ Goals
Since we put the user/pwd
when creating the USER MAPPING and while executing the SQL on CI, it is
insecure and cannot be modified depends on different environments.
We would like to decide the values of
user/pwd by the environment variables, for example,
$ psql -h localhost -p 5432 -U postgres -d Demo -v postgres_user=$POSTGRESS_USER -v postgres_password=$POSTGRES_PASSWORD -f create_dblink_wrapper.sql
▋ This will NOT WORK!
Since we can get the argument values
from psql command by :postgres_user. However, we cannot use the
variable(s) inside the DO statement.
▋Solution
We have to use the features of Dynamic SQL and use current_setting(get current value of setting) to make the SQL can read the value of arguments
in DO
statement.
▋create_dblink_wrapper.sql
See the SQL sample file on my Github.
Now we can execute the SQL as
following,
$ psql -h localhost -p 5432 -U postgres -d Demo -v postgres_user=$POSTGRES_USER -v postgres_password=$POSTGRES_PASSWORD -f create_dblink_wrapper.sql
Output:
▌Reference
▋ PostgreSQL Doc -
Dynamic SQL
▋ PSQL Command Line Arguments in DO script
▋ PostgreSQL: How to pass parameters from command
line?
沒有留言:
張貼留言