@seip/bluebird-js 0.1.6 → 0.2.0

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 (152) hide show
  1. package/.vscode/extensions.json +7 -7
  2. package/.vscode/settings.json +10 -10
  3. package/AGENTS.md +266 -116
  4. package/README.md +258 -245
  5. package/app/models/user.js +19 -0
  6. package/app/resources/html/home.html +137 -0
  7. package/app/resources/html/layouts/main.html +54 -0
  8. package/app/resources/html/notFound.html +14 -0
  9. package/app/resources/html/terms.html +46 -0
  10. package/app/resources/index.html +27 -0
  11. package/app/resources/layouts/AppLayout.jsx +89 -0
  12. package/app/resources/main.jsx +18 -0
  13. package/app/resources/pages/Dashboard.jsx +98 -0
  14. package/app/resources/pages/Home.jsx +140 -0
  15. package/app/resources/pages/Login.jsx +35 -0
  16. package/app/resources/pages/NotFound.jsx +16 -0
  17. package/app/resources/pages/Register.jsx +55 -0
  18. package/app/resources/routes.jsx +54 -0
  19. package/app/resources/spa.js +67 -0
  20. package/app/resources/styles.css +9 -0
  21. package/app/routes/api.js +85 -50
  22. package/app/routes/auth.js +209 -0
  23. package/app/routes/web.js +49 -37
  24. package/core/ai.d.ts +151 -151
  25. package/core/ai.js +1071 -1051
  26. package/core/app.d.ts +2 -18
  27. package/core/app.js +978 -792
  28. package/core/auth.d.ts +2 -13
  29. package/core/auth.js +444 -326
  30. package/core/cli/backup.js +167 -167
  31. package/core/cli/build.js +37 -0
  32. package/core/cli/dev.js +155 -0
  33. package/core/cli/doctor.js +37 -2
  34. package/core/cli/export.js +191 -0
  35. package/core/cli/init.js +101 -332
  36. package/core/cli/nginx.js +1 -1
  37. package/core/cli/templates.js +139 -0
  38. package/core/cli/view.js +73 -136
  39. package/core/config.js +44 -2
  40. package/core/csrf.js +156 -24
  41. package/core/database.js +737 -684
  42. package/core/debug.js +1 -1
  43. package/core/html.js +8 -1
  44. package/core/index.d.ts +1286 -1431
  45. package/core/paths.js +55 -0
  46. package/core/ratelimit.js +10 -1
  47. package/core/react/client/api.js +237 -0
  48. package/core/react/client/auth.js +236 -0
  49. package/core/react/client/components.js +1321 -0
  50. package/core/react/client/i18n.js +338 -0
  51. package/core/react/client/index.d.ts +249 -0
  52. package/core/react/client/index.js +49 -0
  53. package/core/react/client/router.js +26 -0
  54. package/core/react/client/theme.css +512 -0
  55. package/core/render-cache.js +250 -212
  56. package/core/render.d.ts +25 -21
  57. package/core/render.js +613 -603
  58. package/core/router.d.ts +2 -3
  59. package/core/router.js +171 -171
  60. package/core/seo.js +10 -0
  61. package/core/spa.js +599 -0
  62. package/core/view-loader.js +81 -455
  63. package/core/vite-plugin.d.ts +18 -0
  64. package/core/vite-plugin.js +162 -0
  65. package/core/vite.js +250 -145
  66. package/index.js +22 -18
  67. package/jsconfig.json +5 -3
  68. package/package.json +114 -92
  69. package/production.md +8 -3
  70. package/public/js/bluebird.js +1160 -0
  71. package/templates/_auth/app/database.js +19 -0
  72. package/templates/_auth/app/models/user.js +22 -0
  73. package/templates/_auth/app/routes/auth-router.js +304 -0
  74. package/templates/_base/app/resources/html/layouts/main.html +55 -0
  75. package/templates/_base/app/resources/html/notFound.html +14 -0
  76. package/templates/_base/app/resources/index.html +27 -0
  77. package/templates/_base/app/resources/styles.css +9 -0
  78. package/templates/api/app/models/note.js +18 -0
  79. package/templates/api/app/routes/api.js +82 -0
  80. package/templates/api/app/routes/auth.js +11 -0
  81. package/templates/api/index.js +19 -0
  82. package/templates/api/template.json +13 -0
  83. package/templates/auth/app/mail.js +11 -0
  84. package/templates/auth/app/models/password_reset.js +18 -0
  85. package/templates/auth/app/resources/html/home.html +21 -0
  86. package/templates/auth/app/resources/html/partials/nav.html +2 -0
  87. package/templates/auth/app/resources/layouts/AppLayout.jsx +60 -0
  88. package/templates/auth/app/resources/main.jsx +18 -0
  89. package/templates/auth/app/resources/pages/Dashboard.jsx +51 -0
  90. package/templates/auth/app/resources/pages/ForgotPassword.jsx +34 -0
  91. package/templates/auth/app/resources/pages/Login.jsx +36 -0
  92. package/templates/auth/app/resources/pages/NotFound.jsx +16 -0
  93. package/templates/auth/app/resources/pages/Profile.jsx +99 -0
  94. package/templates/auth/app/resources/pages/Register.jsx +50 -0
  95. package/templates/auth/app/resources/pages/ResetPassword.jsx +50 -0
  96. package/templates/auth/app/resources/routes.jsx +54 -0
  97. package/templates/auth/app/resources/spa.js +29 -0
  98. package/templates/auth/app/routes/api.js +17 -0
  99. package/templates/auth/app/routes/auth.js +13 -0
  100. package/templates/auth/app/routes/web.js +21 -0
  101. package/templates/auth/index.js +19 -0
  102. package/templates/auth/template.json +15 -0
  103. package/templates/blank/app/models/.gitkeep +0 -0
  104. package/templates/blank/app/resources/html/home.html +27 -0
  105. package/templates/blank/app/resources/html/partials/nav.html +1 -0
  106. package/templates/blank/app/resources/main.jsx +16 -0
  107. package/templates/blank/app/resources/pages/Home.jsx +42 -0
  108. package/templates/blank/app/resources/pages/NotFound.jsx +27 -0
  109. package/templates/blank/app/resources/routes.jsx +15 -0
  110. package/templates/blank/app/resources/spa.js +24 -0
  111. package/templates/blank/app/routes/api.js +11 -0
  112. package/templates/blank/app/routes/web.js +21 -0
  113. package/templates/blank/index.js +13 -0
  114. package/templates/blank/template.json +12 -0
  115. package/templates/blog/app/lib/blog.js +149 -0
  116. package/templates/blog/app/models/post.js +22 -0
  117. package/templates/blog/app/resources/html/home.html +28 -0
  118. package/templates/blog/app/resources/html/not-found.html +5 -0
  119. package/templates/blog/app/resources/html/partials/nav.html +2 -0
  120. package/templates/blog/app/resources/html/partials/post-card.html +9 -0
  121. package/templates/blog/app/resources/html/post.html +8 -0
  122. package/templates/blog/app/resources/layouts/AdminLayout.jsx +54 -0
  123. package/templates/blog/app/resources/main.jsx +18 -0
  124. package/templates/blog/app/resources/pages/Login.jsx +31 -0
  125. package/templates/blog/app/resources/pages/NotFound.jsx +16 -0
  126. package/templates/blog/app/resources/pages/PostEditor.jsx +51 -0
  127. package/templates/blog/app/resources/pages/Posts.jsx +83 -0
  128. package/templates/blog/app/resources/pages/Register.jsx +43 -0
  129. package/templates/blog/app/resources/routes.jsx +51 -0
  130. package/templates/blog/app/resources/spa.js +25 -0
  131. package/templates/blog/app/resources/styles.css +40 -0
  132. package/templates/blog/app/routes/api.js +77 -0
  133. package/templates/blog/app/routes/auth.js +10 -0
  134. package/templates/blog/app/routes/web.js +114 -0
  135. package/templates/blog/index.js +21 -0
  136. package/templates/blog/template.json +14 -0
  137. package/vite.config.js +11 -0
  138. package/app/views/about.jsx +0 -98
  139. package/app/views/components/Header.jsx +0 -42
  140. package/app/views/components/LiveCounter.jsx +0 -66
  141. package/app/views/dashboard.jsx +0 -300
  142. package/app/views/index.jsx +0 -123
  143. package/app/views/layouts/main/view.jsx +0 -201
  144. package/app/views/legal/terms.html +0 -29
  145. package/app/views/login.jsx +0 -141
  146. package/core/actions.d.ts +0 -4
  147. package/core/actions.js +0 -329
  148. package/core/jsx.d.ts +0 -38
  149. package/core/jsx.js +0 -1432
  150. package/core/vite.d.ts +0 -3
  151. package/public/js/bluebird-client.js +0 -3161
  152. package/public/js/tailwind.js +0 -8
