In RethinkDB, what is the easiest way to check if a database or a table exists?

André Pena picture André Pena · Jul 25, 2015 · Viewed 10.8k times · Source

One way I know I can do it is by listing throughdbList() and tableList() and then looking for what I want in the results.

Is there an easier way?

EDIT

My goal is to create a table in case it doesn't exist.

Answer

Tholle picture Tholle · Jul 26, 2015

If you want to create a database if it does not exists, or get a value like "database already exists" if it does exist, you could do something like the following:

r.dbList().contains('example_database')
  .do(function(databaseExists) {
    return r.branch(
      databaseExists,
      { dbs_created: 0 },
      r.dbCreate('example_database')
    );
  }).run();

It will return the following if it is created:

{
  "config_changes": [
    {
      "new_val": {
        "id": "1ee7ddb4-6e2c-43bb-a0f5-64ef6a6211a8",
        "name": "example_database"
      },
      "old_val": null
    }
  ],
  "dbs_created": 1
}

And this if it already exists:

{
  "dbs_created": 0
}