Skip to content

Instantly share code, notes, and snippets.

@taktamur
Last active May 31, 2025 10:40
Show Gist options
  • Save taktamur/6a5929bf1f7f0d9a59cbfe875ce6d6a7 to your computer and use it in GitHub Desktop.
Save taktamur/6a5929bf1f7f0d9a59cbfe875ce6d6a7 to your computer and use it in GitHub Desktop.

このディレクトリは、deno で sqlite の排他制御の動作確認を行うファイルを置いてます。

deno run --allow-read --allow-write writer.ts # 排他制御をかけて数秒止まる
deno run --allow-read --allow-write reader.ts # 制御が解除されるまで待つ

例えば、ターミナルを3つ開いて、(1)writer (2)writer (3)reader の順番で動かすと (1)→(2)→(3)の順番に、ちゃんとロックが解除されるまで待つ動作をしている。

import { DB } from "https://deno.land/x/[email protected]/mod.ts";
try {
const db = new DB("test.db");
console.log("Trying SELECT...");
const results = [...db.query("SELECT * FROM test")];
for (const [id, value] of results) {
console.log({ id, value });
}
db.close();
} catch (err) {
console.error("ERROR:", err);
}
import { DB } from "https://deno.land/x/[email protected]/mod.ts";
const db = new DB("test.db");
db.execute(`
CREATE TABLE IF NOT EXISTS test (
id INTEGER PRIMARY KEY AUTOINCREMENT,
value TEXT
)
`);
console.log("BEGIN EXCLUSIVE TRANSACTION");
db.execute("BEGIN EXCLUSIVE"); // 排他ロック取得
console.log("Inserting...");
db.execute("INSERT INTO test (value) VALUES ('locked from writer')");
// 15秒間ロックを保持
await new Promise((resolve) => setTimeout(resolve, 15000));
console.log("Committing...");
db.execute("COMMIT");
db.close();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment