1/**
2 * Compatibility shim that wraps Bun's built-in bun:sqlite module to match
3 * the subset of the sqlite3 npm package's callback API that sequelize uses.
4 *
5 * This lets sequelize use bun:sqlite directly, which is embedded in the bun
6 * runtime and works in compiled binaries without native node_modules.
7 */
8import { Database as BunDatabase } from "bun:sqlite";
9
10const OPEN_READONLY = 0x00000001;
11const OPEN_READWRITE = 0x00000002;
12const OPEN_CREATE = 0x00000004;
13
14const parseArgs = (args) => {
15 let params = [];
16 let callback;
17 for (const arg of args) {
18 if (typeof arg === "function") callback = arg;
19 else if (Array.isArray(arg)) params = arg;
20 else if (arg !== null && typeof arg === "object") params = arg;
21 else if (arg !== undefined) params.push(arg);
22 }
23 return [params, callback];
24};
25
26class Database {
27 constructor(filename, mode, callback) {
28 try {
29 const readonly = typeof mode === "number" && !(mode & OPEN_READWRITE);
30 this.db = new BunDatabase(filename, { readonly, create: !readonly });
31 this.filename = filename;
32 this.db.exec("PRAGMA journal_mode = WAL");
33 if (callback) process.nextTick(() => callback(null));
34 } catch (err) {
35 if (callback) process.nextTick(() => callback(err));
36 else throw err;
37 }
38 }
39
40 run(sql, ...args) {
41 const [params, callback] = parseArgs(args);
42 try {
43 const result = this.db.prepare(sql).run(params);
44
45 const context = { lastID: result.lastInsertRowid, changes: result.changes, sql };
46 if (callback) process.nextTick(() => callback.call(context, null));
47 } catch (err) {
48 if (callback) process.nextTick(() => callback.call({}, err));
49 }
50 return this;
51 }
52
53 all(sql, ...args) {
54 const [params, callback] = parseArgs(args);
55 try {
56 const rows = this.db.prepare(sql).all(params);
57 if (callback) process.nextTick(() => callback(null, rows));
58 } catch (err) {
59 if (callback) process.nextTick(() => callback(err, []));
60 }
61 return this;
62 }
63
64 serialize(fn) {
65 if (fn) fn();
66 return this;
67 }
68
69 close(callback) {
70 try {
71 this.db.close();
72 if (callback) process.nextTick(() => callback(null));
73 } catch (err) {
74 if (callback) process.nextTick(() => callback(err));
75 }
76 return this;
77 }
78}
79
80const sqlite3 = { Database, OPEN_READONLY, OPEN_READWRITE, OPEN_CREATE };
81
82export default sqlite3;
83export { Database, OPEN_READONLY, OPEN_READWRITE, OPEN_CREATE };
84