Search code examples
pythonrethinkdbrethinkdb-python

How to check if table exists in RethinkDB with Python


I wish to check if a table already exists in RethinkDB with the python client before trying to create the table. If you try to create the table and it exists it throws an error. So how can I check that? My code looks like this :

from rethinkdb import RethinkDB
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()


r.db("test").table_create("instruments").run()

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 check < 0.5 and check >0.25:
    r.table("instruments").insert(instrument()).run()

  if  check < 0.25:
    cursor = r.table("instruments").filter( r.row["category"].count() > 2 ).delete().run()

  sleep(1)

Solution

  • This works :

    try:
      r.db("test").table_drop("instruments").run()
    except:
      pass
    
    r.db("test").table_create("instruments").run()
    

    I couldnt find a suggested way anywhere. They should maybe add such a method.