@seip/bluebird-js 0.1.7 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/AGENTS.md +727 -620
  2. package/README.md +670 -607
  3. package/app/models/user.js +19 -0
  4. package/app/resources/html/home.html +137 -0
  5. package/app/resources/html/layouts/main.html +55 -0
  6. package/app/resources/html/notFound.html +14 -0
  7. package/app/resources/html/table.html +15 -0
  8. package/app/resources/html/terms.html +46 -0
  9. package/app/resources/index.html +27 -0
  10. package/app/resources/layouts/AppLayout.jsx +92 -0
  11. package/app/resources/main.jsx +18 -0
  12. package/app/resources/pages/Dashboard.jsx +93 -0
  13. package/app/resources/pages/Home.jsx +140 -0
  14. package/app/resources/pages/Login.jsx +35 -0
  15. package/app/resources/pages/NotFound.jsx +16 -0
  16. package/app/resources/pages/Register.jsx +55 -0
  17. package/app/resources/pages/TableDemo.jsx +85 -0
  18. package/app/resources/routes.jsx +59 -0
  19. package/app/resources/spa.js +73 -0
  20. package/app/resources/styles.css +9 -0
  21. package/app/routes/api.js +129 -50
  22. package/app/routes/auth.js +209 -0
  23. package/app/routes/web.js +89 -47
  24. package/core/ai.js +30 -10
  25. package/core/app.d.ts +2 -18
  26. package/core/app.js +987 -801
  27. package/core/auth.d.ts +2 -13
  28. package/core/auth.js +444 -326
  29. package/core/cli/build.js +37 -0
  30. package/core/cli/dev.js +155 -0
  31. package/core/cli/doctor.js +37 -2
  32. package/core/cli/export.js +191 -0
  33. package/core/cli/init.js +91 -322
  34. package/core/cli/nginx.js +1 -1
  35. package/core/cli/templates.js +139 -0
  36. package/core/cli/view.js +98 -161
  37. package/core/config.js +44 -2
  38. package/core/csrf.js +156 -24
  39. package/core/database.js +1184 -1131
  40. package/core/debug.js +1 -1
  41. package/core/html.js +8 -1
  42. package/core/index.d.ts +126 -310
  43. package/core/paths.js +55 -0
  44. package/core/ratelimit.js +10 -1
  45. package/core/react/client/api.js +239 -0
  46. package/core/react/client/auth.js +236 -0
  47. package/core/react/client/components.js +1321 -0
  48. package/core/react/client/datatable.js +595 -0
  49. package/core/react/client/i18n.js +440 -0
  50. package/core/react/client/index.d.ts +314 -0
  51. package/core/react/client/index.js +50 -0
  52. package/core/react/client/router.js +26 -0
  53. package/core/react/client/theme.css +512 -0
  54. package/core/render-cache.js +250 -212
  55. package/core/render.d.ts +25 -21
  56. package/core/render.js +738 -736
  57. package/core/router.d.ts +2 -3
  58. package/core/router.js +171 -171
  59. package/core/seo.js +10 -0
  60. package/core/spa.js +599 -0
  61. package/core/view-loader.js +155 -613
  62. package/core/vite-plugin.d.ts +18 -0
  63. package/core/vite-plugin.js +162 -0
  64. package/core/vite.js +250 -145
  65. package/index.js +22 -18
  66. package/jsconfig.json +5 -3
  67. package/package.json +114 -92
  68. package/production.md +8 -3
  69. package/public/js/bluebird.js +1886 -0
  70. package/templates/_auth/app/database.js +19 -0
  71. package/templates/_auth/app/models/user.js +22 -0
  72. package/templates/_auth/app/routes/auth-router.js +304 -0
  73. package/templates/_base/app/resources/html/layouts/main.html +55 -0
  74. package/templates/_base/app/resources/html/notFound.html +14 -0
  75. package/templates/_base/app/resources/index.html +27 -0
  76. package/templates/_base/app/resources/styles.css +9 -0
  77. package/templates/api/app/models/note.js +18 -0
  78. package/templates/api/app/routes/api.js +82 -0
  79. package/templates/api/app/routes/auth.js +11 -0
  80. package/templates/api/index.js +19 -0
  81. package/templates/api/template.json +13 -0
  82. package/templates/auth/app/mail.js +11 -0
  83. package/templates/auth/app/models/password_reset.js +18 -0
  84. package/templates/auth/app/resources/html/home.html +21 -0
  85. package/templates/auth/app/resources/html/partials/nav.html +2 -0
  86. package/templates/auth/app/resources/layouts/AppLayout.jsx +60 -0
  87. package/templates/auth/app/resources/main.jsx +18 -0
  88. package/templates/auth/app/resources/pages/Dashboard.jsx +51 -0
  89. package/templates/auth/app/resources/pages/ForgotPassword.jsx +34 -0
  90. package/templates/auth/app/resources/pages/Login.jsx +36 -0
  91. package/templates/auth/app/resources/pages/NotFound.jsx +16 -0
  92. package/templates/auth/app/resources/pages/Profile.jsx +99 -0
  93. package/templates/auth/app/resources/pages/Register.jsx +50 -0
  94. package/templates/auth/app/resources/pages/ResetPassword.jsx +50 -0
  95. package/templates/auth/app/resources/routes.jsx +54 -0
  96. package/templates/auth/app/resources/spa.js +29 -0
  97. package/templates/auth/app/routes/api.js +17 -0
  98. package/templates/auth/app/routes/auth.js +13 -0
  99. package/templates/auth/app/routes/web.js +21 -0
  100. package/templates/auth/index.js +19 -0
  101. package/templates/auth/template.json +15 -0
  102. package/templates/blank/app/models/.gitkeep +0 -0
  103. package/templates/blank/app/resources/html/home.html +27 -0
  104. package/templates/blank/app/resources/html/partials/nav.html +1 -0
  105. package/templates/blank/app/resources/main.jsx +16 -0
  106. package/templates/blank/app/resources/pages/Home.jsx +42 -0
  107. package/templates/blank/app/resources/pages/NotFound.jsx +27 -0
  108. package/templates/blank/app/resources/routes.jsx +15 -0
  109. package/templates/blank/app/resources/spa.js +24 -0
  110. package/templates/blank/app/routes/api.js +11 -0
  111. package/templates/blank/app/routes/web.js +21 -0
  112. package/templates/blank/index.js +13 -0
  113. package/templates/blank/template.json +12 -0
  114. package/templates/blog/app/lib/blog.js +149 -0
  115. package/templates/blog/app/models/post.js +22 -0
  116. package/templates/blog/app/resources/html/home.html +28 -0
  117. package/templates/blog/app/resources/html/not-found.html +5 -0
  118. package/templates/blog/app/resources/html/partials/nav.html +2 -0
  119. package/templates/blog/app/resources/html/partials/post-card.html +9 -0
  120. package/templates/blog/app/resources/html/post.html +8 -0
  121. package/templates/blog/app/resources/layouts/AdminLayout.jsx +54 -0
  122. package/templates/blog/app/resources/main.jsx +18 -0
  123. package/templates/blog/app/resources/pages/Login.jsx +31 -0
  124. package/templates/blog/app/resources/pages/NotFound.jsx +16 -0
  125. package/templates/blog/app/resources/pages/PostEditor.jsx +51 -0
  126. package/templates/blog/app/resources/pages/Posts.jsx +83 -0
  127. package/templates/blog/app/resources/pages/Register.jsx +43 -0
  128. package/templates/blog/app/resources/routes.jsx +51 -0
  129. package/templates/blog/app/resources/spa.js +25 -0
  130. package/templates/blog/app/resources/styles.css +40 -0
  131. package/templates/blog/app/routes/api.js +77 -0
  132. package/templates/blog/app/routes/auth.js +10 -0
  133. package/templates/blog/app/routes/web.js +114 -0
  134. package/templates/blog/index.js +21 -0
  135. package/templates/blog/template.json +14 -0
  136. package/vite.config.js +11 -0
  137. package/app/views/components/Header.jsx +0 -42
  138. package/app/views/components/LiveCounter.jsx +0 -67
  139. package/app/views/layouts/main/view.jsx +0 -201
  140. package/app/views/legal/terms.html +0 -29
  141. package/app/views/pages/about.jsx +0 -98
  142. package/app/views/pages/dashboard.jsx +0 -278
  143. package/app/views/pages/index.jsx +0 -123
  144. package/app/views/pages/login.jsx +0 -141
  145. package/core/actions.d.ts +0 -4
  146. package/core/actions.js +0 -355
  147. package/core/jsx.d.ts +0 -38
  148. package/core/jsx.js +0 -1597
  149. package/core/vite.d.ts +0 -3
  150. package/public/js/bluebird-client.js +0 -3265
  151. package/public/js/tailwind.js +0 -8
