I am using psql command to call a file bypassing argument as -v argument=value
. In the SQL file, the argument needs to be used as part of a string. For example prefix_:argument_suffix
. This is not working. If I use it as prefix_:argument
it works, but when it comes to the suffix it doesn't.
This is for building a database name in the create database
statement.
Can somebody help with this?
2 Answers 2
Use another variable like:
nd@postgres=# \set argument 'aaa'
nd@postgres=# \set dbname 'foo_':argument'_bar'
nd@postgres=# select :'dbname';
┌─────────────┐
│ ?column? │
├─────────────┤
│ foo_aaa_bar │
└─────────────┘
nd@postgres=# create database :dbname;
CREATE DATABASE
nd@postgres=# \l
List of databases
┌─────────────┬──────────┬──────────┬─────────────┬─────────────┬───────────────────────┐
│ Name │ Owner │ Encoding │ Collate │ Ctype │ Access privileges │
├─────────────┼──────────┼──────────┼─────────────┼─────────────┼───────────────────────┤
│ foo_aaa_bar │ nd │ UTF8 │ en_US.UTF-8 │ en_US.UTF-8 │ │
│ postgres │ postgres │ UTF8 │ en_US.UTF-8 │ en_US.UTF-8 │ │
│ template0 │ postgres │ UTF8 │ en_US.UTF-8 │ en_US.UTF-8 │ =c/postgres ↵│
│ │ │ │ │ │ postgres=CTc/postgres │
│ template1 │ postgres │ UTF8 │ en_US.UTF-8 │ en_US.UTF-8 │ =c/postgres ↵│
│ │ │ │ │ │ postgres=CTc/postgres │
└─────────────┴──────────┴──────────┴─────────────┴─────────────┴───────────────────────┘
5 Comments
prefix/suffix
variables and then use it like create database :prefix:argument:suffix
. Choose the case most suitable for you. Good luck!The string could be built as
'prefix_' || :'variable' || '_suffix'
To use it in a CREATE DATABASE
statement, you will have to use dynamic SQL in a function:
CREATE FUNCTION pg_temp.mkdb(var text) RETURNS void
LANGUAGE plpgsql STRICT AS
$$BEGIN
EXECUTE format('CREATE DATABASE %I;', 'prefix_' || var || '_suffix');
END;$$;
SELECT pg_temp.mkdb(:'variable');
Since the function is created in the temporary schema, it will exist only in this database session.