我在 Postgres 9.4 中编写了一个用户定义的函数来编码字符串:
CREATE OR REPLACE FUNCTION platform.encode_sig(sig text)
RETURNS bigint AS $BODY$
declare sig_id bigint;
begin
lock table platform.sig2encodings in access exclusive mode;
execute 'select sig_id from platform.sig2encodings where sig = ''' || sig || '''' into sig_id;
if sig_id is null
then
raise notice 'I do not have encoding for %', sig;
execute 'insert into platform.sig2encodings (sig) values (''' || sig || ''')';
execute 'select sig_id from platform.sig2encodings where sig = ''' || sig || '''' into sig_id;
else
raise notice 'I do have encoding for %', sig;
end if;
return sig_id;
END;
$BODY$
LANGUAGE plpgsql VOLATILE COST 100;
桌子:
CREATE TABLE platform.sig2encodings
(
sig_id bigserial NOT NULL,
sig text,
CONSTRAINT sig2encodings_pkey PRIMARY KEY (sig_id ),
CONSTRAINT sig2encodings_sig_key UNIQUE (sig )
)
pgadmin 或 psql 中的调用将数据插入到表中:
select * from platform.encode_sig('NM_Gateway_NL_Shutdown');
python 中的调用获取id
,但不插入数据:
db="""dbname='XXX' user='XXX' password='XXX' host=XXX port=XXX"""
def encode_sig(sig):
try:
conn=psycopg2.connect(db)
except:
print "I am unable to connect to the database."
exit()
cur = conn.cursor()
try:
sql = "select * from platform.encode_sig('" + sig + "');"
print sql
cur.execute(sql)
except:
print "I can't retrieve sid"
row = cur.fetchone()
return row[0]
print str(encode_sig('NM_Gateway_UDS_CC'))
python脚本的输出:
$ ./events_insert.py
616
617
618
619
620
621
$ ./events_insert.py
622
623
624
625
626
627
postgres 中的表是空的。到底是怎么回事?
更新:
以下 perl 脚本有效(所有控制台输出(通知)和表中的行):
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use DBI;
my $dbh = get_connection();
$dbh->do("SELECT platform.encode_sig('blah blah blah')");
$dbh->disconnect();
sub get_connection {
return DBI->connect('dbi:Pg:dbname=XXX;host=XXX;port=XXX',
'XXX', 'XXX', { RaiseError => 1 });
}
数据库配置是非常标准的配置。这些行来自 postgresql.conf(因为它们已被注释掉,所以假定为默认值):
#fsync = on # turns forced synchronization on or off
#synchronous_commit = on # synchronization level;
# off, local, remote_write, or on
#wal_sync_method = fsync # the default is the first option
# supported by the operating system:
# open_datasync
# fdatasync (default on Linux)
# fsync
# fsync_writethrough
# open_sync
#full_page_writes = on # recover from partial page writes
#wal_log_hints = off # also do full page writes of non-critical updates
# (change requires restart)
#wal_buffers = -1 # min 32kB, -1 sets based on shared_buffers
# (change requires restart)
#wal_writer_delay = 200ms # 1-10000 milliseconds
#commit_delay = 0 # range 0-100000, in microseconds
#commit_siblings = 5 # range 1-1000