Created
July 2, 2022 11:59
-
-
Save kylemocode/81c6040017ff7e7c8640910bc6cfd552 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 開始一個 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