package/core/database.js CHANGED
@@ -1,139 +1,139 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
3
  import crypto from "node:crypto";
4
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
-
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
137
  const _activeDatabases = new Set();
138
138
 
139
139
  /**
@@ -153,14 +153,62 @@ function getBackupTimestamp() {
153
153
  return `${year}-${month}-${day}_${hours}${mins}${secs}_${ms}`;
154
154
  }
155
155
 
156
+ const BACKUP_STAMP = /(\d{4}-\d{2}-\d{2}_\d{6}_\d{3})(?:-(\d+))?/;
157
+
156
158
  /**
157
- * Rotates backups in backupDir, keeping only the most recent N backups.
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`.
158
205
  * @param {string} backupDir
159
206
  * @param {string} prefix
160
207
  * @param {number} [keep=10]
208
+ * @param {string} [protectFile] - Absolute path of the backup that was just created.
161
209
  * @returns {number} Count of deleted backups.
162
210
  */
163
- function rotateBackups(backupDir, prefix, keep = 10) {
211
+ function rotateBackups(backupDir, prefix, keep = 10, protectFile = "") {
164
212
  if (!fs.existsSync(backupDir) || keep <= 0) return 0;
165
213
  try {
166
214
  const files = fs.readdirSync(backupDir)
@@ -173,7 +221,12 @@ function rotateBackups(backupDir, prefix, keep = 10) {
173
221
  mtime: fs.statSync(fullPath).mtimeMs,
174
222
  };
175
223
  })
176
- .sort((a, b) => b.mtime - a.mtime);
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
+ }
177
230
 
178
231
  let deleted = 0;
179
232
  if (files.length > keep) {
@@ -188,530 +241,530 @@ function rotateBackups(backupDir, prefix, keep = 10) {
188
241
  } catch {
189
242
  return 0;
190
243
  }
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;
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;
315
368
  _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
- */
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
+ */
715
768
  /**
716
769
  * Creates an atomic backup of this database instance.
717
770
  * @param {Object} [options={}]
@@ -775,8 +828,8 @@ class Database {
775
828
  }
776
829
 
777
830
  const ext = compress ? ".db.gz" : ".db";
778
- const filename = options.filename || `backup-sqlite-${timestamp}${ext}`;
779
- const targetPath = path.join(backupDir, filename);
831
+ const targetPath = uniqueBackupPath(backupDir, options.filename || `backup-sqlite-${timestamp}${ext}`);
832
+ const filename = path.basename(targetPath);
780
833
  const tempDbPath = path.join(backupDir, `.temp-backup-${Date.now()}-${Math.random().toString(36).slice(2, 6)}.db`);
781
834
 
782
835
  if (fs.existsSync(tempDbPath)) {
@@ -814,7 +867,7 @@ class Database {
814
867
  fs.renameSync(tempDbPath, targetPath);
815
868
  }
816
869
 
817
- const rotated = rotateBackups(backupDir, "backup-sqlite-", keep);
870
+ const rotated = rotateBackups(backupDir, "backup-sqlite-", keep, targetPath);
818
871
 
819
872
  return {
820
873
  success: true,
@@ -828,8 +881,8 @@ class Database {
828
881
 
829
882
  if (dbType === "postgres") {
830
883
  const ext = compress ? ".sql.gz" : ".sql";
831
- const filename = options.filename || `backup-postgres-${timestamp}${ext}`;
832
- const targetPath = path.join(backupDir, filename);
884
+ const targetPath = uniqueBackupPath(backupDir, options.filename || `backup-postgres-${timestamp}${ext}`);
885
+ const filename = path.basename(targetPath);
833
886
 
834
887
  const dbName = process.env.DB_NAME || "blue_bird";
835
888
  const dbHost = process.env.DB_HOST || "localhost";
@@ -850,7 +903,7 @@ class Database {
850
903
  fs.writeFileSync(targetPath, dumpBuffer);
851
904
  }
852
905
 
853
- const rotated = rotateBackups(backupDir, "backup-postgres-", keep);
906
+ const rotated = rotateBackups(backupDir, "backup-postgres-", keep, targetPath);
854
907
  return {
855
908
  success: true,
856
909
  file: targetPath,
@@ -863,8 +916,8 @@ class Database {
863
916
 
864
917
  if (dbType === "mysql") {
865
918
  const ext = compress ? ".sql.gz" : ".sql";
866
- const filename = options.filename || `backup-mysql-${timestamp}${ext}`;
867
- const targetPath = path.join(backupDir, filename);
919
+ const targetPath = uniqueBackupPath(backupDir, options.filename || `backup-mysql-${timestamp}${ext}`);
920
+ const filename = path.basename(targetPath);
868
921
 
869
922
  const dbName = process.env.DB_NAME || "blue_bird";
870
923
  const dbHost = process.env.DB_HOST || "localhost";
@@ -880,7 +933,7 @@ class Database {
880
933
  fs.writeFileSync(targetPath, dumpBuffer);
881
934
  }
882
935
 
883
- const rotated = rotateBackups(backupDir, "backup-mysql-", keep);
936
+ const rotated = rotateBackups(backupDir, "backup-mysql-", keep, targetPath);
884
937
  return {
885
938
  success: true,
886
939
  file: targetPath,
@@ -1004,7 +1057,7 @@ class Database {
1004
1057
  if (!fs.existsSync(backupDir)) {
1005
1058
  fs.mkdirSync(backupDir, { recursive: true });
1006
1059
  }
1007
- preRestoreBackup = path.join(backupDir, `pre-restore-sqlite-${getBackupTimestamp()}.db`);
1060
+ preRestoreBackup = uniqueBackupPath(backupDir, `pre-restore-sqlite-${getBackupTimestamp()}.db`);
1008
1061
  fs.copyFileSync(targetDbPath, preRestoreBackup);
1009
1062
  }
1010
1063
 
@@ -1115,17 +1168,17 @@ class Database {
1115
1168
  throw new Error(`Unsupported database type '${dbType}' for restore.`);
1116
1169
  }
1117
1170
 
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;
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;