@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.
- package/AGENTS.md +727 -620
- package/README.md +670 -607
- package/app/models/user.js +19 -0
- package/app/resources/html/home.html +137 -0
- package/app/resources/html/layouts/main.html +55 -0
- package/app/resources/html/notFound.html +14 -0
- package/app/resources/html/table.html +15 -0
- package/app/resources/html/terms.html +46 -0
- package/app/resources/index.html +27 -0
- package/app/resources/layouts/AppLayout.jsx +92 -0
- package/app/resources/main.jsx +18 -0
- package/app/resources/pages/Dashboard.jsx +93 -0
- package/app/resources/pages/Home.jsx +140 -0
- package/app/resources/pages/Login.jsx +35 -0
- package/app/resources/pages/NotFound.jsx +16 -0
- package/app/resources/pages/Register.jsx +55 -0
- package/app/resources/pages/TableDemo.jsx +85 -0
- package/app/resources/routes.jsx +59 -0
- package/app/resources/spa.js +73 -0
- package/app/resources/styles.css +9 -0
- package/app/routes/api.js +129 -50
- package/app/routes/auth.js +209 -0
- package/app/routes/web.js +89 -47
- package/core/ai.js +30 -10
- package/core/app.d.ts +2 -18
- package/core/app.js +987 -801
- package/core/auth.d.ts +2 -13
- package/core/auth.js +444 -326
- package/core/cli/build.js +37 -0
- package/core/cli/dev.js +155 -0
- package/core/cli/doctor.js +37 -2
- package/core/cli/export.js +191 -0
- package/core/cli/init.js +91 -322
- package/core/cli/nginx.js +1 -1
- package/core/cli/templates.js +139 -0
- package/core/cli/view.js +98 -161
- package/core/config.js +44 -2
- package/core/csrf.js +156 -24
- package/core/database.js +1184 -1131
- package/core/debug.js +1 -1
- package/core/html.js +8 -1
- package/core/index.d.ts +126 -310
- package/core/paths.js +55 -0
- package/core/ratelimit.js +10 -1
- package/core/react/client/api.js +239 -0
- package/core/react/client/auth.js +236 -0
- package/core/react/client/components.js +1321 -0
- package/core/react/client/datatable.js +595 -0
- package/core/react/client/i18n.js +440 -0
- package/core/react/client/index.d.ts +314 -0
- package/core/react/client/index.js +50 -0
- package/core/react/client/router.js +26 -0
- package/core/react/client/theme.css +512 -0
- package/core/render-cache.js +250 -212
- package/core/render.d.ts +25 -21
- package/core/render.js +738 -736
- package/core/router.d.ts +2 -3
- package/core/router.js +171 -171
- package/core/seo.js +10 -0
- package/core/spa.js +599 -0
- package/core/view-loader.js +155 -613
- package/core/vite-plugin.d.ts +18 -0
- package/core/vite-plugin.js +162 -0
- package/core/vite.js +250 -145
- package/index.js +22 -18
- package/jsconfig.json +5 -3
- package/package.json +114 -92
- package/production.md +8 -3
- package/public/js/bluebird.js +1886 -0
- package/templates/_auth/app/database.js +19 -0
- package/templates/_auth/app/models/user.js +22 -0
- package/templates/_auth/app/routes/auth-router.js +304 -0
- package/templates/_base/app/resources/html/layouts/main.html +55 -0
- package/templates/_base/app/resources/html/notFound.html +14 -0
- package/templates/_base/app/resources/index.html +27 -0
- package/templates/_base/app/resources/styles.css +9 -0
- package/templates/api/app/models/note.js +18 -0
- package/templates/api/app/routes/api.js +82 -0
- package/templates/api/app/routes/auth.js +11 -0
- package/templates/api/index.js +19 -0
- package/templates/api/template.json +13 -0
- package/templates/auth/app/mail.js +11 -0
- package/templates/auth/app/models/password_reset.js +18 -0
- package/templates/auth/app/resources/html/home.html +21 -0
- package/templates/auth/app/resources/html/partials/nav.html +2 -0
- package/templates/auth/app/resources/layouts/AppLayout.jsx +60 -0
- package/templates/auth/app/resources/main.jsx +18 -0
- package/templates/auth/app/resources/pages/Dashboard.jsx +51 -0
- package/templates/auth/app/resources/pages/ForgotPassword.jsx +34 -0
- package/templates/auth/app/resources/pages/Login.jsx +36 -0
- package/templates/auth/app/resources/pages/NotFound.jsx +16 -0
- package/templates/auth/app/resources/pages/Profile.jsx +99 -0
- package/templates/auth/app/resources/pages/Register.jsx +50 -0
- package/templates/auth/app/resources/pages/ResetPassword.jsx +50 -0
- package/templates/auth/app/resources/routes.jsx +54 -0
- package/templates/auth/app/resources/spa.js +29 -0
- package/templates/auth/app/routes/api.js +17 -0
- package/templates/auth/app/routes/auth.js +13 -0
- package/templates/auth/app/routes/web.js +21 -0
- package/templates/auth/index.js +19 -0
- package/templates/auth/template.json +15 -0
- package/templates/blank/app/models/.gitkeep +0 -0
- package/templates/blank/app/resources/html/home.html +27 -0
- package/templates/blank/app/resources/html/partials/nav.html +1 -0
- package/templates/blank/app/resources/main.jsx +16 -0
- package/templates/blank/app/resources/pages/Home.jsx +42 -0
- package/templates/blank/app/resources/pages/NotFound.jsx +27 -0
- package/templates/blank/app/resources/routes.jsx +15 -0
- package/templates/blank/app/resources/spa.js +24 -0
- package/templates/blank/app/routes/api.js +11 -0
- package/templates/blank/app/routes/web.js +21 -0
- package/templates/blank/index.js +13 -0
- package/templates/blank/template.json +12 -0
- package/templates/blog/app/lib/blog.js +149 -0
- package/templates/blog/app/models/post.js +22 -0
- package/templates/blog/app/resources/html/home.html +28 -0
- package/templates/blog/app/resources/html/not-found.html +5 -0
- package/templates/blog/app/resources/html/partials/nav.html +2 -0
- package/templates/blog/app/resources/html/partials/post-card.html +9 -0
- package/templates/blog/app/resources/html/post.html +8 -0
- package/templates/blog/app/resources/layouts/AdminLayout.jsx +54 -0
- package/templates/blog/app/resources/main.jsx +18 -0
- package/templates/blog/app/resources/pages/Login.jsx +31 -0
- package/templates/blog/app/resources/pages/NotFound.jsx +16 -0
- package/templates/blog/app/resources/pages/PostEditor.jsx +51 -0
- package/templates/blog/app/resources/pages/Posts.jsx +83 -0
- package/templates/blog/app/resources/pages/Register.jsx +43 -0
- package/templates/blog/app/resources/routes.jsx +51 -0
- package/templates/blog/app/resources/spa.js +25 -0
- package/templates/blog/app/resources/styles.css +40 -0
- package/templates/blog/app/routes/api.js +77 -0
- package/templates/blog/app/routes/auth.js +10 -0
- package/templates/blog/app/routes/web.js +114 -0
- package/templates/blog/index.js +21 -0
- package/templates/blog/template.json +14 -0
- package/vite.config.js +11 -0
- package/app/views/components/Header.jsx +0 -42
- package/app/views/components/LiveCounter.jsx +0 -67
- package/app/views/layouts/main/view.jsx +0 -201
- package/app/views/legal/terms.html +0 -29
- package/app/views/pages/about.jsx +0 -98
- package/app/views/pages/dashboard.jsx +0 -278
- package/app/views/pages/index.jsx +0 -123
- package/app/views/pages/login.jsx +0 -141
- package/core/actions.d.ts +0 -4
- package/core/actions.js +0 -355
- package/core/jsx.d.ts +0 -38
- package/core/jsx.js +0 -1597
- package/core/vite.d.ts +0 -3
- package/public/js/bluebird-client.js +0 -3265
- 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
|
-
|
|
158
|
-
|
|
159
|
-
*
|
|
160
|
-
* @param {
|
|
161
|
-
* @returns {number}
|
|
162
|
-
*/
|
|
163
|
-
function
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
if (
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
process.env.DATABASE_URL.startsWith("
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
this.
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
*
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
const ext = compress ? ".
|
|
831
|
-
const
|
|
832
|
-
const
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
const
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
}
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
const
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
}
|
|
993
|
-
|
|
994
|
-
if (
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
fs.copyFileSync(
|
|
1009
|
-
}
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
const
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
if (
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
if (
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
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;
|