Let's say I have a windows user environment variable SOME_STRING.
Is it possible to use its value in a PL/pgSQL function?
If not, do I need to use an untrusted language (like PL/pythonu) or can I use a trusted one?
I am on PG 9.2
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It only takes a minute to sign up.
Sign up to join this communityYou can not access a environment variable directly; but you can access a custom configuration setting and set that to a value from the environment at startup. For example, you can pass the follow startup option using PGOPTIONS
:
PGOPTIONS="-c 'custom.some_string=${SOME_STRING}'"
Note: the dot (.
) in the name is important.
Then retrieve the value using current_setting
:
SELECT current_setting('custom.some_string');
(I have tried this on Linux and found it to be working, it should be the same for Windows, but may need some slight modification to cater for that particular platform.)
Custom parameters have been possible since postgresql version 8.0 with the use of custom_variable_classes
(see 16.4.12. Customized Options) Since postgresql version 10.0, the use of custom_variable_classes
is not necessary but the parameter name must still consist of two parts, separated by a .
, first a variable class name, then the variable name. The class name should be unique across all loaded modules.
psql -v variable_name=“$ENV_VARIABLE”
and then using it within scripts as :variable_name
.
psql
), which is a little different. Having said this, I thought that the method I described should still be applicable 🤔
To set a env variable in session level:
set db.beta = 'Stored in env variable';
(db.beta can be replaced with any string as desired but it should have dot(.) in-between)
To use env variable in your query:
create table neo(display text);
insert into neo values((SELECT current_setting('db.beta')));
To set env variable globally, put the variable in postgresql.conf
file under CUSTOMIZED OPTIONS
like below.
db.beta = 'Stored in env variable'