snippetsqlModerate
How can I use an environment variable in a Postgres function?
Viewed 0 times
canpostgresfunctionenvironmenthowusevariable
Problem
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
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
Solution
You 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
Note: the dot (
Then retrieve the value using
(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
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.Code Snippets
PGOPTIONS="-c 'custom.some_string=${SOME_STRING}'"SELECT current_setting('custom.some_string');Context
StackExchange Database Administrators Q#52235, answer score: 14
Revisions (0)
No revisions yet.