5

我对事务数据库有些陌生,并且遇到了我试图理解的问题。

我创建了一个简单的演示,其中一个数据库连接存储在cherrypy 创建的5 个线程中的每一个中。我有一个方法可以显示存储在数据库中的时间戳表和一个按钮来添加新的时间戳记录。

该表有 2 个字段,一个用于 python 传递的 datetime.datetime.now() 时间戳,另一个用于设置为默认 NOW() 的数据库时间戳。


CREATE TABLE test (given_time timestamp,
                   default_time timestamp DEFAULT NOW());

我有两种与数据库交互的方法。第一个将创建一个新游标,插入一个新的 given_timestamp,提交游标,并返回到索引页面。第二种方法将创建一个新游标,选择 10 个最近的时间戳并将其返回给调用者。


import sys
import datetime
import psycopg2
import cherrypy

def connect(thread_index): 
    # Create a connection and store it in the current thread 
    cherrypy.thread_data.db = psycopg2.connect('dbname=timestamps')

# Tell CherryPy to call "connect" for each thread, when it starts up
cherrypy.engine.subscribe('start_thread', connect)

class Root:
    @cherrypy.expose
    def index(self): 
        html = []
        html.append("<html><body>")

        html.append("<table border=1><thead>")
        html.append("<tr><td>Given Time</td><td>Default Time</td></tr>")
        html.append("</thead><tbody>")

        for given, default in self.get_timestamps():
            html.append("<tr><td>%s<td>%s" % (given, default))

        html.append("</tbody>")
        html.append("</table>")

        html.append("<form action='add_timestamp' method='post'>")
        html.append("<input type='submit' value='Add Timestamp'/>")
        html.append("</form>")

        html.append("</body></html>")
        return "\n".join(html)

    @cherrypy.expose
    def add_timestamp(self):
        c = cherrypy.thread_data.db.cursor()
        now = datetime.datetime.now()
        c.execute("insert into test (given_time) values ('%s')" % now)
        c.connection.commit()
        c.close()
        raise cherrypy.HTTPRedirect('/')

    def get_timestamps(self):
        c = cherrypy.thread_data.db.cursor()
        c.execute("select * from test order by given_time desc limit 10")
        records = c.fetchall()
        c.close()
        return records

if __name__ == '__main__':

    cherrypy.config.update({'server.socket_host': '0.0.0.0',
                            'server.socket_port': 8081,
                            'server.thread_pool': 5,
                            'tools.log_headers.on': False,
                            })

    cherrypy.quickstart(Root())

我希望 given_time 和 default_time 时间戳彼此之间只有几微秒的差距。但是我得到了一些奇怪的行为。如果我每隔几秒添加一次时间戳,则 default_time 不会与 given_time 相差几微秒,但通常与前一个given_time 相差几微秒。

给定时间 默认时间
2009-03-18 09:31:30.725017 2009-03-18 09:31:25.218871
2009-03-18 09:31:25.198022 2009-03-18 09:31:17.642010
2009-03-18 09:31:17.622439 2009-03-18 09:31:08.266720
2009-03-18 09:31:08.246084 2009-03-18 09:31:01.970120
2009-03-18 09:31:01.950780 2009-03-18 09:30:53.571090
2009-03-18 09:30:53.550952 2009-03-18 09:30:47.260795
2009-03-18 09:30:47.239150 2009-03-18 09:30:41.177318
2009-03-18 09:30:41.151950 2009-03-18 09:30:36.005037
2009-03-18 09:30:35.983541 2009-03-18 09:30:31.666679
2009-03-18 09:30:31.649717 2009-03-18 09:30:28.319693

然而,如果我大约每分钟添加一个新的时间戳,那么 given_time 和 default_time 都只有几微秒,正如预期的那样。但是,在提交第 6 个时间戳(线程数 + 1)之后,default_time 与第一个 given_time 时间戳相差几微秒。

给定时间 默认时间
2009-03-18 09:38:15.906788 2009-03-18 09:33:58.839075
2009-03-18 09:37:19.520227 2009-03-18 09:37:19.520293
2009-03-18 09:36:04.744987 2009-03-18 09:36:04.745039
2009-03-18 09:35:05.958962 2009-03-18 09:35:05.959053
2009-03-18 09:34:10.961227 2009-03-18 09:34:10.961298
2009-03-18 09:33:58.822138 2009-03-18 09:33:55.423485

即使我在每次使用后都明确关闭游标,但似乎前一个游标仍在被重用。如果我在完成后关闭光标并每次创建一个新光标,这怎么可能?有人可以解释一下这里发生了什么吗?

