Can I use the hostname of the server in a PostgreSQL SELECT
statement? The following may be close but apparently does not quite work:
\set x \! hostname
select :x;
This is for PostgreSQL 9.6 on Debian.
I don't think it's possible. I think what you're looking for is gethostname()
. That's not called anywhere in the PostgreSQL source code. Nor is utsname
or any kernel interface into this.
What is called is getaddrinfo
that provides a CANONNAME
but that's essentially just your own method of addressing the server not the "symbolic hostname". If you need the hostname, you'll have to build a C-extension that does just that. Or, use a third party procedural language, like perl plperlu
, that has that support (through Sys::Hostname
or Net::Domain
, see perldoc -q hostname
); or, alternatively through javascript with plv8
that has os.hostname()
.
Another method would be simply reading the file /proc/sys/kernel/hostname
.
It's a database, not a remote administration utility. You can't really fault it for not doing this.
\! hostname
(when executed from inside PostgreSQL) into an SQL statement?
\!
you're accessing the shell of the client, not the server.
Commented
Dec 8, 2017 at 21:48
PostgreSQL has 2 functions for getting server address information. inet_server_addr()
and inet_server_port()
which provide ip address and port information of the server.
However I don't know a direct way for getting hostname. So, you may try this;
You can use postgresql.conf to create a custom configuration and use current_setting function to get that value. Here is detailed description.
For other system functions you can check System Information Functions section of the documentation.