1

我正在测试一个在 RethinkDB 数据库的多个表中插入或删除数据的 API。为了在使用 API 时监控数据库发生的情况,我想打印所有表中的更改。

这是我想要实现的一些“伪代码”:

import rethinkdb as r

# Prior to running this script, run "rethinkdb --port-offset 1" at the command line
conn = r.connect('localhost', 28016)
if 'test' in r.db_list().run(conn):
    r.db_drop('test').run(conn)
r.db_create('test').run(conn)

r.table_create('table1').run(conn)
r.table_create('table2').run(conn)

feed = r.table('table1' and 'table2').changes().run(conn)
for document in feed:
    print document

在运行此脚本之前,我将运行rethinkdb --port-offset 1以初始化 RethinkDB 数据库。

运行此脚本后,我想将数据插入table1table2(例如,使用 web UI at localhost:8081)并查看运行脚本的终端中打印的更改。但是,这似乎不起作用,因为r.table('table1' and 'table2')可能不是有效的 ReQL 查询。

如何监控两个表中的更改?

4

2 回答 2

6

您可以使用以下命令在单个查询中跟踪多个更改提要r.union

r.union(
  r.table('table1').changes(),
  r.table('table2').changes()
).run(conn)
于 2017-01-10T18:18:07.783 回答
1

我最终在一个单独的线程中为每个表运行 changefeeds:

import rethinkdb as r
import threading

# Prior to running this script, run "rethinkdb --port-offset 1" at the command line
conn = r.connect('localhost', 28016)

def clear_test_database():
    '''Clear the contents of the "test" database by dropping and re-creating it.'''
    if 'test' in r.db_list().run(conn):
        r.db_drop('test').run(conn)
    r.db_create('test').run(conn)

clear_test_database()

def monitor_changes(table_name, conn):
    feed = r.table(table_name).changes().run(conn)
    for document in feed:
        print document

tables = ['table1', 'table2']

for table in tables:
    conn = r.connect('localhost', 28016)
    r.table_create(table).run(conn)
    thread = threading.Thread(target=monitor_changes, args=(table, conn))
    thread.start()

请注意,我在 for 循环中重新定义了conn连接对象,因为这些对象不是线程安全的。

为了测试该方法,我打开了 Web UIlocalhost:8081并使用了以下insert命令:

在此处输入图像描述

在 Sublime 运行器中,每次按下“运行”按钮时,我都会看到添加的更改:

在此处输入图像描述

这在我选择table1table2insert命令中都有效。

于 2017-01-09T14:20:45.043 回答