【问题标题】:Get the id of the just-inserted row获取刚刚插入的行的id
【发布时间】:2018-05-14 04:25:03
【问题描述】:

我的实际问题是我需要为每个用户生成唯一的 ID。我在下面详细说明了我是如何尝试这样做的以及我的解决方案给我带来了什么问题。

我正在使用cassandra-driver 插入到我的数据库的这个表中:

CREATE TABLE myspace.unpublished_question (
    user_id uuid PRIMARY KEY,
    account_created timestamp,
    first_name text,
    surname text
)

为了避免冲突,我想我会让 cassandra 为主键列自动生成 uuid,所以我插入如下:

const cassandra = require('cassandra-driver');
const cassandraClient = new cassandra.Client({contactPoints: ['localhost'], keyspace: 'myspace'});

const query = 'insert into user (user_id, account_created, first_name, surname) values (uuid(), ?, ?, ?)';
const params = [new Date(), 'John', 'Smith'];
cassandraClient.execute(query, params, {prepare: true}, (err, results) => {
  console.log('Callback arguments:', err, JSON.stringify(results));
});

但它只记录这个:

Callback: null {"info":{"queriedHost":"127.0.0.1:9042","triedHosts":{},"achievedConsistency":10},"columns":null,"pageState":null}

我无法检索 cassandra 刚刚为此条目生成的 uuid

我怎样才能知道这个 uuid 是什么?

理想情况下,我希望能够执行以下操作:

cassandraClient.execute(query, params, {prepare: true}, (err, results) => {
  const uuid = X;
  console.log('User has been given uuid:', uuid);
});

【问题讨论】:

  • @GrégoryNEUT 只是建议我自己传入 uuid。这当然是可能的,但我如何确保不会引起冲突呢?
  • 查看here。你问的这个问题很好
  • @GrégoryNEUT 所以我将列类型更改为 timeuuid 然后在 JavaScript 中我通过 new Date()?
  • 如果两个插入同时运行会发生什么情况

标签: javascript node.js database cassandra cql


【解决方案1】:

插入操作不提供插入的数据,所以在同一个操作上没有办法从服务器获取。

您需要生成TimeUuid 客户端:

const id = TimeUuid.now();
client.execute(query, [ id, 'John', 'Smith' ], { prepare: true }, (err, result) => {
  // do something with the id
});

有关更多信息,请参阅 TimeUuid 上的 Node.js 文档:http://docs.datastax.com/en/developer/nodejs-driver/latest/features/datatypes/uuids/#time-uuid

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-23
    • 2011-07-31
    • 2011-07-11
    • 2014-04-19
    • 1970-01-01
    • 2011-06-17
    • 1970-01-01
    相关资源
    最近更新 更多