如何为数据库中的所有表生成 RethinkDB 变更源

How to generate a RethinkDB changefeed for all tables in a database

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

这是我正在努力实现的一些 'pseudo-code':

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 数据库。

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

如何监控两个表的变化?

我结束了 运行 每个 table 在单独线程中的更改提要:

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 连接对象,因为这些对象不是线程安全的。

为了测试该方法,我在 localhost:8081 打开了网络 UI 并使用了以下 insert 命令:

在 Sublime runner 中,我每次按下 "Run" 按钮时都会看到正在添加的更改:

当我在 insert 命令中选择 table1table2 时,这都有效。

您可以使用 r.union:

在单个查询中关注多个变更源
r.union(
  r.table('table1').changes(),
  r.table('table2').changes()
).run(conn)