【发布时间】:2023-03-08 03:39:01
【问题描述】:
假设我有一个cars 表,其中vin 是主键。
我想插入一条记录(在事务中)或读取记录(如果已经存在具有相同 PK 的记录)。
如果已经存在具有相同 PK 的记录,那么插入或读取记录的最高效方式是什么?
这是我目前的做法:
案例 A:记录不存在
- 插入记录
- 返回记录
案例 B:记录已存在
- 插入记录
- 检查错误是否是由于记录已存在
- 阅读记录
- 返回记录
const car = { vin: '123', make: 'honda', model: 'accord' };
spannerDatabase.runTransactionAsync(async (databaseTransaction) => {
try {
// Try to insert car
await databaseTransaction.insert('cars', car);
await databaseTransaction.commit();
return car;
} catch (error) {
await databaseTransaction.end();
// Spanner "row already exists" error. Insert failed because there is already a record with the same vin(PK)
if (error.code === 6) {
// Since the record already exists, I want to read it and return it. Whats the most performant way to do this?
const existingRecord = await carsTable.read({
columns: ['vin', 'make', 'model'],
keys: [car.vin],
json: true,
});
return existingRecord;
}
}
})
【问题讨论】:
-
我认为这是实现您想要做的事情的完美方式。只是插入的一个小问题,您可以使用突变 API (example) 来避免传递事务并避免
commit()调用。但是,如果您需要更改代码以读取自己的写入 (RYW),那么您将不得不在事务中使用 DML 查询作为RYW is not supported with the mutations API。
标签: node.js google-cloud-platform google-cloud-spanner