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

前端 未结 3 467
庸人自扰
庸人自扰 2021-02-05 05:04

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 wa

相关标签:
3条回答
  • 2021-02-05 05:23

    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;
            }
        });
      }
    
    0 讨论(0)
  • 2021-02-05 05:32

    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)
    
    0 讨论(0)
  • 2021-02-05 05:36

    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
    }
    
    0 讨论(0)
提交回复
热议问题