如何使用Python客户端检查RethinkDB中的表是否已存在
RethinkDB Python 客户端建表前存在性检查实现
核心思路
直接调用table_create()创建已存在的表会触发RethinkDB运行时错误,可通过预检查或异常捕获的方式规避该问题,两种实现方式可按需选择:
- 表列表预判断:通过
table_list()接口拉取目标数据库下的全量表名,确认目标表不存在后再执行建表操作,适合单实例初始化场景,逻辑直观无额外异常开销 - 异常捕获兜底:直接尝试执行建表语句,捕获「表已存在」类型的运行时错误后直接跳过,其余错误正常抛出,适合多实例并发初始化场景,能规避检查和建表操作之间的竞态问题
代码修改示例
原有代码中直接建表的片段:
r.db("test").table_create("instruments").run()
替换为预检查逻辑即可:
# 拉取test库下所有已存在的表名 existing_tables = r.db("test").table_list().run() if "instruments" not in existing_tables: r.db("test").table_create("instruments").run()
如果需要兼容并发场景,可搭配异常捕获做兜底:
from rethinkdb.errors import RqlRuntimeError try: r.db("test").table_create("instruments").run() except RqlRuntimeError as e: # 仅忽略表已存在的错误,其余错误正常抛出 if "already exists" not in str(e): raise e
修改后的完整可运行代码
from rethinkdb import RethinkDB from rethinkdb.errors import RqlRuntimeError from faker import Faker from faker_music import MusicProvider from random import random from time import sleep fake = Faker() fake.add_provider(MusicProvider) r = RethinkDB() r.connect("localhost", 28015).repl() # 带存在性检查的建表逻辑 existing_tables = r.db("test").table_list().run() if "instruments" not in existing_tables: try: r.db("test").table_create("instruments").run() except RqlRuntimeError as e: if "already exists" not in str(e): raise e def instrument()->dict: instrument = {"name":fake.music_instrument(),"category":fake.music_instrument_category()} return instrument initial = [instrument() for _ in range(3)] r.table("instruments").insert(initial).run() while True: check = random() if 0.25 < check < 0.5: r.table("instruments").insert(instrument()).run() if check < 0.25: r.table("instruments").filter(r.row["category"].count() > 2).delete().run() sleep(1)
内容的提问来源于stack exchange,提问作者KZiovas
相关产品推荐
相关产品推荐