更接近答案:

我在 get_timestamps 方法中添加了 cursor.connection.commit() ,现在它为我提供了带有时间戳的准确数据。谁能解释为什么我需要调用 cursor.connection.commit() 当我所做的只是一个选择?我猜每次我得到一个游标时,一个事务就会开始(或继续使用它提交的现有事务单元)。有没有更好的方法来做到这一点,或者我每次得到一个光标时都会坚持提交,不管我用那个光标做什么?

4

3 回答 3

3

尝试按照模块文档中的说明调用 c.close():http ://tools.cherrypy.org/wiki/Databases

def add_timestamp(self):
        c = cherrypy.thread_data.db.cursor()
        now = datetime.datetime.now()
        c.execute("insert into test (given_time) values ('%s')" % now)
        c.connection.commit()
        c.close()
        raise cherrypy.HTTPRedirect('/')

def get_timestamps(self):
        c = cherrypy.thread_data.db.cursor()
        c.execute("select * from test order by given_time desc limit 10")
        records = c.fetchall()
        c.close()
        return records
于 2009-03-17T17:12:27.680 回答
2

要解决您最近的编辑提出的问题:

在 PostgreSQL 中,NOW()不是当前时间,而是当前事务开始时的时间。Psycopg2 可能正在为您隐式启动事务,并且由于事务从未关闭(通过提交或其他方式),因此时间戳会“卡住”并变得陈旧。

可能的修复:

  • 经常提交(如果你只做 SELECT 就傻了)
  • 设置 Psycopg2 以使用不同的行为来自动创建事务(可能很难做到正确,并且影响应用程序的其他部分)
  • 使用不同的时间戳函数,例如statement_timestamp()(不符合 SQL 标准,但非常适合这种情况)

手册的第 9.9.4 节中,强调了:

PostgreSQL 提供了许多返回与当前日期和时间相关的值的函数。这些 SQL 标准函数都基于当前事务的开始时间返回值:

  • CURRENT_DATE
  • CURRENT_TIME
  • CURRENT_TIMESTAMP
  • CURRENT_TIME(precision)
  • CURRENT_TIMESTAMP(precision)
  • LOCALTIME LOCALTIMESTAMP
  • LOCALTIME(precision)
  • LOCALTIMESTAMP(precision)

CURRENT_TIMECURRENT_TIMESTAMP 提供带有时区的值; LOCALTIMELOCALTIMESTAMP 提供无时区的价值。

CURRENT_TIME, CURRENT_TIMESTAMP, LOCALTIME, 和LOCALTIMESTAMP可以选择给定一个精度参数,这会使结果四舍五入到秒字段中的小数位数。如果没有精度参数,则将结果提供给完整的可用精度。

...

由于这些函数返回当前事务的开始时间,因此它们的值在事务期间不会改变。这被认为是一个特性:目的是允许单个事务具有一致的“当前”时间概念,以便同一事务中的多个修改具有相同的时间戳。

注意:其他数据库系统可能会更频繁地推进这些值。

PostgreSQL 还提供了返回当前语句开始时间的函数,以及调用函数时的实际当前时间。非 SQL 标准时间函数的完整列表是:

  • now()
  • transaction_timestamp()
  • statement_timestamp()
  • clock_timestamp()
  • timeofday()

now()是传统的 PostgreSQL 等价于CURRENT_TIMESTAMP. transaction_timestamp()同样等价于CURRENT_TIMESTAMP, 但被命名为清楚地反映它返回的内容。statement_timestamp() 返回当前语句的开始时间(更具体地说,从客户端收到最新命令消息的时间)。 statement_timestamp()transaction_timestamp()在事务的第一个命令期间返回相同的值,但在后续命令期间可能会有所不同。 clock_timestamp()返回实际的当前时间,因此即使在单个 SQL 命令中,它的值也会发生变化。timeofday()是一个历史性的 PostgreSQL 函数。像 clock_timestamp(),它返回实际的当前时间,但作为格式化的文本字符串而不是带有时区值的时间戳。

于 2009-03-20T07:24:44.230 回答
0

我已经向选择时间戳的方法添加了一个提交并解决了问题。

 def get_timestamps(self):
    c = cherrypy.thread_data.db.cursor()
    c.execute("select * from test order by given_time desc limit 10")
    records = c.fetchall()
    c.connection.commit()  # Adding this line fixes the timestamp issue
    c.close()
    return records

当我所做的只是选择时,谁能解释为什么我需要调用 cursor.connection.commit() ?

于 2009-03-19T17:43:58.553 回答