Pg gethostname
来自 PostgreSQL wiki
跳转到导航跳转到搜索
这是一个可编译的 C 函数,用于获取服务器主机名。 PGXN 上也提供更新版本。
已在 CentOS 5 x86_64,postgresql 9.0 & 9.1 上测试。
可能在早期版本的 pg 和其他 linux 发行版中也能正常工作,但尚未测试。
/*
A PostgreSQL function for getting the hostname.
File: `pg_config --libdir`/pg_gethostname.c
To compile... (make sure pg_config is in your PATH)
gcc -I$(pg_config --includedir-server) -fpic -c pg_gethostname.c -L$(pg_config --libdir)
gcc --shared -o pg_gethostname.so pg_gethostname.o
To create the funciton in PostgreSQL...
CREATE OR REPLACE FUNCTION pg_gethostname() RETURNS text
AS 'pg_gethostname'
LANGUAGE C IMMUTABLE STRICT;
*/
#include "postgres.h"
#include <limits.h>
#include <unistd.h>
#include <string.h>
#include "fmgr.h"
#include "utils/palloc.h"
#include "utils/elog.h"
#include "storage/bufpage.h"
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif
PG_FUNCTION_INFO_V1( pg_gethostname );
Datum pg_gethostname( PG_FUNCTION_ARGS );
Datum pg_gethostname( PG_FUNCTION_ARGS )
{
text *t;
char server_hostname[HOST_NAME_MAX];
size_t length;
if ( gethostname( server_hostname, HOST_NAME_MAX ) != 0 )
{
// returning an empty string for the hostname if it fails makes
// sense because if it succeeded, we would have a name
server_hostname[0] = '\0';
}
length = strnlen( server_hostname, HOST_NAME_MAX );
t = (text *) palloc(VARHDRSZ + length );
SET_VARSIZE( t, VARHDRSZ + length );
memcpy( VARDATA(t), server_hostname, length );
PG_RETURN_TEXT_P( t );
}
用法
postgres# select pg_gethostname(); pg_gethostname ---------------- myserver
使用 makefile 安装
https://postgresql.ac.cn/docs/9.1/static/extend-pgxs.html
这在我的 Ubuntu 12.04 64bit PostgreSQL 9.1 上有效
在您选择的目录中创建一个 makefile
# makefile MODULES = pg_gethostname PG_CONFIG = pg_config PGXS := $(shell $(PG_CONFIG) --pgxs) include $(PGXS)
将 pg_gethostname.c 放置在同一目录中,并运行以下脚本。 您必须在路径中拥有 pg_config
#!/bin/bash # Install script PGXS=`pg_config --pgxs` PG_CONFIG=`which pg_config` make make install echo "CREATE OR REPLACE FUNCTION pg_gethostname() RETURNS text AS 'pg_gethostname' LANGUAGE C IMMUTABLE STRICT;" | psql -U postgres template1