package/core/database.js CHANGED
@@ -1,1131 +1,1184 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
- import crypto from "node:crypto";
4
- import zlib from "node:zlib";
5
- import { execSync } from "node:child_process";
6
- import Config from "./config.js";
7
- import Cache from "./cache.js";
8
-
9
- const rawDbType = (process.env.DB_TYPE || "").toLowerCase().trim();
10
- let DB_TYPE = "";
11
-
12
- if (
13
- rawDbType === "sqlite" ||
14
- rawDbType === "sqlite3" ||
15
- rawDbType === "sql" ||
16
- rawDbType === "better-sqlite3" ||
17
- rawDbType === "better-sqlite" ||
18
- rawDbType === "lite"
19
- ) {
20
- DB_TYPE = "sqlite";
21
- } else if (
22
- rawDbType === "postgres" ||
23
- rawDbType === "postgresql" ||
24
- rawDbType === "pg" ||
25
- rawDbType === "psql" ||
26
- rawDbType === "pgsql" ||
27
- rawDbType === "postgre" ||
28
- rawDbType === "postgr" ||
29
- rawDbType === "psgr"
30
- ) {
31
- DB_TYPE = "postgres";
32
- } else if (
33
- rawDbType === "mysql" ||
34
- rawDbType === "mariadb" ||
35
- rawDbType === "maria" ||
36
- rawDbType === "my"
37
- ) {
38
- DB_TYPE = "mysql";
39
- } else if (
40
- rawDbType === "none" ||
41
- rawDbType === "no" ||
42
- rawDbType === "false" ||
43
- rawDbType === "null" ||
44
- rawDbType === "0"
45
- ) {
46
- DB_TYPE = "none";
47
- }
48
-
49
- if (
50
- !DB_TYPE &&
51
- process.env.DATABASE_URL &&
52
- !process.env.DATABASE_URL.startsWith("#")
53
- ) {
54
- if (
55
- process.env.DATABASE_URL.startsWith("postgres://") ||
56
- process.env.DATABASE_URL.startsWith("postgresql://")
57
- ) {
58
- DB_TYPE = "postgres";
59
- } else if (process.env.DATABASE_URL.startsWith("mysql://")) {
60
- DB_TYPE = "mysql";
61
- } else if (
62
- process.env.DATABASE_URL.startsWith("sqlite://") ||
63
- process.env.DATABASE_URL.startsWith("sqlite:")
64
- ) {
65
- DB_TYPE = "sqlite";
66
- }
67
- }
68
- if (!DB_TYPE) {
69
- DB_TYPE = "sqlite";
70
- }
71
-
72
- let mysqlPromise = null;
73
- let pgPromise = null;
74
- let sqlitePromise = null;
75
-
76
- if (DB_TYPE === "postgres") {
77
- try {
78
- pgPromise = await import("pg");
79
- } catch (err) {
80
- console.error("[DATABASE ERROR] pg package is not installed. Database wrapper is disabled.");
81
- }
82
- } else if (DB_TYPE === "mysql") {
83
- try {
84
- mysqlPromise = await import("mysql2/promise");
85
- } catch (err) {
86
- console.error("[DATABASE ERROR] mysql2 package is not installed. Database wrapper is disabled.");
87
- }
88
- } else if (DB_TYPE === "sqlite") {
89
- try {
90
- const { DatabaseSync } = await import("node:sqlite");
91
- const testDb = new DatabaseSync(":memory:");
92
- testDb.close();
93
- sqlitePromise = { source: "node:sqlite", DatabaseSync };
94
- } catch {
95
- try {
96
- const mod = await import("better-sqlite3");
97
- sqlitePromise = { source: "better-sqlite3", BetterSqlite: mod.default || mod };
98
- } catch {
99
- console.error(
100
- "[DATABASE] No SQLite driver available. Node.js 22.18+ required for node:sqlite, or install better-sqlite3."
101
- );
102
- }
103
- }
104
- }
105
-
106
- /**
107
- * Replaces ? parameter placeholders with $1, $2, etc., ignoring quoted string literals.
108
- * @param {string} sql
109
- * @returns {string}
110
- */
111
- function toPostgresSql(sql) {
112
- let paramIndex = 1;
113
- let inSingleQuote = false;
114
- let inDoubleQuote = false;
115
- let result = "";
116
-
117
- for (let i = 0; i < sql.length; i++) {
118
- const char = sql[i];
119
- const prev = i > 0 ? sql[i - 1] : "";
120
-
121
- if (char === "'" && prev !== "\\" && !inDoubleQuote) {
122
- inSingleQuote = !inSingleQuote;
123
- result += char;
124
- } else if (char === '"' && prev !== "\\" && !inSingleQuote) {
125
- inDoubleQuote = !inDoubleQuote;
126
- result += char;
127
- } else if (char === "?" && !inSingleQuote && !inDoubleQuote) {
128
- result += `$${paramIndex++}`;
129
- } else {
130
- result += char;
131
- }
132
- }
133
-
134
- return result;
135
- }
136
-
137
- const _activeDatabases = new Set();
138
-
139
- /**
140
- * Generates an ISO-safe timestamp string formatted for filenames across OS platforms.
141
- * @returns {string}
142
- */
143
- function getBackupTimestamp() {
144
- const now = new Date();
145
- const pad = (n) => String(n).padStart(2, "0");
146
- const year = now.getFullYear();
147
- const month = pad(now.getMonth() + 1);
148
- const day = pad(now.getDate());
149
- const hours = pad(now.getHours());
150
- const mins = pad(now.getMinutes());
151
- const secs = pad(now.getSeconds());
152
- const ms = String(now.getMilliseconds()).padStart(3, "0");
153
- return `${year}-${month}-${day}_${hours}${mins}${secs}_${ms}`;
154
- }
155
-
156
- /**
157
- * Rotates backups in backupDir, keeping only the most recent N backups.
158
- * @param {string} backupDir
159
- * @param {string} prefix
160
- * @param {number} [keep=10]
161
- * @returns {number} Count of deleted backups.
162
- */
163
- function rotateBackups(backupDir, prefix, keep = 10) {
164
- if (!fs.existsSync(backupDir) || keep <= 0) return 0;
165
- try {
166
- const files = fs.readdirSync(backupDir)
167
- .filter((file) => file.startsWith(prefix))
168
- .map((file) => {
169
- const fullPath = path.join(backupDir, file);
170
- return {
171
- file,
172
- fullPath,
173
- mtime: fs.statSync(fullPath).mtimeMs,
174
- };
175
- })
176
- .sort((a, b) => b.mtime - a.mtime);
177
-
178
- let deleted = 0;
179
- if (files.length > keep) {
180
- for (let i = keep; i < files.length; i++) {
181
- try {
182
- fs.unlinkSync(files[i].fullPath);
183
- deleted++;
184
- } catch {}
185
- }
186
- }
187
- return deleted;
188
- } catch {
189
- return 0;
190
- }
191
- }
192
-
193
- /**
194
- * Database class wrapping native node:sqlite, mysql2, and pg with pooling and multi-level caching.
195
- */
196
- class Database {
197
- /**
198
- * Initializes database connection parameters.
199
- * @param {number} [connectionLimit=10]
200
- * @param {number} [queueLimit=0]
201
- * @param {Object} [config={}]
202
- */
203
- constructor(connectionLimit = 10, queueLimit = 0, config = {}) {
204
- this.pool = null;
205
- this.db = null;
206
- this.type = config.DB_TYPE || DB_TYPE;
207
- this._stmtCache = new Map();
208
- this._maxStatements = 500;
209
-
210
- let defaultSqliteFile = process.env.DB_FILE || "database/blue_bird.db";
211
- let busyTimeout = 5000;
212
- let journalMode = "WAL";
213
- let synchronous = "NORMAL";
214
-
215
- if (process.env.DATABASE_URL && !process.env.DATABASE_URL.startsWith("#")) {
216
- try {
217
- if (
218
- process.env.DATABASE_URL.startsWith("sqlite://") ||
219
- process.env.DATABASE_URL.startsWith("sqlite:")
220
- ) {
221
- const rawUrl = process.env.DATABASE_URL;
222
- const cleanUrl = rawUrl.replace(/^sqlite:\/\/|^sqlite:/, "");
223
- const [filePath, queryStr] = cleanUrl.split("?");
224
- if (filePath) {
225
- defaultSqliteFile = filePath;
226
- }
227
- if (queryStr) {
228
- const params = new URLSearchParams(queryStr);
229
- if (params.has("busy_timeout")) {
230
- busyTimeout = parseInt(params.get("busy_timeout"), 10) || busyTimeout;
231
- }
232
- if (params.has("journal_mode")) {
233
- journalMode = params.get("journal_mode").toUpperCase();
234
- }
235
- if (params.has("synchronous")) {
236
- synchronous = params.get("synchronous").toUpperCase();
237
- }
238
- }
239
- }
240
- } catch (err) {
241
- console.error("[DATABASE ERROR] Failed to parse SQLite DATABASE_URL:", err.message);
242
- }
243
- }
244
-
245
- this.sqliteConfig = {
246
- filename: config.DB_FILE || defaultSqliteFile,
247
- busyTimeout: config.busyTimeout || busyTimeout,
248
- journalMode: config.journalMode || journalMode,
249
- synchronous: config.synchronous || synchronous,
250
- };
251
-
252
- this.config = {
253
- ...config,
254
- host: process.env.DB_HOST || "localhost",
255
- user: process.env.DB_USER || (this.type === "postgres" ? "postgres" : "root"),
256
- password: process.env.DB_PASSWORD || "root",
257
- database: process.env.DB_NAME || "blue_bird",
258
- port: parseInt(process.env.DB_PORT, 10) || (this.type === "postgres" ? 5432 : 3306),
259
- charset: "utf8mb4",
260
- waitForConnections: true,
261
- connectionLimit: connectionLimit,
262
- queueLimit: queueLimit,
263
- max: connectionLimit,
264
- };
265
-
266
- if (process.env.DATABASE_URL && !process.env.DATABASE_URL.startsWith("#")) {
267
- try {
268
- if (
269
- process.env.DATABASE_URL.startsWith("mysql://") ||
270
- process.env.DATABASE_URL.startsWith("postgres://") ||
271
- process.env.DATABASE_URL.startsWith("postgresql://")
272
- ) {
273
- const url = new URL(process.env.DATABASE_URL);
274
- this.config.host = url.hostname;
275
- this.config.port = parseInt(url.port, 10) || (this.type === "postgres" ? 5432 : 3306);
276
- this.config.user = url.username;
277
- this.config.password = url.password;
278
- this.config.database = url.pathname.substring(1);
279
- this.config.connectionString = process.env.DATABASE_URL;
280
- }
281
- } catch (err) {
282
- console.error("[DATABASE ERROR] Failed to parse DATABASE_URL:", err.message);
283
- }
284
- }
285
-
286
- _activeDatabases.add(this);
287
- }
288
-
289
- /**
290
- * Retrieves or creates a prepared statement with LRU caching.
291
- * @private
292
- * @param {string} sql
293
- * @returns {*} Prepared statement.
294
- */
295
- _getPreparedStatement(sql) {
296
- let stmt = this._stmtCache.get(sql);
297
- if (stmt) return stmt;
298
-
299
- stmt = this.db.prepare(sql);
300
- if (this._stmtCache.size >= this._maxStatements) {
301
- const oldestKey = this._stmtCache.keys().next().value;
302
- if (oldestKey !== undefined) this._stmtCache.delete(oldestKey);
303
- }
304
- this._stmtCache.set(sql, stmt);
305
- return stmt;
306
- }
307
-
308
- /**
309
- * Initializes connection pool or SQLite database.
310
- * @param {number} [retries=3]
311
- * @returns {Promise<boolean>}
312
- */
313
- async init(retries = 3) {
314
- if (!mysqlPromise && !pgPromise && !sqlitePromise) return false;
315
- _activeDatabases.add(this);
316
- if (this.pool || this.db) return true;
317
-
318
- if (this.type === "sqlite" && sqlitePromise) {
319
- try {
320
- const isMemoryDb = this.sqliteConfig.filename === ":memory:";
321
- const userDataBase = Config.userDataDir();
322
- const dbFilePath = isMemoryDb
323
- ? ":memory:"
324
- : path.isAbsolute(this.sqliteConfig.filename)
325
- ? this.sqliteConfig.filename
326
- : path.resolve(userDataBase, this.sqliteConfig.filename);
327
-
328
- if (!isMemoryDb) {
329
- const dir = path.dirname(dbFilePath);
330
- if (!fs.existsSync(dir)) {
331
- fs.mkdirSync(dir, { recursive: true });
332
- }
333
-
334
- if (!fs.existsSync(dbFilePath)) {
335
- const candidatePaths = [
336
- path.resolve(Config.appDir(), this.sqliteConfig.filename),
337
- process.resourcesPath ? path.join(process.resourcesPath, this.sqliteConfig.filename) : null,
338
- process.resourcesPath ? path.join(process.resourcesPath, "database", path.basename(this.sqliteConfig.filename)) : null,
339
- Config.appDir().includes(".asar")
340
- ? path.resolve(Config.appDir().replace(/\.asar(?=[\/\\]|$)/, ".asar.unpacked"), this.sqliteConfig.filename)
341
- : null,
342
- path.resolve(process.cwd(), this.sqliteConfig.filename),
343
- ].filter(Boolean);
344
-
345
- for (const candidate of candidatePaths) {
346
- if (fs.existsSync(candidate) && path.resolve(candidate) !== path.resolve(dbFilePath)) {
347
- try {
348
- fs.copyFileSync(candidate, dbFilePath);
349
- break;
350
- } catch {}
351
- }
352
- }
353
- }
354
- }
355
-
356
- if (sqlitePromise.source === "node:sqlite") {
357
- const { DatabaseSync } = sqlitePromise;
358
- this.db = new DatabaseSync(dbFilePath);
359
- this._sqliteDriver = "node:sqlite";
360
- this.db.exec(`PRAGMA journal_mode = ${this.sqliteConfig.journalMode};`);
361
- this.db.exec(`PRAGMA synchronous = ${this.sqliteConfig.synchronous};`);
362
- this.db.exec(`PRAGMA busy_timeout = ${this.sqliteConfig.busyTimeout};`);
363
- this.db.exec("PRAGMA foreign_keys = ON;");
364
- this.db.exec("PRAGMA temp_store = MEMORY;");
365
- this.db.exec("PRAGMA cache_size = -8000;");
366
- this.db.exec("PRAGMA mmap_size = 268435456;");
367
- } else {
368
- const { BetterSqlite } = sqlitePromise;
369
- this.db = new BetterSqlite(dbFilePath, { timeout: this.sqliteConfig.busyTimeout });
370
- this._sqliteDriver = "better-sqlite3";
371
- this.db.pragma(`journal_mode = ${this.sqliteConfig.journalMode}`);
372
- this.db.pragma(`synchronous = ${this.sqliteConfig.synchronous}`);
373
- this.db.pragma("foreign_keys = ON");
374
- this.db.pragma(`busy_timeout = ${this.sqliteConfig.busyTimeout}`);
375
- this.db.pragma("temp_store = MEMORY");
376
- this.db.pragma("cache_size = -8000");
377
- this.db.pragma("mmap_size = 268435456");
378
- }
379
-
380
- return true;
381
- } catch (err) {
382
- console.error("[DATABASE] Failed to initialize SQLite database:", err.message);
383
- this.db = null;
384
- return false;
385
- }
386
- }
387
-
388
- for (let attempt = 1; attempt <= retries; attempt++) {
389
- try {
390
- if (this.type === "postgres" && pgPromise) {
391
- const pg = pgPromise.default || pgPromise;
392
- this.pool = new pg.Pool(this.config);
393
- await this.pool.query("SELECT 1");
394
- } else if (mysqlPromise) {
395
- const { max, connectionString, ...mysqlConfig } = this.config;
396
- this.pool = mysqlPromise.createPool(mysqlConfig);
397
- await this.pool.query("SELECT 1");
398
- }
399
- return true;
400
- } catch (err) {
401
- this.pool = null;
402
- if (attempt === retries) {
403
- console.error(`[DATABASE ERROR] Connection failed after ${retries} attempts:`, err.message);
404
- return false;
405
- }
406
- await new Promise((resolve) => setTimeout(resolve, 1000));
407
- }
408
- }
409
- return false;
410
- }
411
-
412
- /**
413
- * Runs a SQL query with parameters and formatting options.
414
- * Accurately classifies CTEs (WITH ... SELECT) and RETURNING clauses.
415
- * Multi-level caching supports both in-memory and Redis backends.
416
- * @param {string} sql - SQL query string.
417
- * @param {Array} [params=[]] - Query parameter array.
418
- * @param {Object|string} [options={}] - Query options.
419
- * @returns {Promise<*>}
420
- */
421
- async query(sql, params = [], options = {}) {
422
- if (!mysqlPromise && !pgPromise && !sqlitePromise) return false;
423
- if (!this.pool && !this.db) {
424
- const initialized = await this.init();
425
- if (!initialized) return false;
426
- }
427
-
428
- const queryOptions = typeof options === "string" ? { [options]: true } : options;
429
- const cleanSql = sql.trim();
430
- const isSelect = /^\s*(select|pragma|explain|with)\b/i.test(cleanSql);
431
- const hasReturning = /\breturning\b/i.test(cleanSql);
432
- const isInsert = /^\s*insert\b/i.test(cleanSql);
433
-
434
- let cacheKey = null;
435
- const cacheTtl = queryOptions.cache ? parseInt(queryOptions.cache, 10) : 0;
436
- if (isSelect && cacheTtl > 0) {
437
- const hash = crypto
438
- .createHash("sha256")
439
- .update(cleanSql + JSON.stringify(params) + (queryOptions.return_row ? ":row" : ":all"))
440
- .digest("hex");
441
- const prefix = queryOptions.cachePrefix || "db:";
442
- cacheKey = `${prefix}${hash}`;
443
- const cached = await Cache.get(cacheKey);
444
- if (cached !== null) {
445
- return cached;
446
- }
447
- }
448
-
449
- try {
450
- if (this.type === "sqlite" && this.db) {
451
- const stmt = this._getPreparedStatement(cleanSql);
452
-
453
- if (isSelect || hasReturning) {
454
- if (queryOptions.return_row) {
455
- const row = stmt.get(...params);
456
- const result = row || null;
457
- if (cacheKey && cacheTtl > 0) {
458
- await Cache.set(cacheKey, result, cacheTtl);
459
- }
460
- return result;
461
- }
462
-
463
- const rows = stmt.all(...params);
464
- if (cacheKey && cacheTtl > 0) {
465
- await Cache.set(cacheKey, rows, cacheTtl);
466
- }
467
- return rows;
468
- }
469
-
470
- if (isInsert) {
471
- const info = stmt.run(...params);
472
- return Number(info.lastInsertRowid);
473
- }
474
-
475
- const info = stmt.run(...params);
476
- return info.changes;
477
- } else if (this.type === "postgres" && pgPromise) {
478
- const pgSql = toPostgresSql(cleanSql);
479
- const res = await this.pool.query(pgSql, params);
480
-
481
- if (isSelect || hasReturning) {
482
- const rows = res.rows || [];
483
- const result = queryOptions.return_row ? (rows.length > 0 ? rows[0] : null) : rows;
484
- if (cacheKey && cacheTtl > 0) {
485
- await Cache.set(cacheKey, result, cacheTtl);
486
- }
487
- return result;
488
- }
489
-
490
- if (isInsert) {
491
- if (res.rows && res.rows.length > 0) {
492
- return res.rows[0].id || res.rows[0];
493
- }
494
- return res.rowCount;
495
- }
496
-
497
- return res.rowCount;
498
- } else {
499
- const [results] = await this.pool.execute(cleanSql, params);
500
-
501
- if (isSelect || hasReturning) {
502
- const rows = Array.isArray(results) ? results : [];
503
- const result = queryOptions.return_row ? (rows.length > 0 ? rows[0] : null) : rows;
504
- if (cacheKey && cacheTtl > 0) {
505
- await Cache.set(cacheKey, result, cacheTtl);
506
- }
507
- return result;
508
- }
509
-
510
- if (isInsert) {
511
- return results.insertId || results;
512
- }
513
-
514
- return results;
515
- }
516
- } catch (err) {
517
- console.error("[DATABASE ERROR] Query execution failed:", err.message);
518
- throw err;
519
- }
520
- }
521
-
522
- /**
523
- * Executes a paginated SQL query.
524
- * @param {string} sql - SQL query string.
525
- * @param {Array} [params=[]] - Query parameters.
526
- * @param {Object} [options={}] - Pagination options: page, limit, cache.
527
- * @returns {Promise<{data: Array, total: number, page: number, limit: number, totalPages: number}>}
528
- */
529
- async paginate(sql, params = [], options = {}) {
530
- const page = Math.max(1, parseInt(options.page, 10) || 1);
531
- const limit = Math.max(1, parseInt(options.limit, 10) || 10);
532
- const offset = (page - 1) * limit;
533
-
534
- const cleanSql = sql.trim().replace(/;$/, "");
535
- const countSql = `SELECT COUNT(*) as total FROM (${cleanSql}) as _count_subquery`;
536
-
537
- const countResult = await this.query(countSql, params, { return_row: true });
538
- const total = Number(countResult?.total || countResult?.count || 0);
539
- const totalPages = Math.ceil(total / limit);
540
-
541
- const paginatedSql = `${cleanSql} LIMIT ${limit} OFFSET ${offset}`;
542
- const rows = await this.query(paginatedSql, params, options);
543
-
544
- return {
545
- data: Array.isArray(rows) ? rows : [],
546
- total,
547
- page,
548
- limit,
549
- totalPages,
550
- };
551
- }
552
-
553
- /**
554
- * Executes a database transaction with automatic commit and rollback.
555
- * @param {Function} callback - Async function receiving transaction client: async (tx) => { ... }
556
- * @returns {Promise<*>}
557
- */
558
- async transaction(callback) {
559
- if (!mysqlPromise && !pgPromise && !sqlitePromise) throw new Error("[DATABASE ERROR] No database driver available.");
560
- if (!this.pool && !this.db) {
561
- const initialized = await this.init();
562
- if (!initialized) throw new Error("[DATABASE ERROR] Failed to initialize database pool.");
563
- }
564
-
565
- if (this.type === "sqlite" && this.db) {
566
- this.db.exec("BEGIN IMMEDIATE");
567
- try {
568
- const tx = {
569
- query: async (sql, params = [], options = {}) => {
570
- const queryOptions = typeof options === "string" ? { [options]: true } : options;
571
- const cleanSql = sql.trim();
572
- const isSelect = /^\s*(select|pragma|explain|with)\b/i.test(cleanSql);
573
- const hasReturning = /\breturning\b/i.test(cleanSql);
574
- const isInsert = /^\s*insert\b/i.test(cleanSql);
575
-
576
- const stmt = this._getPreparedStatement(cleanSql);
577
- if (isSelect || hasReturning) {
578
- if (queryOptions.return_row) {
579
- const row = stmt.get(...params);
580
- return row || null;
581
- }
582
- return stmt.all(...params);
583
- }
584
- if (isInsert) {
585
- const info = stmt.run(...params);
586
- return Number(info.lastInsertRowid);
587
- }
588
- const info = stmt.run(...params);
589
- return info.changes;
590
- },
591
- };
592
-
593
- const result = await callback(tx);
594
- this.db.exec("COMMIT");
595
- return result;
596
- } catch (err) {
597
- this.db.exec("ROLLBACK");
598
- console.error("[DATABASE ERROR] Transaction rolled back:", err.message);
599
- throw err;
600
- }
601
- } else if (this.type === "postgres" && pgPromise) {
602
- const client = await this.pool.connect();
603
- try {
604
- await client.query("BEGIN");
605
-
606
- const tx = {
607
- query: async (sql, params = [], options = {}) => {
608
- const queryOptions = typeof options === "string" ? { [options]: true } : options;
609
- const cleanSql = sql.trim();
610
- const isSelect = /^\s*(select|pragma|explain|with)\b/i.test(cleanSql);
611
- const hasReturning = /\breturning\b/i.test(cleanSql);
612
- const isInsert = /^\s*insert\b/i.test(cleanSql);
613
-
614
- const pgSql = toPostgresSql(cleanSql);
615
- const res = await client.query(pgSql, params);
616
-
617
- if (isSelect || hasReturning) {
618
- const rows = res.rows || [];
619
- return queryOptions.return_row ? (rows[0] || null) : rows;
620
- }
621
- if (isInsert) {
622
- if (res.rows && res.rows.length > 0) return res.rows[0].id || res.rows[0];
623
- return res.rowCount;
624
- }
625
- return res.rowCount;
626
- },
627
- };
628
-
629
- const result = await callback(tx);
630
- await client.query("COMMIT");
631
- return result;
632
- } catch (err) {
633
- await client.query("ROLLBACK").catch(() => {});
634
- console.error("[DATABASE ERROR] Transaction rolled back:", err.message);
635
- throw err;
636
- } finally {
637
- client.release();
638
- }
639
- } else {
640
- const connection = await this.pool.getConnection();
641
- try {
642
- await connection.beginTransaction();
643
-
644
- const tx = {
645
- query: async (sql, params = [], options = {}) => {
646
- const queryOptions = typeof options === "string" ? { [options]: true } : options;
647
- const cleanSql = sql.trim();
648
- const isSelect = /^\s*(select|pragma|explain|with)\b/i.test(cleanSql);
649
- const hasReturning = /\breturning\b/i.test(cleanSql);
650
- const isInsert = /^\s*insert\b/i.test(cleanSql);
651
-
652
- const [results] = await connection.execute(cleanSql, params);
653
-
654
- if (isSelect || hasReturning) {
655
- const rows = Array.isArray(results) ? results : [];
656
- return queryOptions.return_row ? (rows[0] || null) : rows;
657
- }
658
- if (isInsert) {
659
- return results.insertId || results;
660
- }
661
- return results;
662
- },
663
- };
664
-
665
- const result = await callback(tx);
666
- await connection.commit();
667
- return result;
668
- } catch (err) {
669
- await connection.rollback().catch(() => {});
670
- console.error("[DATABASE ERROR] Transaction rolled back:", err.message);
671
- throw err;
672
- } finally {
673
- connection.release();
674
- }
675
- }
676
- }
677
-
678
- /**
679
- * Alias for transaction().
680
- * @param {Function} callback
681
- */
682
- async executeTransaction(callback) {
683
- return this.transaction(callback);
684
- }
685
-
686
- /**
687
- * Closes the database connection pool or SQLite instance, checkpointing WAL if SQLite.
688
- */
689
- async close() {
690
- this._stmtCache.clear();
691
- if (this.db) {
692
- try {
693
- if (this._sqliteDriver === "node:sqlite") {
694
- this.db.exec("PRAGMA wal_checkpoint(TRUNCATE);");
695
- } else if (this._sqliteDriver === "better-sqlite3") {
696
- this.db.pragma("wal_checkpoint(TRUNCATE)");
697
- }
698
- } catch {}
699
- this.db.close();
700
- this.db = null;
701
- }
702
- if (this.pool) {
703
- if (typeof this.pool.end === "function") {
704
- await this.pool.end();
705
- }
706
- this.pool = null;
707
- }
708
- _activeDatabases.delete(this);
709
- }
710
-
711
- /**
712
- * Closes all active database instances across the application.
713
- * @returns {Promise<void>}
714
- */
715
- /**
716
- * Creates an atomic backup of this database instance.
717
- * @param {Object} [options={}]
718
- * @returns {Promise<{ success: boolean, file: string, filename: string, size: number, rotated: number, dbType: string }>}
719
- */
720
- async backup(options = {}) {
721
- return Database.backup({ ...options, dbInstance: this });
722
- }
723
-
724
- /**
725
- * Restores this database instance from a backup file.
726
- * @param {string} filePath
727
- * @param {Object} [options={}]
728
- * @returns {Promise<{ success: boolean, restoredFrom: string, targetFile: string, preRestoreBackup?: string, size: number, dbType: string }>}
729
- */
730
- async restore(filePath, options = {}) {
731
- return Database.restore(filePath, { ...options, dbInstance: this });
732
- }
733
-
734
- /**
735
- * Creates an atomic, compressed database backup with automatic retention rotation.
736
- * For SQLite, executes VACUUM INTO for non-blocking, WAL-safe online snapshots.
737
- * @param {Object} [options={}]
738
- * @param {string} [options.out] - Directory to store backups (default: database/backups).
739
- * @param {boolean} [options.compress=true] - Whether to compress with gzip (.gz).
740
- * @param {number} [options.keep=10] - Number of recent backups to retain.
741
- * @param {string} [options.filename] - Custom output filename.
742
- * @param {Database} [options.dbInstance] - Specific database instance to backup.
743
- * @returns {Promise<{ success: boolean, file: string, filename: string, size: number, rotated: number, dbType: string }>}
744
- */
745
- static async backup(options = {}) {
746
- const dbType = options.dbInstance?.type || options.dbType || DB_TYPE;
747
- const backupDir = options.out
748
- ? path.resolve(options.out)
749
- : path.resolve(Config.userDataDir(), "database/backups");
750
-
751
- if (!fs.existsSync(backupDir)) {
752
- fs.mkdirSync(backupDir, { recursive: true });
753
- }
754
-
755
- const compress = options.compress !== false;
756
- const keep = options.keep !== undefined ? parseInt(options.keep, 10) : 10;
757
- const timestamp = getBackupTimestamp();
758
-
759
- if (dbType === "sqlite") {
760
- let dbFilePath =
761
- options.dbInstance?.sqliteConfig?.filename ||
762
- process.env.DB_FILE ||
763
- "database/blue_bird.db";
764
-
765
- if (!path.isAbsolute(dbFilePath) && dbFilePath !== ":memory:") {
766
- dbFilePath = path.resolve(Config.userDataDir(), dbFilePath);
767
- }
768
-
769
- if (dbFilePath === ":memory:") {
770
- throw new Error("Cannot backup an in-memory SQLite database (:memory:).");
771
- }
772
-
773
- if (!fs.existsSync(dbFilePath)) {
774
- throw new Error(`SQLite database file not found: ${dbFilePath}`);
775
- }
776
-
777
- const ext = compress ? ".db.gz" : ".db";
778
- const filename = options.filename || `backup-sqlite-${timestamp}${ext}`;
779
- const targetPath = path.join(backupDir, filename);
780
- const tempDbPath = path.join(backupDir, `.temp-backup-${Date.now()}-${Math.random().toString(36).slice(2, 6)}.db`);
781
-
782
- if (fs.existsSync(tempDbPath)) {
783
- try { fs.unlinkSync(tempDbPath); } catch {}
784
- }
785
-
786
- if (options.dbInstance && options.dbInstance.db) {
787
- options.dbInstance.db.exec(`VACUUM INTO '${tempDbPath.replace(/'/g, "''")}';`);
788
- } else {
789
- if (sqlitePromise?.DatabaseSync) {
790
- const tempConn = new sqlitePromise.DatabaseSync(dbFilePath);
791
- try {
792
- tempConn.exec(`VACUUM INTO '${tempDbPath.replace(/'/g, "''")}';`);
793
- } finally {
794
- tempConn.close();
795
- }
796
- } else if (sqlitePromise?.BetterSqlite) {
797
- const tempConn = new sqlitePromise.BetterSqlite(dbFilePath);
798
- try {
799
- tempConn.exec(`VACUUM INTO '${tempDbPath.replace(/'/g, "''")}';`);
800
- } finally {
801
- tempConn.close();
802
- }
803
- } else {
804
- throw new Error("No SQLite driver available to perform VACUUM INTO backup.");
805
- }
806
- }
807
-
808
- if (compress) {
809
- const rawBytes = fs.readFileSync(tempDbPath);
810
- const gzipped = zlib.gzipSync(rawBytes);
811
- fs.writeFileSync(targetPath, gzipped);
812
- try { fs.unlinkSync(tempDbPath); } catch {}
813
- } else {
814
- fs.renameSync(tempDbPath, targetPath);
815
- }
816
-
817
- const rotated = rotateBackups(backupDir, "backup-sqlite-", keep);
818
-
819
- return {
820
- success: true,
821
- file: targetPath,
822
- filename,
823
- size: fs.statSync(targetPath).size,
824
- rotated,
825
- dbType: "sqlite",
826
- };
827
- }
828
-
829
- if (dbType === "postgres") {
830
- const ext = compress ? ".sql.gz" : ".sql";
831
- const filename = options.filename || `backup-postgres-${timestamp}${ext}`;
832
- const targetPath = path.join(backupDir, filename);
833
-
834
- const dbName = process.env.DB_NAME || "blue_bird";
835
- const dbHost = process.env.DB_HOST || "localhost";
836
- const dbPort = process.env.DB_PORT || "5432";
837
- const dbUser = process.env.DB_USER || "postgres";
838
- const dbPass = process.env.DB_PASSWORD || "";
839
-
840
- const env = { ...process.env, PGPASSWORD: dbPass };
841
- let cmd = `pg_dump -h ${dbHost} -p ${dbPort} -U ${dbUser} -d ${dbName}`;
842
- if (process.env.DATABASE_URL) {
843
- cmd = `pg_dump "${process.env.DATABASE_URL}"`;
844
- }
845
-
846
- const dumpBuffer = execSync(cmd, { env, maxBuffer: 1024 * 1024 * 100 });
847
- if (compress) {
848
- fs.writeFileSync(targetPath, zlib.gzipSync(dumpBuffer));
849
- } else {
850
- fs.writeFileSync(targetPath, dumpBuffer);
851
- }
852
-
853
- const rotated = rotateBackups(backupDir, "backup-postgres-", keep);
854
- return {
855
- success: true,
856
- file: targetPath,
857
- filename,
858
- size: fs.statSync(targetPath).size,
859
- rotated,
860
- dbType: "postgres",
861
- };
862
- }
863
-
864
- if (dbType === "mysql") {
865
- const ext = compress ? ".sql.gz" : ".sql";
866
- const filename = options.filename || `backup-mysql-${timestamp}${ext}`;
867
- const targetPath = path.join(backupDir, filename);
868
-
869
- const dbName = process.env.DB_NAME || "blue_bird";
870
- const dbHost = process.env.DB_HOST || "localhost";
871
- const dbPort = process.env.DB_PORT || "3306";
872
- const dbUser = process.env.DB_USER || "root";
873
- const dbPass = process.env.DB_PASSWORD || "";
874
-
875
- let cmd = `mysqldump -h ${dbHost} -P ${dbPort} -u ${dbUser} ${dbPass ? `-p${dbPass}` : ""} ${dbName}`;
876
- const dumpBuffer = execSync(cmd, { maxBuffer: 1024 * 1024 * 100 });
877
- if (compress) {
878
- fs.writeFileSync(targetPath, zlib.gzipSync(dumpBuffer));
879
- } else {
880
- fs.writeFileSync(targetPath, dumpBuffer);
881
- }
882
-
883
- const rotated = rotateBackups(backupDir, "backup-mysql-", keep);
884
- return {
885
- success: true,
886
- file: targetPath,
887
- filename,
888
- size: fs.statSync(targetPath).size,
889
- rotated,
890
- dbType: "mysql",
891
- };
892
- }
893
-
894
- throw new Error(`Unsupported database type '${dbType}' for backup.`);
895
- }
896
-
897
- /**
898
- * Restores a database from a backup file with pre-restore safety snapshot and SQLite integrity verification.
899
- * @param {string} filePath - Path to backup file (.db, .db.gz, .sql, .sql.gz).
900
- * @param {Object} [options={}]
901
- * @param {boolean} [options.safetyBackup=true] - Create pre-restore snapshot of current database.
902
- * @param {boolean} [options.verify=true] - Verify SQLite PRAGMA integrity_check before overwriting.
903
- * @param {Database} [options.dbInstance]
904
- * @returns {Promise<{ success: boolean, restoredFrom: string, targetFile: string, preRestoreBackup?: string, size: number, dbType: string }>}
905
- */
906
- static async restore(filePath, options = {}) {
907
- if (!filePath) {
908
- throw new Error("Backup file path is required for restore.");
909
- }
910
-
911
- let resolvedFile = path.isAbsolute(filePath) ? filePath : path.resolve(process.cwd(), filePath);
912
- if (!fs.existsSync(resolvedFile)) {
913
- const inDefaultBackups = path.resolve(Config.userDataDir(), "database/backups", filePath);
914
- if (fs.existsSync(inDefaultBackups)) {
915
- resolvedFile = inDefaultBackups;
916
- } else {
917
- throw new Error(`Backup file not found: ${filePath}`);
918
- }
919
- }
920
-
921
- const filename = path.basename(resolvedFile).toLowerCase();
922
- let dbType = options.dbInstance?.type || options.dbType || DB_TYPE;
923
- if (filename.includes("postgres")) {
924
- dbType = "postgres";
925
- } else if (filename.includes("mysql")) {
926
- dbType = "mysql";
927
- } else if (filename.endsWith(".db") || filename.endsWith(".db.gz")) {
928
- dbType = "sqlite";
929
- }
930
-
931
- if (dbType === "sqlite") {
932
- let targetDbPath =
933
- options.dbInstance?.sqliteConfig?.filename ||
934
- process.env.DB_FILE ||
935
- "database/blue_bird.db";
936
-
937
- if (!path.isAbsolute(targetDbPath) && targetDbPath !== ":memory:") {
938
- targetDbPath = path.resolve(Config.userDataDir(), targetDbPath);
939
- }
940
-
941
- if (targetDbPath === ":memory:") {
942
- throw new Error("Cannot restore into an in-memory SQLite database (:memory:).");
943
- }
944
-
945
- const candidateFile = path.join(
946
- path.dirname(targetDbPath),
947
- `.restore-cand-${Date.now()}-${Math.random().toString(36).slice(2, 6)}.db`
948
- );
949
-
950
- if (resolvedFile.endsWith(".gz")) {
951
- const compressed = fs.readFileSync(resolvedFile);
952
- const decompressed = zlib.gunzipSync(compressed);
953
- fs.writeFileSync(candidateFile, decompressed);
954
- } else {
955
- fs.copyFileSync(resolvedFile, candidateFile);
956
- }
957
-
958
- if (options.verify !== false) {
959
- let integrityOk = false;
960
- let integrityMsg = "";
961
-
962
- if (sqlitePromise?.DatabaseSync) {
963
- const testDb = new sqlitePromise.DatabaseSync(candidateFile);
964
- try {
965
- const row = testDb.prepare("PRAGMA integrity_check;").get();
966
- if (row && (row.integrity_check === "ok" || Object.values(row)[0] === "ok")) {
967
- integrityOk = true;
968
- } else {
969
- integrityMsg = JSON.stringify(row);
970
- }
971
- } finally {
972
- testDb.close();
973
- }
974
- } else if (sqlitePromise?.BetterSqlite) {
975
- const testDb = new sqlitePromise.BetterSqlite(candidateFile);
976
- try {
977
- const row = testDb.pragma("integrity_check", { simple: true });
978
- if (row === "ok") {
979
- integrityOk = true;
980
- } else {
981
- integrityMsg = String(row);
982
- }
983
- } finally {
984
- testDb.close();
985
- }
986
- }
987
-
988
- if (!integrityOk) {
989
- try { fs.unlinkSync(candidateFile); } catch {}
990
- throw new Error(`Database restore aborted: backup failed integrity check (${integrityMsg || "unknown error"}).`);
991
- }
992
- }
993
-
994
- if (options.dbInstance) {
995
- try {
996
- await options.dbInstance.close();
997
- } catch {}
998
- }
999
- await Database.closeAll();
1000
-
1001
- let preRestoreBackup = null;
1002
- if (options.safetyBackup !== false && fs.existsSync(targetDbPath)) {
1003
- const backupDir = path.resolve(Config.userDataDir(), "database/backups");
1004
- if (!fs.existsSync(backupDir)) {
1005
- fs.mkdirSync(backupDir, { recursive: true });
1006
- }
1007
- preRestoreBackup = path.join(backupDir, `pre-restore-sqlite-${getBackupTimestamp()}.db`);
1008
- fs.copyFileSync(targetDbPath, preRestoreBackup);
1009
- }
1010
-
1011
- const targetDir = path.dirname(targetDbPath);
1012
- if (!fs.existsSync(targetDir)) {
1013
- fs.mkdirSync(targetDir, { recursive: true });
1014
- }
1015
-
1016
- try {
1017
- fs.unlinkSync(targetDbPath);
1018
- } catch {}
1019
-
1020
- try {
1021
- fs.copyFileSync(candidateFile, targetDbPath);
1022
- } catch {
1023
- await new Promise((resolve) => setTimeout(resolve, 100));
1024
- fs.copyFileSync(candidateFile, targetDbPath);
1025
- }
1026
- try { fs.unlinkSync(candidateFile); } catch {}
1027
-
1028
- const walFile = `${targetDbPath}-wal`;
1029
- const shmFile = `${targetDbPath}-shm`;
1030
- if (fs.existsSync(walFile)) {
1031
- try { fs.unlinkSync(walFile); } catch {}
1032
- }
1033
- if (fs.existsSync(shmFile)) {
1034
- try { fs.unlinkSync(shmFile); } catch {}
1035
- }
1036
-
1037
- return {
1038
- success: true,
1039
- restoredFrom: resolvedFile,
1040
- targetFile: targetDbPath,
1041
- preRestoreBackup,
1042
- size: fs.statSync(targetDbPath).size,
1043
- dbType: "sqlite",
1044
- };
1045
- }
1046
-
1047
- if (dbType === "postgres") {
1048
- let sqlFile = resolvedFile;
1049
- let tempSql = null;
1050
- if (resolvedFile.endsWith(".gz")) {
1051
- tempSql = path.join(os.tmpdir(), `bluebird-restore-${Date.now()}.sql`);
1052
- fs.writeFileSync(tempSql, zlib.gunzipSync(fs.readFileSync(resolvedFile)));
1053
- sqlFile = tempSql;
1054
- }
1055
-
1056
- await Database.closeAll();
1057
-
1058
- const dbName = process.env.DB_NAME || "blue_bird";
1059
- const dbHost = process.env.DB_HOST || "localhost";
1060
- const dbPort = process.env.DB_PORT || "5432";
1061
- const dbUser = process.env.DB_USER || "postgres";
1062
- const dbPass = process.env.DB_PASSWORD || "";
1063
-
1064
- const env = { ...process.env, PGPASSWORD: dbPass };
1065
- let cmd = `psql -h ${dbHost} -p ${dbPort} -U ${dbUser} -d ${dbName} -f "${sqlFile}"`;
1066
- if (process.env.DATABASE_URL) {
1067
- cmd = `psql "${process.env.DATABASE_URL}" -f "${sqlFile}"`;
1068
- }
1069
-
1070
- execSync(cmd, { env });
1071
- if (tempSql) {
1072
- try { fs.unlinkSync(tempSql); } catch {}
1073
- }
1074
-
1075
- return {
1076
- success: true,
1077
- restoredFrom: resolvedFile,
1078
- targetFile: dbName,
1079
- dbType: "postgres",
1080
- };
1081
- }
1082
-
1083
- if (dbType === "mysql") {
1084
- let sqlFile = resolvedFile;
1085
- let tempSql = null;
1086
- if (resolvedFile.endsWith(".gz")) {
1087
- tempSql = path.join(os.tmpdir(), `bluebird-restore-${Date.now()}.sql`);
1088
- fs.writeFileSync(tempSql, zlib.gunzipSync(fs.readFileSync(resolvedFile)));
1089
- sqlFile = tempSql;
1090
- }
1091
-
1092
- await Database.closeAll();
1093
-
1094
- const dbName = process.env.DB_NAME || "blue_bird";
1095
- const dbHost = process.env.DB_HOST || "localhost";
1096
- const dbPort = process.env.DB_PORT || "3306";
1097
- const dbUser = process.env.DB_USER || "root";
1098
- const dbPass = process.env.DB_PASSWORD || "";
1099
-
1100
- let cmd = `mysql -h ${dbHost} -P ${dbPort} -u ${dbUser} ${dbPass ? `-p${dbPass}` : ""} ${dbName} < "${sqlFile}"`;
1101
- execSync(cmd, { shell: true });
1102
-
1103
- if (tempSql) {
1104
- try { fs.unlinkSync(tempSql); } catch {}
1105
- }
1106
-
1107
- return {
1108
- success: true,
1109
- restoredFrom: resolvedFile,
1110
- targetFile: dbName,
1111
- dbType: "mysql",
1112
- };
1113
- }
1114
-
1115
- throw new Error(`Unsupported database type '${dbType}' for restore.`);
1116
- }
1117
-
1118
- static async closeAll() {
1119
- const list = Array.from(_activeDatabases);
1120
- for (const db of list) {
1121
- try {
1122
- await db.close();
1123
- } catch (err) {
1124
- console.error("[DATABASE] Error closing database connection:", err.message);
1125
- }
1126
- }
1127
- }
1128
- }
1129
-
1130
- export { Database, DB_TYPE };
1131
- export default Database;
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import crypto from "node:crypto";
4
+ import zlib from "node:zlib";
5
+ import { execSync } from "node:child_process";
6
+ import Config from "./config.js";
7
+ import Cache from "./cache.js";
8
+
9
+ const rawDbType = (process.env.DB_TYPE || "").toLowerCase().trim();
10
+ let DB_TYPE = "";
11
+
12
+ if (
13
+ rawDbType === "sqlite" ||
14
+ rawDbType === "sqlite3" ||
15
+ rawDbType === "sql" ||
16
+ rawDbType === "better-sqlite3" ||
17
+ rawDbType === "better-sqlite" ||
18
+ rawDbType === "lite"
19
+ ) {
20
+ DB_TYPE = "sqlite";
21
+ } else if (
22
+ rawDbType === "postgres" ||
23
+ rawDbType === "postgresql" ||
24
+ rawDbType === "pg" ||
25
+ rawDbType === "psql" ||
26
+ rawDbType === "pgsql" ||
27
+ rawDbType === "postgre" ||
28
+ rawDbType === "postgr" ||
29
+ rawDbType === "psgr"
30
+ ) {
31
+ DB_TYPE = "postgres";
32
+ } else if (
33
+ rawDbType === "mysql" ||
34
+ rawDbType === "mariadb" ||
35
+ rawDbType === "maria" ||
36
+ rawDbType === "my"
37
+ ) {
38
+ DB_TYPE = "mysql";
39
+ } else if (
40
+ rawDbType === "none" ||
41
+ rawDbType === "no" ||
42
+ rawDbType === "false" ||
43
+ rawDbType === "null" ||
44
+ rawDbType === "0"
45
+ ) {
46
+ DB_TYPE = "none";
47
+ }
48
+
49
+ if (
50
+ !DB_TYPE &&
51
+ process.env.DATABASE_URL &&
52
+ !process.env.DATABASE_URL.startsWith("#")
53
+ ) {
54
+ if (
55
+ process.env.DATABASE_URL.startsWith("postgres://") ||
56
+ process.env.DATABASE_URL.startsWith("postgresql://")
57
+ ) {
58
+ DB_TYPE = "postgres";
59
+ } else if (process.env.DATABASE_URL.startsWith("mysql://")) {
60
+ DB_TYPE = "mysql";
61
+ } else if (
62
+ process.env.DATABASE_URL.startsWith("sqlite://") ||
63
+ process.env.DATABASE_URL.startsWith("sqlite:")
64
+ ) {
65
+ DB_TYPE = "sqlite";
66
+ }
67
+ }
68
+ if (!DB_TYPE) {
69
+ DB_TYPE = "sqlite";
70
+ }
71
+
72
+ let mysqlPromise = null;
73
+ let pgPromise = null;
74
+ let sqlitePromise = null;
75
+
76
+ if (DB_TYPE === "postgres") {
77
+ try {
78
+ pgPromise = await import("pg");
79
+ } catch (err) {
80
+ console.error("[DATABASE ERROR] pg package is not installed. Database wrapper is disabled.");
81
+ }
82
+ } else if (DB_TYPE === "mysql") {
83
+ try {
84
+ mysqlPromise = await import("mysql2/promise");
85
+ } catch (err) {
86
+ console.error("[DATABASE ERROR] mysql2 package is not installed. Database wrapper is disabled.");
87
+ }
88
+ } else if (DB_TYPE === "sqlite") {
89
+ try {
90
+ const { DatabaseSync } = await import("node:sqlite");
91
+ const testDb = new DatabaseSync(":memory:");
92
+ testDb.close();
93
+ sqlitePromise = { source: "node:sqlite", DatabaseSync };
94
+ } catch {
95
+ try {
96
+ const mod = await import("better-sqlite3");
97
+ sqlitePromise = { source: "better-sqlite3", BetterSqlite: mod.default || mod };
98
+ } catch {
99
+ console.error(
100
+ "[DATABASE] No SQLite driver available. Node.js 22.18+ required for node:sqlite, or install better-sqlite3."
101
+ );
102
+ }
103
+ }
104
+ }
105
+
106
+ /**
107
+ * Replaces ? parameter placeholders with $1, $2, etc., ignoring quoted string literals.
108
+ * @param {string} sql
109
+ * @returns {string}
110
+ */
111
+ function toPostgresSql(sql) {
112
+ let paramIndex = 1;
113
+ let inSingleQuote = false;
114
+ let inDoubleQuote = false;
115
+ let result = "";
116
+
117
+ for (let i = 0; i < sql.length; i++) {
118
+ const char = sql[i];
119
+ const prev = i > 0 ? sql[i - 1] : "";
120
+
121
+ if (char === "'" && prev !== "\\" && !inDoubleQuote) {
122
+ inSingleQuote = !inSingleQuote;
123
+ result += char;
124
+ } else if (char === '"' && prev !== "\\" && !inSingleQuote) {
125
+ inDoubleQuote = !inDoubleQuote;
126
+ result += char;
127
+ } else if (char === "?" && !inSingleQuote && !inDoubleQuote) {
128
+ result += `$${paramIndex++}`;
129
+ } else {
130
+ result += char;
131
+ }
132
+ }
133
+
134
+ return result;
135
+ }
136
+
137
+ const _activeDatabases = new Set();
138
+
139
+ /**
140
+ * Generates an ISO-safe timestamp string formatted for filenames across OS platforms.
141
+ * @returns {string}
142
+ */
143
+ function getBackupTimestamp() {
144
+ const now = new Date();
145
+ const pad = (n) => String(n).padStart(2, "0");
146
+ const year = now.getFullYear();
147
+ const month = pad(now.getMonth() + 1);
148
+ const day = pad(now.getDate());
149
+ const hours = pad(now.getHours());
150
+ const mins = pad(now.getMinutes());
151
+ const secs = pad(now.getSeconds());
152
+ const ms = String(now.getMilliseconds()).padStart(3, "0");
153
+ return `${year}-${month}-${day}_${hours}${mins}${secs}_${ms}`;
154
+ }
155
+
156
+ const BACKUP_STAMP = /(\d{4}-\d{2}-\d{2}_\d{6}_\d{3})(?:-(\d+))?/;
157
+
158
+ /**
159
+ * Returns a sortable `[timestamp, sequence]` key from a backup filename, or `null` for custom names.
160
+ * @param {string} file
161
+ * @returns {[string, number]|null}
162
+ */
163
+ function backupSortKey(file) {
164
+ const match = BACKUP_STAMP.exec(file);
165
+ return match ? [match[1], Number(match[2] || 0)] : null;
166
+ }
167
+
168
+ /**
169
+ * Sorts backups newest first. Timestamped names win over `mtime`, because several backups written in the same
170
+ * millisecond share the same `mtime` on some filesystems (Windows/NTFS) and a tie must never drop the newest one.
171
+ * @param {{ file: string, mtime: number }} a
172
+ * @param {{ file: string, mtime: number }} b
173
+ * @returns {number}
174
+ */
175
+ export function compareBackupsNewestFirst(a, b) {
176
+ const ka = backupSortKey(a.file);
177
+ const kb = backupSortKey(b.file);
178
+ if (ka && kb) {
179
+ if (ka[0] !== kb[0]) return ka[0] < kb[0] ? 1 : -1;
180
+ if (ka[1] !== kb[1]) return kb[1] - ka[1];
181
+ }
182
+ if (b.mtime !== a.mtime) return b.mtime - a.mtime;
183
+ return a.file < b.file ? 1 : a.file > b.file ? -1 : 0;
184
+ }
185
+
186
+ /**
187
+ * Returns a non-existing path for `filename` inside `dir`, appending `-1`, `-2`, ... before the extension on collision.
188
+ * @param {string} dir
189
+ * @param {string} filename
190
+ * @returns {string}
191
+ */
192
+ function uniqueBackupPath(dir, filename) {
193
+ let candidate = path.join(dir, filename);
194
+ if (!fs.existsSync(candidate)) return candidate;
195
+ const ext = filename.match(/(\.db\.gz|\.sql\.gz|\.db|\.sql)$/)?.[1] || path.extname(filename);
196
+ const stem = filename.slice(0, filename.length - ext.length);
197
+ for (let i = 1; fs.existsSync(candidate); i++) {
198
+ candidate = path.join(dir, `${stem}-${i}${ext}`);
199
+ }
200
+ return candidate;
201
+ }
202
+
203
+ /**
204
+ * Rotates backups in backupDir, keeping only the most recent N backups and never deleting `protectFile`.
205
+ * @param {string} backupDir
206
+ * @param {string} prefix
207
+ * @param {number} [keep=10]
208
+ * @param {string} [protectFile] - Absolute path of the backup that was just created.
209
+ * @returns {number} Count of deleted backups.
210
+ */
211
+ function rotateBackups(backupDir, prefix, keep = 10, protectFile = "") {
212
+ if (!fs.existsSync(backupDir) || keep <= 0) return 0;
213
+ try {
214
+ const files = fs.readdirSync(backupDir)
215
+ .filter((file) => file.startsWith(prefix))
216
+ .map((file) => {
217
+ const fullPath = path.join(backupDir, file);
218
+ return {
219
+ file,
220
+ fullPath,
221
+ mtime: fs.statSync(fullPath).mtimeMs,
222
+ };
223
+ })
224
+ .sort(compareBackupsNewestFirst);
225
+
226
+ if (protectFile) {
227
+ const idx = files.findIndex((f) => path.resolve(f.fullPath) === path.resolve(protectFile));
228
+ if (idx > 0) files.unshift(...files.splice(idx, 1));
229
+ }
230
+
231
+ let deleted = 0;
232
+ if (files.length > keep) {
233
+ for (let i = keep; i < files.length; i++) {
234
+ try {
235
+ fs.unlinkSync(files[i].fullPath);
236
+ deleted++;
237
+ } catch {}
238
+ }
239
+ }
240
+ return deleted;
241
+ } catch {
242
+ return 0;
243
+ }
244
+ }
245
+
246
+ /**
247
+ * Database class wrapping native node:sqlite, mysql2, and pg with pooling and multi-level caching.
248
+ */
249
+ class Database {
250
+ /**
251
+ * Initializes database connection parameters.
252
+ * @param {number} [connectionLimit=10]
253
+ * @param {number} [queueLimit=0]
254
+ * @param {Object} [config={}]
255
+ */
256
+ constructor(connectionLimit = 10, queueLimit = 0, config = {}) {
257
+ this.pool = null;
258
+ this.db = null;
259
+ this.type = config.DB_TYPE || DB_TYPE;
260
+ this._stmtCache = new Map();
261
+ this._maxStatements = 500;
262
+
263
+ let defaultSqliteFile = process.env.DB_FILE || "database/blue_bird.db";
264
+ let busyTimeout = 5000;
265
+ let journalMode = "WAL";
266
+ let synchronous = "NORMAL";
267
+
268
+ if (process.env.DATABASE_URL && !process.env.DATABASE_URL.startsWith("#")) {
269
+ try {
270
+ if (
271
+ process.env.DATABASE_URL.startsWith("sqlite://") ||
272
+ process.env.DATABASE_URL.startsWith("sqlite:")
273
+ ) {
274
+ const rawUrl = process.env.DATABASE_URL;
275
+ const cleanUrl = rawUrl.replace(/^sqlite:\/\/|^sqlite:/, "");
276
+ const [filePath, queryStr] = cleanUrl.split("?");
277
+ if (filePath) {
278
+ defaultSqliteFile = filePath;
279
+ }
280
+ if (queryStr) {
281
+ const params = new URLSearchParams(queryStr);
282
+ if (params.has("busy_timeout")) {
283
+ busyTimeout = parseInt(params.get("busy_timeout"), 10) || busyTimeout;
284
+ }
285
+ if (params.has("journal_mode")) {
286
+ journalMode = params.get("journal_mode").toUpperCase();
287
+ }
288
+ if (params.has("synchronous")) {
289
+ synchronous = params.get("synchronous").toUpperCase();
290
+ }
291
+ }
292
+ }
293
+ } catch (err) {
294
+ console.error("[DATABASE ERROR] Failed to parse SQLite DATABASE_URL:", err.message);
295
+ }
296
+ }
297
+
298
+ this.sqliteConfig = {
299
+ filename: config.DB_FILE || defaultSqliteFile,
300
+ busyTimeout: config.busyTimeout || busyTimeout,
301
+ journalMode: config.journalMode || journalMode,
302
+ synchronous: config.synchronous || synchronous,
303
+ };
304
+
305
+ this.config = {
306
+ ...config,
307
+ host: process.env.DB_HOST || "localhost",
308
+ user: process.env.DB_USER || (this.type === "postgres" ? "postgres" : "root"),
309
+ password: process.env.DB_PASSWORD || "root",
310
+ database: process.env.DB_NAME || "blue_bird",
311
+ port: parseInt(process.env.DB_PORT, 10) || (this.type === "postgres" ? 5432 : 3306),
312
+ charset: "utf8mb4",
313
+ waitForConnections: true,
314
+ connectionLimit: connectionLimit,
315
+ queueLimit: queueLimit,
316
+ max: connectionLimit,
317
+ };
318
+
319
+ if (process.env.DATABASE_URL && !process.env.DATABASE_URL.startsWith("#")) {
320
+ try {
321
+ if (
322
+ process.env.DATABASE_URL.startsWith("mysql://") ||
323
+ process.env.DATABASE_URL.startsWith("postgres://") ||
324
+ process.env.DATABASE_URL.startsWith("postgresql://")
325
+ ) {
326
+ const url = new URL(process.env.DATABASE_URL);
327
+ this.config.host = url.hostname;
328
+ this.config.port = parseInt(url.port, 10) || (this.type === "postgres" ? 5432 : 3306);
329
+ this.config.user = url.username;
330
+ this.config.password = url.password;
331
+ this.config.database = url.pathname.substring(1);
332
+ this.config.connectionString = process.env.DATABASE_URL;
333
+ }
334
+ } catch (err) {
335
+ console.error("[DATABASE ERROR] Failed to parse DATABASE_URL:", err.message);
336
+ }
337
+ }
338
+
339
+ _activeDatabases.add(this);
340
+ }
341
+
342
+ /**
343
+ * Retrieves or creates a prepared statement with LRU caching.
344
+ * @private
345
+ * @param {string} sql
346
+ * @returns {*} Prepared statement.
347
+ */
348
+ _getPreparedStatement(sql) {
349
+ let stmt = this._stmtCache.get(sql);
350
+ if (stmt) return stmt;
351
+
352
+ stmt = this.db.prepare(sql);
353
+ if (this._stmtCache.size >= this._maxStatements) {
354
+ const oldestKey = this._stmtCache.keys().next().value;
355
+ if (oldestKey !== undefined) this._stmtCache.delete(oldestKey);
356
+ }
357
+ this._stmtCache.set(sql, stmt);
358
+ return stmt;
359
+ }
360
+
361
+ /**
362
+ * Initializes connection pool or SQLite database.
363
+ * @param {number} [retries=3]
364
+ * @returns {Promise<boolean>}
365
+ */
366
+ async init(retries = 3) {
367
+ if (!mysqlPromise && !pgPromise && !sqlitePromise) return false;
368
+ _activeDatabases.add(this);
369
+ if (this.pool || this.db) return true;
370
+
371
+ if (this.type === "sqlite" && sqlitePromise) {
372
+ try {
373
+ const isMemoryDb = this.sqliteConfig.filename === ":memory:";
374
+ const userDataBase = Config.userDataDir();
375
+ const dbFilePath = isMemoryDb
376
+ ? ":memory:"
377
+ : path.isAbsolute(this.sqliteConfig.filename)
378
+ ? this.sqliteConfig.filename
379
+ : path.resolve(userDataBase, this.sqliteConfig.filename);
380
+
381
+ if (!isMemoryDb) {
382
+ const dir = path.dirname(dbFilePath);
383
+ if (!fs.existsSync(dir)) {
384
+ fs.mkdirSync(dir, { recursive: true });
385
+ }
386
+
387
+ if (!fs.existsSync(dbFilePath)) {
388
+ const candidatePaths = [
389
+ path.resolve(Config.appDir(), this.sqliteConfig.filename),
390
+ process.resourcesPath ? path.join(process.resourcesPath, this.sqliteConfig.filename) : null,
391
+ process.resourcesPath ? path.join(process.resourcesPath, "database", path.basename(this.sqliteConfig.filename)) : null,
392
+ Config.appDir().includes(".asar")
393
+ ? path.resolve(Config.appDir().replace(/\.asar(?=[\/\\]|$)/, ".asar.unpacked"), this.sqliteConfig.filename)
394
+ : null,
395
+ path.resolve(process.cwd(), this.sqliteConfig.filename),
396
+ ].filter(Boolean);
397
+
398
+ for (const candidate of candidatePaths) {
399
+ if (fs.existsSync(candidate) && path.resolve(candidate) !== path.resolve(dbFilePath)) {
400
+ try {
401
+ fs.copyFileSync(candidate, dbFilePath);
402
+ break;
403
+ } catch {}
404
+ }
405
+ }
406
+ }
407
+ }
408
+
409
+ if (sqlitePromise.source === "node:sqlite") {
410
+ const { DatabaseSync } = sqlitePromise;
411
+ this.db = new DatabaseSync(dbFilePath);
412
+ this._sqliteDriver = "node:sqlite";
413
+ this.db.exec(`PRAGMA journal_mode = ${this.sqliteConfig.journalMode};`);
414
+ this.db.exec(`PRAGMA synchronous = ${this.sqliteConfig.synchronous};`);
415
+ this.db.exec(`PRAGMA busy_timeout = ${this.sqliteConfig.busyTimeout};`);
416
+ this.db.exec("PRAGMA foreign_keys = ON;");
417
+ this.db.exec("PRAGMA temp_store = MEMORY;");
418
+ this.db.exec("PRAGMA cache_size = -8000;");
419
+ this.db.exec("PRAGMA mmap_size = 268435456;");
420
+ } else {
421
+ const { BetterSqlite } = sqlitePromise;
422
+ this.db = new BetterSqlite(dbFilePath, { timeout: this.sqliteConfig.busyTimeout });
423
+ this._sqliteDriver = "better-sqlite3";
424
+ this.db.pragma(`journal_mode = ${this.sqliteConfig.journalMode}`);
425
+ this.db.pragma(`synchronous = ${this.sqliteConfig.synchronous}`);
426
+ this.db.pragma("foreign_keys = ON");
427
+ this.db.pragma(`busy_timeout = ${this.sqliteConfig.busyTimeout}`);
428
+ this.db.pragma("temp_store = MEMORY");
429
+ this.db.pragma("cache_size = -8000");
430
+ this.db.pragma("mmap_size = 268435456");
431
+ }
432
+
433
+ return true;
434
+ } catch (err) {
435
+ console.error("[DATABASE] Failed to initialize SQLite database:", err.message);
436
+ this.db = null;
437
+ return false;
438
+ }
439
+ }
440
+
441
+ for (let attempt = 1; attempt <= retries; attempt++) {
442
+ try {
443
+ if (this.type === "postgres" && pgPromise) {
444
+ const pg = pgPromise.default || pgPromise;
445
+ this.pool = new pg.Pool(this.config);
446
+ await this.pool.query("SELECT 1");
447
+ } else if (mysqlPromise) {
448
+ const { max, connectionString, ...mysqlConfig } = this.config;
449
+ this.pool = mysqlPromise.createPool(mysqlConfig);
450
+ await this.pool.query("SELECT 1");
451
+ }
452
+ return true;
453
+ } catch (err) {
454
+ this.pool = null;
455
+ if (attempt === retries) {
456
+ console.error(`[DATABASE ERROR] Connection failed after ${retries} attempts:`, err.message);
457
+ return false;
458
+ }
459
+ await new Promise((resolve) => setTimeout(resolve, 1000));
460
+ }
461
+ }
462
+ return false;
463
+ }
464
+
465
+ /**
466
+ * Runs a SQL query with parameters and formatting options.
467
+ * Accurately classifies CTEs (WITH ... SELECT) and RETURNING clauses.
468
+ * Multi-level caching supports both in-memory and Redis backends.
469
+ * @param {string} sql - SQL query string.
470
+ * @param {Array} [params=[]] - Query parameter array.
471
+ * @param {Object|string} [options={}] - Query options.
472
+ * @returns {Promise<*>}
473
+ */
474
+ async query(sql, params = [], options = {}) {
475
+ if (!mysqlPromise && !pgPromise && !sqlitePromise) return false;
476
+ if (!this.pool && !this.db) {
477
+ const initialized = await this.init();
478
+ if (!initialized) return false;
479
+ }
480
+
481
+ const queryOptions = typeof options === "string" ? { [options]: true } : options;
482
+ const cleanSql = sql.trim();
483
+ const isSelect = /^\s*(select|pragma|explain|with)\b/i.test(cleanSql);
484
+ const hasReturning = /\breturning\b/i.test(cleanSql);
485
+ const isInsert = /^\s*insert\b/i.test(cleanSql);
486
+
487
+ let cacheKey = null;
488
+ const cacheTtl = queryOptions.cache ? parseInt(queryOptions.cache, 10) : 0;
489
+ if (isSelect && cacheTtl > 0) {
490
+ const hash = crypto
491
+ .createHash("sha256")
492
+ .update(cleanSql + JSON.stringify(params) + (queryOptions.return_row ? ":row" : ":all"))
493
+ .digest("hex");
494
+ const prefix = queryOptions.cachePrefix || "db:";
495
+ cacheKey = `${prefix}${hash}`;
496
+ const cached = await Cache.get(cacheKey);
497
+ if (cached !== null) {
498
+ return cached;
499
+ }
500
+ }
501
+
502
+ try {
503
+ if (this.type === "sqlite" && this.db) {
504
+ const stmt = this._getPreparedStatement(cleanSql);
505
+
506
+ if (isSelect || hasReturning) {
507
+ if (queryOptions.return_row) {
508
+ const row = stmt.get(...params);
509
+ const result = row || null;
510
+ if (cacheKey && cacheTtl > 0) {
511
+ await Cache.set(cacheKey, result, cacheTtl);
512
+ }
513
+ return result;
514
+ }
515
+
516
+ const rows = stmt.all(...params);
517
+ if (cacheKey && cacheTtl > 0) {
518
+ await Cache.set(cacheKey, rows, cacheTtl);
519
+ }
520
+ return rows;
521
+ }
522
+
523
+ if (isInsert) {
524
+ const info = stmt.run(...params);
525
+ return Number(info.lastInsertRowid);
526
+ }
527
+
528
+ const info = stmt.run(...params);
529
+ return info.changes;
530
+ } else if (this.type === "postgres" && pgPromise) {
531
+ const pgSql = toPostgresSql(cleanSql);
532
+ const res = await this.pool.query(pgSql, params);
533
+
534
+ if (isSelect || hasReturning) {
535
+ const rows = res.rows || [];
536
+ const result = queryOptions.return_row ? (rows.length > 0 ? rows[0] : null) : rows;
537
+ if (cacheKey && cacheTtl > 0) {
538
+ await Cache.set(cacheKey, result, cacheTtl);
539
+ }
540
+ return result;
541
+ }
542
+
543
+ if (isInsert) {
544
+ if (res.rows && res.rows.length > 0) {
545
+ return res.rows[0].id || res.rows[0];
546
+ }
547
+ return res.rowCount;
548
+ }
549
+
550
+ return res.rowCount;
551
+ } else {
552
+ const [results] = await this.pool.execute(cleanSql, params);
553
+
554
+ if (isSelect || hasReturning) {
555
+ const rows = Array.isArray(results) ? results : [];
556
+ const result = queryOptions.return_row ? (rows.length > 0 ? rows[0] : null) : rows;
557
+ if (cacheKey && cacheTtl > 0) {
558
+ await Cache.set(cacheKey, result, cacheTtl);
559
+ }
560
+ return result;
561
+ }
562
+
563
+ if (isInsert) {
564
+ return results.insertId || results;
565
+ }
566
+
567
+ return results;
568
+ }
569
+ } catch (err) {
570
+ console.error("[DATABASE ERROR] Query execution failed:", err.message);
571
+ throw err;
572
+ }
573
+ }
574
+
575
+ /**
576
+ * Executes a paginated SQL query.
577
+ * @param {string} sql - SQL query string.
578
+ * @param {Array} [params=[]] - Query parameters.
579
+ * @param {Object} [options={}] - Pagination options: page, limit, cache.
580
+ * @returns {Promise<{data: Array, total: number, page: number, limit: number, totalPages: number}>}
581
+ */
582
+ async paginate(sql, params = [], options = {}) {
583
+ const page = Math.max(1, parseInt(options.page, 10) || 1);
584
+ const limit = Math.max(1, parseInt(options.limit, 10) || 10);
585
+ const offset = (page - 1) * limit;
586
+
587
+ const cleanSql = sql.trim().replace(/;$/, "");
588
+ const countSql = `SELECT COUNT(*) as total FROM (${cleanSql}) as _count_subquery`;
589
+
590
+ const countResult = await this.query(countSql, params, { return_row: true });
591
+ const total = Number(countResult?.total || countResult?.count || 0);
592
+ const totalPages = Math.ceil(total / limit);
593
+
594
+ const paginatedSql = `${cleanSql} LIMIT ${limit} OFFSET ${offset}`;
595
+ const rows = await this.query(paginatedSql, params, options);
596
+
597
+ return {
598
+ data: Array.isArray(rows) ? rows : [],
599
+ total,
600
+ page,
601
+ limit,
602
+ totalPages,
603
+ };
604
+ }
605
+
606
+ /**
607
+ * Executes a database transaction with automatic commit and rollback.
608
+ * @param {Function} callback - Async function receiving transaction client: async (tx) => { ... }
609
+ * @returns {Promise<*>}
610
+ */
611
+ async transaction(callback) {
612
+ if (!mysqlPromise && !pgPromise && !sqlitePromise) throw new Error("[DATABASE ERROR] No database driver available.");
613
+ if (!this.pool && !this.db) {
614
+ const initialized = await this.init();
615
+ if (!initialized) throw new Error("[DATABASE ERROR] Failed to initialize database pool.");
616
+ }
617
+
618
+ if (this.type === "sqlite" && this.db) {
619
+ this.db.exec("BEGIN IMMEDIATE");
620
+ try {
621
+ const tx = {
622
+ query: async (sql, params = [], options = {}) => {
623
+ const queryOptions = typeof options === "string" ? { [options]: true } : options;
624
+ const cleanSql = sql.trim();
625
+ const isSelect = /^\s*(select|pragma|explain|with)\b/i.test(cleanSql);
626
+ const hasReturning = /\breturning\b/i.test(cleanSql);
627
+ const isInsert = /^\s*insert\b/i.test(cleanSql);
628
+
629
+ const stmt = this._getPreparedStatement(cleanSql);
630
+ if (isSelect || hasReturning) {
631
+ if (queryOptions.return_row) {
632
+ const row = stmt.get(...params);
633
+ return row || null;
634
+ }
635
+ return stmt.all(...params);
636
+ }
637
+ if (isInsert) {
638
+ const info = stmt.run(...params);
639
+ return Number(info.lastInsertRowid);
640
+ }
641
+ const info = stmt.run(...params);
642
+ return info.changes;
643
+ },
644
+ };
645
+
646
+ const result = await callback(tx);
647
+ this.db.exec("COMMIT");
648
+ return result;
649
+ } catch (err) {
650
+ this.db.exec("ROLLBACK");
651
+ console.error("[DATABASE ERROR] Transaction rolled back:", err.message);
652
+ throw err;
653
+ }
654
+ } else if (this.type === "postgres" && pgPromise) {
655
+ const client = await this.pool.connect();
656
+ try {
657
+ await client.query("BEGIN");
658
+
659
+ const tx = {
660
+ query: async (sql, params = [], options = {}) => {
661
+ const queryOptions = typeof options === "string" ? { [options]: true } : options;
662
+ const cleanSql = sql.trim();
663
+ const isSelect = /^\s*(select|pragma|explain|with)\b/i.test(cleanSql);
664
+ const hasReturning = /\breturning\b/i.test(cleanSql);
665
+ const isInsert = /^\s*insert\b/i.test(cleanSql);
666
+
667
+ const pgSql = toPostgresSql(cleanSql);
668
+ const res = await client.query(pgSql, params);
669
+
670
+ if (isSelect || hasReturning) {
671
+ const rows = res.rows || [];
672
+ return queryOptions.return_row ? (rows[0] || null) : rows;
673
+ }
674
+ if (isInsert) {
675
+ if (res.rows && res.rows.length > 0) return res.rows[0].id || res.rows[0];
676
+ return res.rowCount;
677
+ }
678
+ return res.rowCount;
679
+ },
680
+ };
681
+
682
+ const result = await callback(tx);
683
+ await client.query("COMMIT");
684
+ return result;
685
+ } catch (err) {
686
+ await client.query("ROLLBACK").catch(() => {});
687
+ console.error("[DATABASE ERROR] Transaction rolled back:", err.message);
688
+ throw err;
689
+ } finally {
690
+ client.release();
691
+ }
692
+ } else {
693
+ const connection = await this.pool.getConnection();
694
+ try {
695
+ await connection.beginTransaction();
696
+
697
+ const tx = {
698
+ query: async (sql, params = [], options = {}) => {
699
+ const queryOptions = typeof options === "string" ? { [options]: true } : options;
700
+ const cleanSql = sql.trim();
701
+ const isSelect = /^\s*(select|pragma|explain|with)\b/i.test(cleanSql);
702
+ const hasReturning = /\breturning\b/i.test(cleanSql);
703
+ const isInsert = /^\s*insert\b/i.test(cleanSql);
704
+
705
+ const [results] = await connection.execute(cleanSql, params);
706
+
707
+ if (isSelect || hasReturning) {
708
+ const rows = Array.isArray(results) ? results : [];
709
+ return queryOptions.return_row ? (rows[0] || null) : rows;
710
+ }
711
+ if (isInsert) {
712
+ return results.insertId || results;
713
+ }
714
+ return results;
715
+ },
716
+ };
717
+
718
+ const result = await callback(tx);
719
+ await connection.commit();
720
+ return result;
721
+ } catch (err) {
722
+ await connection.rollback().catch(() => {});
723
+ console.error("[DATABASE ERROR] Transaction rolled back:", err.message);
724
+ throw err;
725
+ } finally {
726
+ connection.release();
727
+ }
728
+ }
729
+ }
730
+
731
+ /**
732
+ * Alias for transaction().
733
+ * @param {Function} callback
734
+ */
735
+ async executeTransaction(callback) {
736
+ return this.transaction(callback);
737
+ }
738
+
739
+ /**
740
+ * Closes the database connection pool or SQLite instance, checkpointing WAL if SQLite.
741
+ */
742
+ async close() {
743
+ this._stmtCache.clear();
744
+ if (this.db) {
745
+ try {
746
+ if (this._sqliteDriver === "node:sqlite") {
747
+ this.db.exec("PRAGMA wal_checkpoint(TRUNCATE);");
748
+ } else if (this._sqliteDriver === "better-sqlite3") {
749
+ this.db.pragma("wal_checkpoint(TRUNCATE)");
750
+ }
751
+ } catch {}
752
+ this.db.close();
753
+ this.db = null;
754
+ }
755
+ if (this.pool) {
756
+ if (typeof this.pool.end === "function") {
757
+ await this.pool.end();
758
+ }
759
+ this.pool = null;
760
+ }
761
+ _activeDatabases.delete(this);
762
+ }
763
+
764
+ /**
765
+ * Closes all active database instances across the application.
766
+ * @returns {Promise<void>}
767
+ */
768
+ /**
769
+ * Creates an atomic backup of this database instance.
770
+ * @param {Object} [options={}]
771
+ * @returns {Promise<{ success: boolean, file: string, filename: string, size: number, rotated: number, dbType: string }>}
772
+ */
773
+ async backup(options = {}) {
774
+ return Database.backup({ ...options, dbInstance: this });
775
+ }
776
+
777
+ /**
778
+ * Restores this database instance from a backup file.
779
+ * @param {string} filePath
780
+ * @param {Object} [options={}]
781
+ * @returns {Promise<{ success: boolean, restoredFrom: string, targetFile: string, preRestoreBackup?: string, size: number, dbType: string }>}
782
+ */
783
+ async restore(filePath, options = {}) {
784
+ return Database.restore(filePath, { ...options, dbInstance: this });
785
+ }
786
+
787
+ /**
788
+ * Creates an atomic, compressed database backup with automatic retention rotation.
789
+ * For SQLite, executes VACUUM INTO for non-blocking, WAL-safe online snapshots.
790
+ * @param {Object} [options={}]
791
+ * @param {string} [options.out] - Directory to store backups (default: database/backups).
792
+ * @param {boolean} [options.compress=true] - Whether to compress with gzip (.gz).
793
+ * @param {number} [options.keep=10] - Number of recent backups to retain.
794
+ * @param {string} [options.filename] - Custom output filename.
795
+ * @param {Database} [options.dbInstance] - Specific database instance to backup.
796
+ * @returns {Promise<{ success: boolean, file: string, filename: string, size: number, rotated: number, dbType: string }>}
797
+ */
798
+ static async backup(options = {}) {
799
+ const dbType = options.dbInstance?.type || options.dbType || DB_TYPE;
800
+ const backupDir = options.out
801
+ ? path.resolve(options.out)
802
+ : path.resolve(Config.userDataDir(), "database/backups");
803
+
804
+ if (!fs.existsSync(backupDir)) {
805
+ fs.mkdirSync(backupDir, { recursive: true });
806
+ }
807
+
808
+ const compress = options.compress !== false;
809
+ const keep = options.keep !== undefined ? parseInt(options.keep, 10) : 10;
810
+ const timestamp = getBackupTimestamp();
811
+
812
+ if (dbType === "sqlite") {
813
+ let dbFilePath =
814
+ options.dbInstance?.sqliteConfig?.filename ||
815
+ process.env.DB_FILE ||
816
+ "database/blue_bird.db";
817
+
818
+ if (!path.isAbsolute(dbFilePath) && dbFilePath !== ":memory:") {
819
+ dbFilePath = path.resolve(Config.userDataDir(), dbFilePath);
820
+ }
821
+
822
+ if (dbFilePath === ":memory:") {
823
+ throw new Error("Cannot backup an in-memory SQLite database (:memory:).");
824
+ }
825
+
826
+ if (!fs.existsSync(dbFilePath)) {
827
+ throw new Error(`SQLite database file not found: ${dbFilePath}`);
828
+ }
829
+
830
+ const ext = compress ? ".db.gz" : ".db";
831
+ const targetPath = uniqueBackupPath(backupDir, options.filename || `backup-sqlite-${timestamp}${ext}`);
832
+ const filename = path.basename(targetPath);
833
+ const tempDbPath = path.join(backupDir, `.temp-backup-${Date.now()}-${Math.random().toString(36).slice(2, 6)}.db`);
834
+
835
+ if (fs.existsSync(tempDbPath)) {
836
+ try { fs.unlinkSync(tempDbPath); } catch {}
837
+ }
838
+
839
+ if (options.dbInstance && options.dbInstance.db) {
840
+ options.dbInstance.db.exec(`VACUUM INTO '${tempDbPath.replace(/'/g, "''")}';`);
841
+ } else {
842
+ if (sqlitePromise?.DatabaseSync) {
843
+ const tempConn = new sqlitePromise.DatabaseSync(dbFilePath);
844
+ try {
845
+ tempConn.exec(`VACUUM INTO '${tempDbPath.replace(/'/g, "''")}';`);
846
+ } finally {
847
+ tempConn.close();
848
+ }
849
+ } else if (sqlitePromise?.BetterSqlite) {
850
+ const tempConn = new sqlitePromise.BetterSqlite(dbFilePath);
851
+ try {
852
+ tempConn.exec(`VACUUM INTO '${tempDbPath.replace(/'/g, "''")}';`);
853
+ } finally {
854
+ tempConn.close();
855
+ }
856
+ } else {
857
+ throw new Error("No SQLite driver available to perform VACUUM INTO backup.");
858
+ }
859
+ }
860
+
861
+ if (compress) {
862
+ const rawBytes = fs.readFileSync(tempDbPath);
863
+ const gzipped = zlib.gzipSync(rawBytes);
864
+ fs.writeFileSync(targetPath, gzipped);
865
+ try { fs.unlinkSync(tempDbPath); } catch {}
866
+ } else {
867
+ fs.renameSync(tempDbPath, targetPath);
868
+ }
869
+
870
+ const rotated = rotateBackups(backupDir, "backup-sqlite-", keep, targetPath);
871
+
872
+ return {
873
+ success: true,
874
+ file: targetPath,
875
+ filename,
876
+ size: fs.statSync(targetPath).size,
877
+ rotated,
878
+ dbType: "sqlite",
879
+ };
880
+ }
881
+
882
+ if (dbType === "postgres") {
883
+ const ext = compress ? ".sql.gz" : ".sql";
884
+ const targetPath = uniqueBackupPath(backupDir, options.filename || `backup-postgres-${timestamp}${ext}`);
885
+ const filename = path.basename(targetPath);
886
+
887
+ const dbName = process.env.DB_NAME || "blue_bird";
888
+ const dbHost = process.env.DB_HOST || "localhost";
889
+ const dbPort = process.env.DB_PORT || "5432";
890
+ const dbUser = process.env.DB_USER || "postgres";
891
+ const dbPass = process.env.DB_PASSWORD || "";
892
+
893
+ const env = { ...process.env, PGPASSWORD: dbPass };
894
+ let cmd = `pg_dump -h ${dbHost} -p ${dbPort} -U ${dbUser} -d ${dbName}`;
895
+ if (process.env.DATABASE_URL) {
896
+ cmd = `pg_dump "${process.env.DATABASE_URL}"`;
897
+ }
898
+
899
+ const dumpBuffer = execSync(cmd, { env, maxBuffer: 1024 * 1024 * 100 });
900
+ if (compress) {
901
+ fs.writeFileSync(targetPath, zlib.gzipSync(dumpBuffer));
902
+ } else {
903
+ fs.writeFileSync(targetPath, dumpBuffer);
904
+ }
905
+
906
+ const rotated = rotateBackups(backupDir, "backup-postgres-", keep, targetPath);
907
+ return {
908
+ success: true,
909
+ file: targetPath,
910
+ filename,
911
+ size: fs.statSync(targetPath).size,
912
+ rotated,
913
+ dbType: "postgres",
914
+ };
915
+ }
916
+
917
+ if (dbType === "mysql") {
918
+ const ext = compress ? ".sql.gz" : ".sql";
919
+ const targetPath = uniqueBackupPath(backupDir, options.filename || `backup-mysql-${timestamp}${ext}`);
920
+ const filename = path.basename(targetPath);
921
+
922
+ const dbName = process.env.DB_NAME || "blue_bird";
923
+ const dbHost = process.env.DB_HOST || "localhost";
924
+ const dbPort = process.env.DB_PORT || "3306";
925
+ const dbUser = process.env.DB_USER || "root";
926
+ const dbPass = process.env.DB_PASSWORD || "";
927
+
928
+ let cmd = `mysqldump -h ${dbHost} -P ${dbPort} -u ${dbUser} ${dbPass ? `-p${dbPass}` : ""} ${dbName}`;
929
+ const dumpBuffer = execSync(cmd, { maxBuffer: 1024 * 1024 * 100 });
930
+ if (compress) {
931
+ fs.writeFileSync(targetPath, zlib.gzipSync(dumpBuffer));
932
+ } else {
933
+ fs.writeFileSync(targetPath, dumpBuffer);
934
+ }
935
+
936
+ const rotated = rotateBackups(backupDir, "backup-mysql-", keep, targetPath);
937
+ return {
938
+ success: true,
939
+ file: targetPath,
940
+ filename,
941
+ size: fs.statSync(targetPath).size,
942
+ rotated,
943
+ dbType: "mysql",
944
+ };
945
+ }
946
+
947
+ throw new Error(`Unsupported database type '${dbType}' for backup.`);
948
+ }
949
+
950
+ /**
951
+ * Restores a database from a backup file with pre-restore safety snapshot and SQLite integrity verification.
952
+ * @param {string} filePath - Path to backup file (.db, .db.gz, .sql, .sql.gz).
953
+ * @param {Object} [options={}]
954
+ * @param {boolean} [options.safetyBackup=true] - Create pre-restore snapshot of current database.
955
+ * @param {boolean} [options.verify=true] - Verify SQLite PRAGMA integrity_check before overwriting.
956
+ * @param {Database} [options.dbInstance]
957
+ * @returns {Promise<{ success: boolean, restoredFrom: string, targetFile: string, preRestoreBackup?: string, size: number, dbType: string }>}
958
+ */
959
+ static async restore(filePath, options = {}) {
960
+ if (!filePath) {
961
+ throw new Error("Backup file path is required for restore.");
962
+ }
963
+
964
+ let resolvedFile = path.isAbsolute(filePath) ? filePath : path.resolve(process.cwd(), filePath);
965
+ if (!fs.existsSync(resolvedFile)) {
966
+ const inDefaultBackups = path.resolve(Config.userDataDir(), "database/backups", filePath);
967
+ if (fs.existsSync(inDefaultBackups)) {
968
+ resolvedFile = inDefaultBackups;
969
+ } else {
970
+ throw new Error(`Backup file not found: ${filePath}`);
971
+ }
972
+ }
973
+
974
+ const filename = path.basename(resolvedFile).toLowerCase();
975
+ let dbType = options.dbInstance?.type || options.dbType || DB_TYPE;
976
+ if (filename.includes("postgres")) {
977
+ dbType = "postgres";
978
+ } else if (filename.includes("mysql")) {
979
+ dbType = "mysql";
980
+ } else if (filename.endsWith(".db") || filename.endsWith(".db.gz")) {
981
+ dbType = "sqlite";
982
+ }
983
+
984
+ if (dbType === "sqlite") {
985
+ let targetDbPath =
986
+ options.dbInstance?.sqliteConfig?.filename ||
987
+ process.env.DB_FILE ||
988
+ "database/blue_bird.db";
989
+
990
+ if (!path.isAbsolute(targetDbPath) && targetDbPath !== ":memory:") {
991
+ targetDbPath = path.resolve(Config.userDataDir(), targetDbPath);
992
+ }
993
+
994
+ if (targetDbPath === ":memory:") {
995
+ throw new Error("Cannot restore into an in-memory SQLite database (:memory:).");
996
+ }
997
+
998
+ const candidateFile = path.join(
999
+ path.dirname(targetDbPath),
1000
+ `.restore-cand-${Date.now()}-${Math.random().toString(36).slice(2, 6)}.db`
1001
+ );
1002
+
1003
+ if (resolvedFile.endsWith(".gz")) {
1004
+ const compressed = fs.readFileSync(resolvedFile);
1005
+ const decompressed = zlib.gunzipSync(compressed);
1006
+ fs.writeFileSync(candidateFile, decompressed);
1007
+ } else {
1008
+ fs.copyFileSync(resolvedFile, candidateFile);
1009
+ }
1010
+
1011
+ if (options.verify !== false) {
1012
+ let integrityOk = false;
1013
+ let integrityMsg = "";
1014
+
1015
+ if (sqlitePromise?.DatabaseSync) {
1016
+ const testDb = new sqlitePromise.DatabaseSync(candidateFile);
1017
+ try {
1018
+ const row = testDb.prepare("PRAGMA integrity_check;").get();
1019
+ if (row && (row.integrity_check === "ok" || Object.values(row)[0] === "ok")) {
1020
+ integrityOk = true;
1021
+ } else {
1022
+ integrityMsg = JSON.stringify(row);
1023
+ }
1024
+ } finally {
1025
+ testDb.close();
1026
+ }
1027
+ } else if (sqlitePromise?.BetterSqlite) {
1028
+ const testDb = new sqlitePromise.BetterSqlite(candidateFile);
1029
+ try {
1030
+ const row = testDb.pragma("integrity_check", { simple: true });
1031
+ if (row === "ok") {
1032
+ integrityOk = true;
1033
+ } else {
1034
+ integrityMsg = String(row);
1035
+ }
1036
+ } finally {
1037
+ testDb.close();
1038
+ }
1039
+ }
1040
+
1041
+ if (!integrityOk) {
1042
+ try { fs.unlinkSync(candidateFile); } catch {}
1043
+ throw new Error(`Database restore aborted: backup failed integrity check (${integrityMsg || "unknown error"}).`);
1044
+ }
1045
+ }
1046
+
1047
+ if (options.dbInstance) {
1048
+ try {
1049
+ await options.dbInstance.close();
1050
+ } catch {}
1051
+ }
1052
+ await Database.closeAll();
1053
+
1054
+ let preRestoreBackup = null;
1055
+ if (options.safetyBackup !== false && fs.existsSync(targetDbPath)) {
1056
+ const backupDir = path.resolve(Config.userDataDir(), "database/backups");
1057
+ if (!fs.existsSync(backupDir)) {
1058
+ fs.mkdirSync(backupDir, { recursive: true });
1059
+ }
1060
+ preRestoreBackup = uniqueBackupPath(backupDir, `pre-restore-sqlite-${getBackupTimestamp()}.db`);
1061
+ fs.copyFileSync(targetDbPath, preRestoreBackup);
1062
+ }
1063
+
1064
+ const targetDir = path.dirname(targetDbPath);
1065
+ if (!fs.existsSync(targetDir)) {
1066
+ fs.mkdirSync(targetDir, { recursive: true });
1067
+ }
1068
+
1069
+ try {
1070
+ fs.unlinkSync(targetDbPath);
1071
+ } catch {}
1072
+
1073
+ try {
1074
+ fs.copyFileSync(candidateFile, targetDbPath);
1075
+ } catch {
1076
+ await new Promise((resolve) => setTimeout(resolve, 100));
1077
+ fs.copyFileSync(candidateFile, targetDbPath);
1078
+ }
1079
+ try { fs.unlinkSync(candidateFile); } catch {}
1080
+
1081
+ const walFile = `${targetDbPath}-wal`;
1082
+ const shmFile = `${targetDbPath}-shm`;
1083
+ if (fs.existsSync(walFile)) {
1084
+ try { fs.unlinkSync(walFile); } catch {}
1085
+ }
1086
+ if (fs.existsSync(shmFile)) {
1087
+ try { fs.unlinkSync(shmFile); } catch {}
1088
+ }
1089
+
1090
+ return {
1091
+ success: true,
1092
+ restoredFrom: resolvedFile,
1093
+ targetFile: targetDbPath,
1094
+ preRestoreBackup,
1095
+ size: fs.statSync(targetDbPath).size,
1096
+ dbType: "sqlite",
1097
+ };
1098
+ }
1099
+
1100
+ if (dbType === "postgres") {
1101
+ let sqlFile = resolvedFile;
1102
+ let tempSql = null;
1103
+ if (resolvedFile.endsWith(".gz")) {
1104
+ tempSql = path.join(os.tmpdir(), `bluebird-restore-${Date.now()}.sql`);
1105
+ fs.writeFileSync(tempSql, zlib.gunzipSync(fs.readFileSync(resolvedFile)));
1106
+ sqlFile = tempSql;
1107
+ }
1108
+
1109
+ await Database.closeAll();
1110
+
1111
+ const dbName = process.env.DB_NAME || "blue_bird";
1112
+ const dbHost = process.env.DB_HOST || "localhost";
1113
+ const dbPort = process.env.DB_PORT || "5432";
1114
+ const dbUser = process.env.DB_USER || "postgres";
1115
+ const dbPass = process.env.DB_PASSWORD || "";
1116
+
1117
+ const env = { ...process.env, PGPASSWORD: dbPass };
1118
+ let cmd = `psql -h ${dbHost} -p ${dbPort} -U ${dbUser} -d ${dbName} -f "${sqlFile}"`;
1119
+ if (process.env.DATABASE_URL) {
1120
+ cmd = `psql "${process.env.DATABASE_URL}" -f "${sqlFile}"`;
1121
+ }
1122
+
1123
+ execSync(cmd, { env });
1124
+ if (tempSql) {
1125
+ try { fs.unlinkSync(tempSql); } catch {}
1126
+ }
1127
+
1128
+ return {
1129
+ success: true,
1130
+ restoredFrom: resolvedFile,
1131
+ targetFile: dbName,
1132
+ dbType: "postgres",
1133
+ };
1134
+ }
1135
+
1136
+ if (dbType === "mysql") {
1137
+ let sqlFile = resolvedFile;
1138
+ let tempSql = null;
1139
+ if (resolvedFile.endsWith(".gz")) {
1140
+ tempSql = path.join(os.tmpdir(), `bluebird-restore-${Date.now()}.sql`);
1141
+ fs.writeFileSync(tempSql, zlib.gunzipSync(fs.readFileSync(resolvedFile)));
1142
+ sqlFile = tempSql;
1143
+ }
1144
+
1145
+ await Database.closeAll();
1146
+
1147
+ const dbName = process.env.DB_NAME || "blue_bird";
1148
+ const dbHost = process.env.DB_HOST || "localhost";
1149
+ const dbPort = process.env.DB_PORT || "3306";
1150
+ const dbUser = process.env.DB_USER || "root";
1151
+ const dbPass = process.env.DB_PASSWORD || "";
1152
+
1153
+ let cmd = `mysql -h ${dbHost} -P ${dbPort} -u ${dbUser} ${dbPass ? `-p${dbPass}` : ""} ${dbName} < "${sqlFile}"`;
1154
+ execSync(cmd, { shell: true });
1155
+
1156
+ if (tempSql) {
1157
+ try { fs.unlinkSync(tempSql); } catch {}
1158
+ }
1159
+
1160
+ return {
1161
+ success: true,
1162
+ restoredFrom: resolvedFile,
1163
+ targetFile: dbName,
1164
+ dbType: "mysql",
1165
+ };
1166
+ }
1167
+
1168
+ throw new Error(`Unsupported database type '${dbType}' for restore.`);
1169
+ }
1170
+
1171
+ static async closeAll() {
1172
+ const list = Array.from(_activeDatabases);
1173
+ for (const db of list) {
1174
+ try {
1175
+ await db.close();
1176
+ } catch (err) {
1177
+ console.error("[DATABASE] Error closing database connection:", err.message);
1178
+ }
1179
+ }
1180
+ }
1181
+ }
1182
+
1183
+ export { Database, DB_TYPE };
1184
+ export default Database;