| 1 | import { DatabaseSync } from "node:sqlite"; |
| 2 | import { mkdirSync } from "node:fs"; |
| 3 | import { dirname } from "node:path"; |
| 4 | |
| 5 | export function openDatabase (filePath) |
| 6 | { |
| 7 | mkdirSync(dirname(filePath), { recursive: true }); |
| 8 | const database = new DatabaseSync(filePath); |
| 9 | database.exec("PRAGMA journal_mode = WAL"); |
| 10 | database.exec("PRAGMA foreign_keys = ON"); |
| 11 | return database; |
| 12 | } |
| 13 | |
| 14 | export function withTransaction (database, fn) |
| 15 | { |
| 16 | database.exec("BEGIN"); |
| 17 | try |
| 18 | { |
| 19 | const result = fn(); |
| 20 | database.exec("COMMIT"); |
| 21 | return result; |
| 22 | } |
| 23 | catch (error) |
| 24 | { |
| 25 | database.exec("ROLLBACK"); |
| 26 | throw error; |
| 27 | } |
| 28 | } |