Skip to content

Instantly share code, notes, and snippets.

@kylemocode
Created July 2, 2022 11:59
Show Gist options
  • Save kylemocode/81c6040017ff7e7c8640910bc6cfd552 to your computer and use it in GitHub Desktop.
Save kylemocode/81c6040017ff7e7c8640910bc6cfd552 to your computer and use it in GitHub Desktop.
// 開始一個 transaction
await conn.query("BEGIN");
// 先 select 使用者指定的 seat,並確認 isbooked 的狀態是 false (FOR UPDATE 是關鍵,等等會說明)
const sql = "SELECT * FROM seats where id = $1 and isbooked = 0 FOR UPDATE";
const result = await conn.query(sql, [id]);
if (result.rowCount === 0) {
res.send({"error": "Seat already booked"})
return;
}
// 執行更新
const sqlU= "update seats set isbooked = 1, name = $2 where id = $1"
const updateResult = await conn.query(sqlU,[id, name]);
// 結束 transaction
await conn.query("COMMIT");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment