在 RethinkDB 中,检查数据库或 table 是否存在的最简单方法是什么?

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

我知道我可以做到的一种方法是列出 dbList()tableList(),然后在结果中寻找我想要的内容。

有没有更简单的方法?

编辑

我的目标是创建一个 table 以防它不存在。

如果你想创建一个不存在的数据库,或者如果它存在就得到一个像 "database already exists" 这样的值,你可以做如下的事情:

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

如果创建,它将return以下内容:

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

这个如果已经存在的话:

{
  "dbs_created": 0
}

对于 table 现有检查,我找到了以下解决方案:

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

这将为您返回在默认数据库中定义的 table 数组,例如:['people']。 (如果你想设置它,请这样做:connection.use('test');)

然后我们可以检查数组是否包含我们要创建的 table 名称。

_.some(tableNames, tableName)

放在一起:

  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;
        }
    });
  }

在JavaScript中,给定一个包含table个名字的数组,最短的路径是

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

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

对于来自 VB.net 的任何人,那么解决方案就是这样.. 一个班轮

Dim RDBDatabase as String = "dbName" 
Dim RDBTable as String = "tableName"  
   
Dim CheckDB = R.DbList().Contains(RDBDatabase).Do_(Function(databaseExists) R.Branch(databaseExists, "db done", R.DbCreate(RDBDatabase))).And(R.Db(RDBDatabase).TableList().Contains(RDBTable).Do_(Function(tableExists) R.Branch(tableExists, "tb done", R.Db(RDBDatabase).TableCreate(RDBTable)))).Run(conn)

如果 DB 不存在,这将创建它,如果它不存在,将创建 table

如果两者都不存在,那么它将 return 来自最后创建的值,即 table

{{
  "config_changes": [
    {
      "new_val": {
        "db": "dbName",
        "durability": "hard",
        "id": "0f72a570-7998-49f7-affc-96cbdd1ea086",
        "indexes": [],
        "name": "tableName",
        "primary_key": "id",
        "shards": [
          {
            "nonvoting_replicas": [],
            "primary_replica": "replicasssss_iu1",
            "replicas": [
              "replicasssss_iu1"
            ]
          }
        ],
        "write_acks": "majority"
      },
      "old_val": null
    }
  ],
  "tables_created": 1
}}