Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python PostgreSQL语句缓存干扰预期结果_Python_Sql_Postgresql - Fatal编程技术网

Python PostgreSQL语句缓存干扰预期结果

Python PostgreSQL语句缓存干扰预期结果,python,sql,postgresql,Python,Sql,Postgresql,我们已经编写了一个PL/pgSQL函数来记录审计表的时间戳。 然而,PostgresSQL语句缓存并没有在每个节点上重新计算now() 调用,这将导致在审计表中记录过时(意味着旧的)时间戳 我们正在运行Postgres 9.2。根据文件 (滚动到文章的底部),建议使用对now()的调用 此功能未按预期工作: CREATE OR REPLACE FUNCTION save(txd integer) RETURNS void AS $$ BEGIN INSERT INTO audit (id

我们已经编写了一个PL/pgSQL函数来记录审计表的时间戳。 然而,PostgresSQL语句缓存并没有在每个节点上重新计算
now()
调用,这将导致在审计表中记录过时(意味着旧的)时间戳

我们正在运行Postgres 9.2。根据文件 (滚动到文章的底部),建议使用对
now()
的调用

此功能未按预期工作:

CREATE OR REPLACE FUNCTION save(txd integer) RETURNS void AS $$
BEGIN
    INSERT INTO audit (id, mtime) VALUES (txd,now());
END;$$
表定义为:

CREATE TABLE audit (
  id integer NOT NULL,
  mtime timestamp without time zone NOT NULL,
  CONSTRAINT audit_pkey PRIMARY KEY (id)
  )
可以使用使用
psycopg2
的简单python 2.7脚本演示该问题:

import datetime, psycopg2, time
def tm():
    # connect and clear contents
    con = psycopg2.connect('dbname=postgres user=postgres')
    cur = con.cursor()
    cur.execute('TRUNCATE audit')

    # Add a record, wait a second, add another
    cur.execute('SELECT save(1)')
    time.sleep(1.0)
    cur.execute('SELECT save(2)')

    # List the contents
    cur.execute('SELECT * FROM audit')
    for row in cur.fetchall():
        print("modified %s" % row[1])
    cur.close()
    con.close()
如果运行此脚本,您将注意到修改时间的两个实例将报告完全相同的值,即使我们在插入之间插入了一个小的1秒睡眠

>>> tm()
modified 2016-05-10 11:05:21.766005
modified 2016-05-10 11:05:21.766005
注意:我们甚至尝试了postgres在链接中提供的示例 文章使用他们的示例,输出没有区别:

CREATE OR REPLACE FUNCTION save(txd integer) RETURNS void AS $$
DECLARE
    curtime timestamp;
BEGIN
    curtime = 'now';
    INSERT INTO audit (id, mtime) VALUES (txd,curtime);
END;$$
有人能告诉我们哪里出了问题吗?

now()
返回事务开始时的时间戳;这将导致事务中的所有时钟读数产生相同的值(这通常是您想要的)

如果您想要子事务级别的实际时间,则需要
clock_timestamp()
now()
返回事务开始时的时间戳;这将导致事务中的所有时钟读数产生相同的值(这通常是您想要的)


如果您想要子事务级别的实际时间,则需要
clock\u timestamp()

now()
返回事务开始时的时间戳。如果您想获得次交易级别的实际时间,您需要
clock\u timestamp()
非常感谢!如果您回答这个问题,我将奖励。
now()
返回事务开始时的时间戳。如果您想获得次交易级别的实际时间,您需要
clock\u timestamp()
非常感谢!如果你能回答这个问题,我会奖励你。