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

邮差的信 提交于 2019-12-03 10:52:41

问题


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.


回答1:


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
}



回答2:


For the table existing checking I have found the following solution:

r.tableList().run(connection); //['people']

this will give you back an array of the tables which are defined on the default DB for example: ['people']. (if you want to set it do this: connection.use('test');)

then we can check if the array is containing our table name to create.

_.some(tableNames, tableName)

put it all together:

  if (!_.isNil(tableName) && _.isString(tableName) && !_.isNil(connection)) {
    r.tableList().run(connection).then(function(tableNames) {
      if (_.includes(tableNames, tableName)) {
        return r.tableCreate(tableName).run(connection);
      } else {
        return;
        }
    });
  }



回答3:


In JavaScript, given an array of table names, the shortest way is

const tables = ['table1Name', 'table2Name', ...]
const db = 'myDb'

r(tables)
    .difference(r.db(db).tableList())
    .forEach(table => r.db(db).tableCreate(table))
    .run(connection)


来源:https://stackoverflow.com/questions/31625913/in-rethinkdb-what-is-the-easiest-way-to-check-if-a-database-or-a-table-exists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!