@seip/bluebird-js 0.0.1 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/.env_example +53 -53
  2. package/AGENTS.md +426 -403
  3. package/LICENSE +1 -1
  4. package/README.md +292 -285
  5. package/app/routes/api.js +50 -50
  6. package/app/routes/web.js +55 -53
  7. package/app/views/about.js +63 -0
  8. package/app/views/dashboard.js +147 -0
  9. package/app/views/index.js +80 -0
  10. package/app/views/layouts/main/view.js +81 -0
  11. package/app/views/legal/terms.html +19 -0
  12. package/app/views/login.js +80 -0
  13. package/core/app.d.ts +18 -18
  14. package/core/app.js +684 -644
  15. package/core/auth.d.ts +13 -13
  16. package/core/auth.js +326 -326
  17. package/core/cache.d.ts +17 -17
  18. package/core/cache.js +475 -475
  19. package/core/cli/doctor.js +287 -287
  20. package/core/cli/ecosystem.js +162 -162
  21. package/core/cli/init.js +779 -779
  22. package/core/cli/migrate.js +541 -541
  23. package/core/cli/model.js +66 -66
  24. package/core/cli/nginx.js +199 -199
  25. package/core/cli/route.js +120 -120
  26. package/core/cli/view.js +55 -36
  27. package/core/config.d.ts +3 -3
  28. package/core/config.js +111 -111
  29. package/core/csrf.d.ts +3 -3
  30. package/core/csrf.js +114 -114
  31. package/core/database.d.ts +15 -15
  32. package/core/database.js +636 -636
  33. package/core/debug.d.ts +3 -3
  34. package/core/debug.js +249 -249
  35. package/core/hash.d.ts +3 -3
  36. package/core/hash.js +194 -194
  37. package/core/html.d.ts +42 -0
  38. package/core/html.js +217 -0
  39. package/core/index.d.ts +1176 -1071
  40. package/core/logger.d.ts +3 -3
  41. package/core/logger.js +127 -124
  42. package/core/middleware.d.ts +3 -3
  43. package/core/middleware.js +28 -28
  44. package/core/model.d.ts +19 -19
  45. package/core/model.js +600 -600
  46. package/core/queue.d.ts +13 -13
  47. package/core/queue.js +172 -172
  48. package/core/ratelimit.d.ts +3 -3
  49. package/core/ratelimit.js +145 -145
  50. package/core/redis.d.ts +21 -21
  51. package/core/redis.js +230 -230
  52. package/core/render-cache.js +212 -0
  53. package/core/render.d.ts +3 -3
  54. package/core/render.js +199 -555
  55. package/core/router.d.ts +3 -3
  56. package/core/router.js +171 -171
  57. package/core/seo.d.ts +3 -3
  58. package/core/seo.js +106 -106
  59. package/core/swagger.d.ts +3 -3
  60. package/core/swagger.js +60 -60
  61. package/core/upload.d.ts +13 -13
  62. package/core/upload.js +102 -102
  63. package/core/util/colors.js +82 -82
  64. package/core/validate.d.ts +15 -15
  65. package/core/validate.js +364 -364
  66. package/core/view-loader.js +162 -0
  67. package/core/vite.d.ts +3 -3
  68. package/core/vite.js +145 -145
  69. package/core/ws.d.ts +13 -13
  70. package/core/ws.js +245 -245
  71. package/index.js +18 -18
  72. package/jsconfig.json +15 -15
  73. package/package.json +85 -86
  74. package/production.md +273 -273
  75. package/public/css/bluebird.min.css +1 -1
  76. package/public/js/bluebird-client.js +1780 -1662
  77. package/public/js/bluebird.min.js +1072 -1072
  78. package/app/views/about.html +0 -161
  79. package/app/views/dashboard.html +0 -140
  80. package/app/views/index.html +0 -150
  81. package/app/views/login.html +0 -144
package/core/database.js CHANGED
@@ -1,636 +1,636 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
- import crypto from "node:crypto";
4
- import Config from "./config.js";
5
- import Cache from "./cache.js";
6
-
7
- const rawDbType = (process.env.DB_TYPE || "").toLowerCase().trim();
8
- let DB_TYPE = "";
9
-
10
- if (
11
- rawDbType === "sqlite" ||
12
- rawDbType === "sqlite3" ||
13
- rawDbType === "sql" ||
14
- rawDbType === "better-sqlite3" ||
15
- rawDbType === "better-sqlite" ||
16
- rawDbType === "lite"
17
- ) {
18
- DB_TYPE = "sqlite";
19
- } else if (
20
- rawDbType === "postgres" ||
21
- rawDbType === "postgresql" ||
22
- rawDbType === "pg" ||
23
- rawDbType === "psql" ||
24
- rawDbType === "pgsql" ||
25
- rawDbType === "postgre" ||
26
- rawDbType === "postgr" ||
27
- rawDbType === "psgr"
28
- ) {
29
- DB_TYPE = "postgres";
30
- } else if (
31
- rawDbType === "mysql" ||
32
- rawDbType === "mariadb" ||
33
- rawDbType === "maria" ||
34
- rawDbType === "my"
35
- ) {
36
- DB_TYPE = "mysql";
37
- } else if (
38
- rawDbType === "none" ||
39
- rawDbType === "no" ||
40
- rawDbType === "false" ||
41
- rawDbType === "null" ||
42
- rawDbType === "0"
43
- ) {
44
- DB_TYPE = "none";
45
- }
46
-
47
- if (
48
- !DB_TYPE &&
49
- process.env.DATABASE_URL &&
50
- !process.env.DATABASE_URL.startsWith("#")
51
- ) {
52
- if (
53
- process.env.DATABASE_URL.startsWith("postgres://") ||
54
- process.env.DATABASE_URL.startsWith("postgresql://")
55
- ) {
56
- DB_TYPE = "postgres";
57
- } else if (process.env.DATABASE_URL.startsWith("mysql://")) {
58
- DB_TYPE = "mysql";
59
- } else if (
60
- process.env.DATABASE_URL.startsWith("sqlite://") ||
61
- process.env.DATABASE_URL.startsWith("sqlite:")
62
- ) {
63
- DB_TYPE = "sqlite";
64
- }
65
- }
66
- if (!DB_TYPE) {
67
- DB_TYPE = "sqlite";
68
- }
69
-
70
- let mysqlPromise = null;
71
- let pgPromise = null;
72
- let sqlitePromise = null;
73
-
74
- if (DB_TYPE === "postgres") {
75
- try {
76
- pgPromise = await import("pg");
77
- } catch (err) {
78
- console.error("[DATABASE ERROR] pg package is not installed. Database wrapper is disabled.");
79
- }
80
- } else if (DB_TYPE === "mysql") {
81
- try {
82
- mysqlPromise = await import("mysql2/promise");
83
- } catch (err) {
84
- console.error("[DATABASE ERROR] mysql2 package is not installed. Database wrapper is disabled.");
85
- }
86
- } else if (DB_TYPE === "sqlite") {
87
- try {
88
- const { DatabaseSync } = await import("node:sqlite");
89
- const testDb = new DatabaseSync(":memory:");
90
- testDb.close();
91
- sqlitePromise = { source: "node:sqlite", DatabaseSync };
92
- } catch {
93
- try {
94
- const mod = await import("better-sqlite3");
95
- sqlitePromise = { source: "better-sqlite3", BetterSqlite: mod.default || mod };
96
- } catch {
97
- console.error(
98
- "[DATABASE] No SQLite driver available. Node.js 22.18+ required for node:sqlite, or install better-sqlite3."
99
- );
100
- }
101
- }
102
- }
103
-
104
- /**
105
- * Replaces ? parameter placeholders with $1, $2, etc., ignoring quoted string literals.
106
- * @param {string} sql
107
- * @returns {string}
108
- */
109
- function toPostgresSql(sql) {
110
- let paramIndex = 1;
111
- let inSingleQuote = false;
112
- let inDoubleQuote = false;
113
- let result = "";
114
-
115
- for (let i = 0; i < sql.length; i++) {
116
- const char = sql[i];
117
- const prev = i > 0 ? sql[i - 1] : "";
118
-
119
- if (char === "'" && prev !== "\\" && !inDoubleQuote) {
120
- inSingleQuote = !inSingleQuote;
121
- result += char;
122
- } else if (char === '"' && prev !== "\\" && !inSingleQuote) {
123
- inDoubleQuote = !inDoubleQuote;
124
- result += char;
125
- } else if (char === "?" && !inSingleQuote && !inDoubleQuote) {
126
- result += `$${paramIndex++}`;
127
- } else {
128
- result += char;
129
- }
130
- }
131
-
132
- return result;
133
- }
134
-
135
- /**
136
- * Database class wrapping native node:sqlite, mysql2, and pg with pooling and multi-level caching.
137
- */
138
- class Database {
139
- /**
140
- * Initializes database connection parameters.
141
- * @param {number} [connectionLimit=10]
142
- * @param {number} [queueLimit=0]
143
- * @param {Object} [config={}]
144
- */
145
- constructor(connectionLimit = 10, queueLimit = 0, config = {}) {
146
- this.pool = null;
147
- this.db = null;
148
- this.type = config.DB_TYPE || DB_TYPE;
149
- this._stmtCache = new Map();
150
- this._maxStatements = 500;
151
-
152
- let defaultSqliteFile = process.env.DB_FILE || "database/blue_bird.db";
153
- let busyTimeout = 5000;
154
- let journalMode = "WAL";
155
- let synchronous = "NORMAL";
156
-
157
- if (process.env.DATABASE_URL && !process.env.DATABASE_URL.startsWith("#")) {
158
- try {
159
- if (
160
- process.env.DATABASE_URL.startsWith("sqlite://") ||
161
- process.env.DATABASE_URL.startsWith("sqlite:")
162
- ) {
163
- const rawUrl = process.env.DATABASE_URL;
164
- const cleanUrl = rawUrl.replace(/^sqlite:\/\/|^sqlite:/, "");
165
- const [filePath, queryStr] = cleanUrl.split("?");
166
- if (filePath) {
167
- defaultSqliteFile = filePath;
168
- }
169
- if (queryStr) {
170
- const params = new URLSearchParams(queryStr);
171
- if (params.has("busy_timeout")) {
172
- busyTimeout = parseInt(params.get("busy_timeout"), 10) || busyTimeout;
173
- }
174
- if (params.has("journal_mode")) {
175
- journalMode = params.get("journal_mode").toUpperCase();
176
- }
177
- if (params.has("synchronous")) {
178
- synchronous = params.get("synchronous").toUpperCase();
179
- }
180
- }
181
- }
182
- } catch (err) {
183
- console.error("[DATABASE ERROR] Failed to parse SQLite DATABASE_URL:", err.message);
184
- }
185
- }
186
-
187
- this.sqliteConfig = {
188
- filename: config.DB_FILE || defaultSqliteFile,
189
- busyTimeout: config.busyTimeout || busyTimeout,
190
- journalMode: config.journalMode || journalMode,
191
- synchronous: config.synchronous || synchronous,
192
- };
193
-
194
- this.config = {
195
- ...config,
196
- host: process.env.DB_HOST || "localhost",
197
- user: process.env.DB_USER || (this.type === "postgres" ? "postgres" : "root"),
198
- password: process.env.DB_PASSWORD || "root",
199
- database: process.env.DB_NAME || "blue_bird",
200
- port: parseInt(process.env.DB_PORT, 10) || (this.type === "postgres" ? 5432 : 3306),
201
- charset: "utf8mb4",
202
- waitForConnections: true,
203
- connectionLimit: connectionLimit,
204
- queueLimit: queueLimit,
205
- max: connectionLimit,
206
- };
207
-
208
- if (process.env.DATABASE_URL && !process.env.DATABASE_URL.startsWith("#")) {
209
- try {
210
- if (
211
- process.env.DATABASE_URL.startsWith("mysql://") ||
212
- process.env.DATABASE_URL.startsWith("postgres://") ||
213
- process.env.DATABASE_URL.startsWith("postgresql://")
214
- ) {
215
- const url = new URL(process.env.DATABASE_URL);
216
- this.config.host = url.hostname;
217
- this.config.port = parseInt(url.port, 10) || (this.type === "postgres" ? 5432 : 3306);
218
- this.config.user = url.username;
219
- this.config.password = url.password;
220
- this.config.database = url.pathname.substring(1);
221
- this.config.connectionString = process.env.DATABASE_URL;
222
- }
223
- } catch (err) {
224
- console.error("[DATABASE ERROR] Failed to parse DATABASE_URL:", err.message);
225
- }
226
- }
227
- }
228
-
229
- /**
230
- * Retrieves or creates a prepared statement with LRU caching.
231
- * @private
232
- * @param {string} sql
233
- * @returns {*} Prepared statement.
234
- */
235
- _getPreparedStatement(sql) {
236
- let stmt = this._stmtCache.get(sql);
237
- if (stmt) return stmt;
238
-
239
- stmt = this.db.prepare(sql);
240
- if (this._stmtCache.size >= this._maxStatements) {
241
- const oldestKey = this._stmtCache.keys().next().value;
242
- if (oldestKey !== undefined) this._stmtCache.delete(oldestKey);
243
- }
244
- this._stmtCache.set(sql, stmt);
245
- return stmt;
246
- }
247
-
248
- /**
249
- * Initializes connection pool or SQLite database.
250
- * @param {number} [retries=3]
251
- * @returns {Promise<boolean>}
252
- */
253
- async init(retries = 3) {
254
- if (!mysqlPromise && !pgPromise && !sqlitePromise) return false;
255
- if (this.pool || this.db) return true;
256
-
257
- if (this.type === "sqlite" && sqlitePromise) {
258
- try {
259
- const isMemoryDb = this.sqliteConfig.filename === ":memory:";
260
- const userDataBase = Config.userDataDir();
261
- const dbFilePath = isMemoryDb
262
- ? ":memory:"
263
- : path.isAbsolute(this.sqliteConfig.filename)
264
- ? this.sqliteConfig.filename
265
- : path.resolve(userDataBase, this.sqliteConfig.filename);
266
-
267
- if (!isMemoryDb) {
268
- const dir = path.dirname(dbFilePath);
269
- if (!fs.existsSync(dir)) {
270
- fs.mkdirSync(dir, { recursive: true });
271
- }
272
-
273
- if (userDataBase !== process.cwd() && !fs.existsSync(dbFilePath)) {
274
- const bundledDbPath = path.resolve(process.cwd(), this.sqliteConfig.filename);
275
- if (fs.existsSync(bundledDbPath)) {
276
- try {
277
- fs.copyFileSync(bundledDbPath, dbFilePath);
278
- } catch {}
279
- }
280
- }
281
- }
282
-
283
- if (sqlitePromise.source === "node:sqlite") {
284
- const { DatabaseSync } = sqlitePromise;
285
- this.db = new DatabaseSync(dbFilePath);
286
- this._sqliteDriver = "node:sqlite";
287
- this.db.exec(`PRAGMA journal_mode = ${this.sqliteConfig.journalMode};`);
288
- this.db.exec(`PRAGMA synchronous = ${this.sqliteConfig.synchronous};`);
289
- this.db.exec(`PRAGMA busy_timeout = ${this.sqliteConfig.busyTimeout};`);
290
- this.db.exec("PRAGMA foreign_keys = ON;");
291
- this.db.exec("PRAGMA temp_store = MEMORY;");
292
- this.db.exec("PRAGMA cache_size = -8000;");
293
- this.db.exec("PRAGMA mmap_size = 268435456;");
294
- } else {
295
- const { BetterSqlite } = sqlitePromise;
296
- this.db = new BetterSqlite(dbFilePath, { timeout: this.sqliteConfig.busyTimeout });
297
- this._sqliteDriver = "better-sqlite3";
298
- this.db.pragma(`journal_mode = ${this.sqliteConfig.journalMode}`);
299
- this.db.pragma(`synchronous = ${this.sqliteConfig.synchronous}`);
300
- this.db.pragma("foreign_keys = ON");
301
- this.db.pragma(`busy_timeout = ${this.sqliteConfig.busyTimeout}`);
302
- this.db.pragma("temp_store = MEMORY");
303
- this.db.pragma("cache_size = -8000");
304
- this.db.pragma("mmap_size = 268435456");
305
- }
306
-
307
- return true;
308
- } catch (err) {
309
- console.error("[DATABASE] Failed to initialize SQLite database:", err.message);
310
- this.db = null;
311
- return false;
312
- }
313
- }
314
-
315
- for (let attempt = 1; attempt <= retries; attempt++) {
316
- try {
317
- if (this.type === "postgres" && pgPromise) {
318
- const pg = pgPromise.default || pgPromise;
319
- this.pool = new pg.Pool(this.config);
320
- await this.pool.query("SELECT 1");
321
- } else if (mysqlPromise) {
322
- const { max, connectionString, ...mysqlConfig } = this.config;
323
- this.pool = mysqlPromise.createPool(mysqlConfig);
324
- await this.pool.query("SELECT 1");
325
- }
326
- return true;
327
- } catch (err) {
328
- this.pool = null;
329
- if (attempt === retries) {
330
- console.error(`[DATABASE ERROR] Connection failed after ${retries} attempts:`, err.message);
331
- return false;
332
- }
333
- await new Promise((resolve) => setTimeout(resolve, 1000));
334
- }
335
- }
336
- return false;
337
- }
338
-
339
- /**
340
- * Runs a SQL query with parameters and formatting options.
341
- * Accurately classifies CTEs (WITH ... SELECT) and RETURNING clauses.
342
- * Multi-level caching supports both in-memory and Redis backends.
343
- * @param {string} sql - SQL query string.
344
- * @param {Array} [params=[]] - Query parameter array.
345
- * @param {Object|string} [options={}] - Query options.
346
- * @returns {Promise<*>}
347
- */
348
- async query(sql, params = [], options = {}) {
349
- if (!mysqlPromise && !pgPromise && !sqlitePromise) return false;
350
- if (!this.pool && !this.db) {
351
- const initialized = await this.init();
352
- if (!initialized) return false;
353
- }
354
-
355
- const queryOptions = typeof options === "string" ? { [options]: true } : options;
356
- const cleanSql = sql.trim();
357
- const isSelect = /^\s*(select|pragma|explain|with)\b/i.test(cleanSql);
358
- const hasReturning = /\breturning\b/i.test(cleanSql);
359
- const isInsert = /^\s*insert\b/i.test(cleanSql);
360
-
361
- let cacheKey = null;
362
- const cacheTtl = queryOptions.cache ? parseInt(queryOptions.cache, 10) : 0;
363
- if (isSelect && cacheTtl > 0) {
364
- const hash = crypto
365
- .createHash("sha256")
366
- .update(cleanSql + JSON.stringify(params) + (queryOptions.return_row ? ":row" : ":all"))
367
- .digest("hex");
368
- const prefix = queryOptions.cachePrefix || "db:";
369
- cacheKey = `${prefix}${hash}`;
370
- const cached = await Cache.get(cacheKey);
371
- if (cached !== null) {
372
- return cached;
373
- }
374
- }
375
-
376
- try {
377
- if (this.type === "sqlite" && this.db) {
378
- const stmt = this._getPreparedStatement(cleanSql);
379
-
380
- if (isSelect || hasReturning) {
381
- if (queryOptions.return_row) {
382
- const row = stmt.get(...params);
383
- const result = row || null;
384
- if (cacheKey && cacheTtl > 0) {
385
- await Cache.set(cacheKey, result, cacheTtl);
386
- }
387
- return result;
388
- }
389
-
390
- const rows = stmt.all(...params);
391
- if (cacheKey && cacheTtl > 0) {
392
- await Cache.set(cacheKey, rows, cacheTtl);
393
- }
394
- return rows;
395
- }
396
-
397
- if (isInsert) {
398
- const info = stmt.run(...params);
399
- return Number(info.lastInsertRowid);
400
- }
401
-
402
- const info = stmt.run(...params);
403
- return info.changes;
404
- } else if (this.type === "postgres" && pgPromise) {
405
- const pgSql = toPostgresSql(cleanSql);
406
- const res = await this.pool.query(pgSql, params);
407
-
408
- if (isSelect || hasReturning) {
409
- const rows = res.rows || [];
410
- if (cacheKey && cacheTtl > 0) {
411
- await Cache.set(cacheKey, rows, cacheTtl);
412
- }
413
- if (queryOptions.return_row) {
414
- return rows.length > 0 ? rows[0] : null;
415
- }
416
- return rows;
417
- }
418
-
419
- if (isInsert) {
420
- if (res.rows && res.rows.length > 0) {
421
- return res.rows[0].id || res.rows[0];
422
- }
423
- return res.rowCount;
424
- }
425
-
426
- return res.rowCount;
427
- } else {
428
- const [results] = await this.pool.execute(cleanSql, params);
429
-
430
- if (isSelect || hasReturning) {
431
- const rows = Array.isArray(results) ? results : [];
432
- if (cacheKey && cacheTtl > 0) {
433
- await Cache.set(cacheKey, rows, cacheTtl);
434
- }
435
- if (queryOptions.return_row) {
436
- return rows.length > 0 ? rows[0] : null;
437
- }
438
- return rows;
439
- }
440
-
441
- if (isInsert) {
442
- return results.insertId || results;
443
- }
444
-
445
- return results;
446
- }
447
- } catch (err) {
448
- console.error("[DATABASE ERROR] Query execution failed:", err.message);
449
- throw err;
450
- }
451
- }
452
-
453
- /**
454
- * Executes a paginated SQL query.
455
- * @param {string} sql - SQL query string.
456
- * @param {Array} [params=[]] - Query parameters.
457
- * @param {Object} [options={}] - Pagination options: page, limit, cache.
458
- * @returns {Promise<{data: Array, total: number, page: number, limit: number, totalPages: number}>}
459
- */
460
- async paginate(sql, params = [], options = {}) {
461
- const page = Math.max(1, parseInt(options.page, 10) || 1);
462
- const limit = Math.max(1, parseInt(options.limit, 10) || 10);
463
- const offset = (page - 1) * limit;
464
-
465
- const cleanSql = sql.trim().replace(/;$/, "");
466
- const countSql = `SELECT COUNT(*) as total FROM (${cleanSql}) as _count_subquery`;
467
-
468
- const countResult = await this.query(countSql, params, { return_row: true });
469
- const total = Number(countResult?.total || countResult?.count || 0);
470
- const totalPages = Math.ceil(total / limit);
471
-
472
- const paginatedSql = `${cleanSql} LIMIT ${limit} OFFSET ${offset}`;
473
- const rows = await this.query(paginatedSql, params, options);
474
-
475
- return {
476
- data: Array.isArray(rows) ? rows : [],
477
- total,
478
- page,
479
- limit,
480
- totalPages,
481
- };
482
- }
483
-
484
- /**
485
- * Executes a database transaction with automatic commit and rollback.
486
- * @param {Function} callback - Async function receiving transaction client: async (tx) => { ... }
487
- * @returns {Promise<*>}
488
- */
489
- async transaction(callback) {
490
- if (!mysqlPromise && !pgPromise && !sqlitePromise) throw new Error("[DATABASE ERROR] No database driver available.");
491
- if (!this.pool && !this.db) {
492
- const initialized = await this.init();
493
- if (!initialized) throw new Error("[DATABASE ERROR] Failed to initialize database pool.");
494
- }
495
-
496
- if (this.type === "sqlite" && this.db) {
497
- this.db.exec("BEGIN IMMEDIATE");
498
- try {
499
- const tx = {
500
- query: async (sql, params = [], options = {}) => {
501
- const queryOptions = typeof options === "string" ? { [options]: true } : options;
502
- const cleanSql = sql.trim();
503
- const isSelect = /^\s*(select|pragma|explain|with)\b/i.test(cleanSql);
504
- const hasReturning = /\breturning\b/i.test(cleanSql);
505
- const isInsert = /^\s*insert\b/i.test(cleanSql);
506
-
507
- const stmt = this._getPreparedStatement(cleanSql);
508
- if (isSelect || hasReturning) {
509
- if (queryOptions.return_row) {
510
- const row = stmt.get(...params);
511
- return row || null;
512
- }
513
- return stmt.all(...params);
514
- }
515
- if (isInsert) {
516
- const info = stmt.run(...params);
517
- return Number(info.lastInsertRowid);
518
- }
519
- const info = stmt.run(...params);
520
- return info.changes;
521
- },
522
- };
523
-
524
- const result = await callback(tx);
525
- this.db.exec("COMMIT");
526
- return result;
527
- } catch (err) {
528
- this.db.exec("ROLLBACK");
529
- console.error("[DATABASE ERROR] Transaction rolled back:", err.message);
530
- throw err;
531
- }
532
- } else if (this.type === "postgres" && pgPromise) {
533
- const client = await this.pool.connect();
534
- try {
535
- await client.query("BEGIN");
536
-
537
- const tx = {
538
- query: async (sql, params = [], options = {}) => {
539
- const queryOptions = typeof options === "string" ? { [options]: true } : options;
540
- const cleanSql = sql.trim();
541
- const isSelect = /^\s*(select|pragma|explain|with)\b/i.test(cleanSql);
542
- const hasReturning = /\breturning\b/i.test(cleanSql);
543
- const isInsert = /^\s*insert\b/i.test(cleanSql);
544
-
545
- const pgSql = toPostgresSql(cleanSql);
546
- const res = await client.query(pgSql, params);
547
-
548
- if (isSelect || hasReturning) {
549
- const rows = res.rows || [];
550
- return queryOptions.return_row ? (rows[0] || null) : rows;
551
- }
552
- if (isInsert) {
553
- if (res.rows && res.rows.length > 0) return res.rows[0].id || res.rows[0];
554
- return res.rowCount;
555
- }
556
- return res.rowCount;
557
- },
558
- };
559
-
560
- const result = await callback(tx);
561
- await client.query("COMMIT");
562
- return result;
563
- } catch (err) {
564
- await client.query("ROLLBACK").catch(() => {});
565
- console.error("[DATABASE ERROR] Transaction rolled back:", err.message);
566
- throw err;
567
- } finally {
568
- client.release();
569
- }
570
- } else {
571
- const connection = await this.pool.getConnection();
572
- try {
573
- await connection.beginTransaction();
574
-
575
- const tx = {
576
- query: async (sql, params = [], options = {}) => {
577
- const queryOptions = typeof options === "string" ? { [options]: true } : options;
578
- const cleanSql = sql.trim();
579
- const isSelect = /^\s*(select|pragma|explain|with)\b/i.test(cleanSql);
580
- const hasReturning = /\breturning\b/i.test(cleanSql);
581
- const isInsert = /^\s*insert\b/i.test(cleanSql);
582
-
583
- const [results] = await connection.execute(cleanSql, params);
584
-
585
- if (isSelect || hasReturning) {
586
- const rows = Array.isArray(results) ? results : [];
587
- return queryOptions.return_row ? (rows[0] || null) : rows;
588
- }
589
- if (isInsert) {
590
- return results.insertId || results;
591
- }
592
- return results;
593
- },
594
- };
595
-
596
- const result = await callback(tx);
597
- await connection.commit();
598
- return result;
599
- } catch (err) {
600
- await connection.rollback().catch(() => {});
601
- console.error("[DATABASE ERROR] Transaction rolled back:", err.message);
602
- throw err;
603
- } finally {
604
- connection.release();
605
- }
606
- }
607
- }
608
-
609
- /**
610
- * Alias for transaction().
611
- * @param {Function} callback
612
- */
613
- async executeTransaction(callback) {
614
- return this.transaction(callback);
615
- }
616
-
617
- /**
618
- * Closes the database connection pool or SQLite instance.
619
- */
620
- async close() {
621
- this._stmtCache.clear();
622
- if (this.db) {
623
- this.db.close();
624
- this.db = null;
625
- }
626
- if (this.pool) {
627
- if (typeof this.pool.end === "function") {
628
- await this.pool.end();
629
- }
630
- this.pool = null;
631
- }
632
- }
633
- }
634
-
635
- export { Database, DB_TYPE };
636
- export default Database;
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import crypto from "node:crypto";
4
+ import Config from "./config.js";
5
+ import Cache from "./cache.js";
6
+
7
+ const rawDbType = (process.env.DB_TYPE || "").toLowerCase().trim();
8
+ let DB_TYPE = "";
9
+
10
+ if (
11
+ rawDbType === "sqlite" ||
12
+ rawDbType === "sqlite3" ||
13
+ rawDbType === "sql" ||
14
+ rawDbType === "better-sqlite3" ||
15
+ rawDbType === "better-sqlite" ||
16
+ rawDbType === "lite"
17
+ ) {
18
+ DB_TYPE = "sqlite";
19
+ } else if (
20
+ rawDbType === "postgres" ||
21
+ rawDbType === "postgresql" ||
22
+ rawDbType === "pg" ||
23
+ rawDbType === "psql" ||
24
+ rawDbType === "pgsql" ||
25
+ rawDbType === "postgre" ||
26
+ rawDbType === "postgr" ||
27
+ rawDbType === "psgr"
28
+ ) {
29
+ DB_TYPE = "postgres";
30
+ } else if (
31
+ rawDbType === "mysql" ||
32
+ rawDbType === "mariadb" ||
33
+ rawDbType === "maria" ||
34
+ rawDbType === "my"
35
+ ) {
36
+ DB_TYPE = "mysql";
37
+ } else if (
38
+ rawDbType === "none" ||
39
+ rawDbType === "no" ||
40
+ rawDbType === "false" ||
41
+ rawDbType === "null" ||
42
+ rawDbType === "0"
43
+ ) {
44
+ DB_TYPE = "none";
45
+ }
46
+
47
+ if (
48
+ !DB_TYPE &&
49
+ process.env.DATABASE_URL &&
50
+ !process.env.DATABASE_URL.startsWith("#")
51
+ ) {
52
+ if (
53
+ process.env.DATABASE_URL.startsWith("postgres://") ||
54
+ process.env.DATABASE_URL.startsWith("postgresql://")
55
+ ) {
56
+ DB_TYPE = "postgres";
57
+ } else if (process.env.DATABASE_URL.startsWith("mysql://")) {
58
+ DB_TYPE = "mysql";
59
+ } else if (
60
+ process.env.DATABASE_URL.startsWith("sqlite://") ||
61
+ process.env.DATABASE_URL.startsWith("sqlite:")
62
+ ) {
63
+ DB_TYPE = "sqlite";
64
+ }
65
+ }
66
+ if (!DB_TYPE) {
67
+ DB_TYPE = "sqlite";
68
+ }
69
+
70
+ let mysqlPromise = null;
71
+ let pgPromise = null;
72
+ let sqlitePromise = null;
73
+
74
+ if (DB_TYPE === "postgres") {
75
+ try {
76
+ pgPromise = await import("pg");
77
+ } catch (err) {
78
+ console.error("[DATABASE ERROR] pg package is not installed. Database wrapper is disabled.");
79
+ }
80
+ } else if (DB_TYPE === "mysql") {
81
+ try {
82
+ mysqlPromise = await import("mysql2/promise");
83
+ } catch (err) {
84
+ console.error("[DATABASE ERROR] mysql2 package is not installed. Database wrapper is disabled.");
85
+ }
86
+ } else if (DB_TYPE === "sqlite") {
87
+ try {
88
+ const { DatabaseSync } = await import("node:sqlite");
89
+ const testDb = new DatabaseSync(":memory:");
90
+ testDb.close();
91
+ sqlitePromise = { source: "node:sqlite", DatabaseSync };
92
+ } catch {
93
+ try {
94
+ const mod = await import("better-sqlite3");
95
+ sqlitePromise = { source: "better-sqlite3", BetterSqlite: mod.default || mod };
96
+ } catch {
97
+ console.error(
98
+ "[DATABASE] No SQLite driver available. Node.js 22.18+ required for node:sqlite, or install better-sqlite3."
99
+ );
100
+ }
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Replaces ? parameter placeholders with $1, $2, etc., ignoring quoted string literals.
106
+ * @param {string} sql
107
+ * @returns {string}
108
+ */
109
+ function toPostgresSql(sql) {
110
+ let paramIndex = 1;
111
+ let inSingleQuote = false;
112
+ let inDoubleQuote = false;
113
+ let result = "";
114
+
115
+ for (let i = 0; i < sql.length; i++) {
116
+ const char = sql[i];
117
+ const prev = i > 0 ? sql[i - 1] : "";
118
+
119
+ if (char === "'" && prev !== "\\" && !inDoubleQuote) {
120
+ inSingleQuote = !inSingleQuote;
121
+ result += char;
122
+ } else if (char === '"' && prev !== "\\" && !inSingleQuote) {
123
+ inDoubleQuote = !inDoubleQuote;
124
+ result += char;
125
+ } else if (char === "?" && !inSingleQuote && !inDoubleQuote) {
126
+ result += `$${paramIndex++}`;
127
+ } else {
128
+ result += char;
129
+ }
130
+ }
131
+
132
+ return result;
133
+ }
134
+
135
+ /**
136
+ * Database class wrapping native node:sqlite, mysql2, and pg with pooling and multi-level caching.
137
+ */
138
+ class Database {
139
+ /**
140
+ * Initializes database connection parameters.
141
+ * @param {number} [connectionLimit=10]
142
+ * @param {number} [queueLimit=0]
143
+ * @param {Object} [config={}]
144
+ */
145
+ constructor(connectionLimit = 10, queueLimit = 0, config = {}) {
146
+ this.pool = null;
147
+ this.db = null;
148
+ this.type = config.DB_TYPE || DB_TYPE;
149
+ this._stmtCache = new Map();
150
+ this._maxStatements = 500;
151
+
152
+ let defaultSqliteFile = process.env.DB_FILE || "database/blue_bird.db";
153
+ let busyTimeout = 5000;
154
+ let journalMode = "WAL";
155
+ let synchronous = "NORMAL";
156
+
157
+ if (process.env.DATABASE_URL && !process.env.DATABASE_URL.startsWith("#")) {
158
+ try {
159
+ if (
160
+ process.env.DATABASE_URL.startsWith("sqlite://") ||
161
+ process.env.DATABASE_URL.startsWith("sqlite:")
162
+ ) {
163
+ const rawUrl = process.env.DATABASE_URL;
164
+ const cleanUrl = rawUrl.replace(/^sqlite:\/\/|^sqlite:/, "");
165
+ const [filePath, queryStr] = cleanUrl.split("?");
166
+ if (filePath) {
167
+ defaultSqliteFile = filePath;
168
+ }
169
+ if (queryStr) {
170
+ const params = new URLSearchParams(queryStr);
171
+ if (params.has("busy_timeout")) {
172
+ busyTimeout = parseInt(params.get("busy_timeout"), 10) || busyTimeout;
173
+ }
174
+ if (params.has("journal_mode")) {
175
+ journalMode = params.get("journal_mode").toUpperCase();
176
+ }
177
+ if (params.has("synchronous")) {
178
+ synchronous = params.get("synchronous").toUpperCase();
179
+ }
180
+ }
181
+ }
182
+ } catch (err) {
183
+ console.error("[DATABASE ERROR] Failed to parse SQLite DATABASE_URL:", err.message);
184
+ }
185
+ }
186
+
187
+ this.sqliteConfig = {
188
+ filename: config.DB_FILE || defaultSqliteFile,
189
+ busyTimeout: config.busyTimeout || busyTimeout,
190
+ journalMode: config.journalMode || journalMode,
191
+ synchronous: config.synchronous || synchronous,
192
+ };
193
+
194
+ this.config = {
195
+ ...config,
196
+ host: process.env.DB_HOST || "localhost",
197
+ user: process.env.DB_USER || (this.type === "postgres" ? "postgres" : "root"),
198
+ password: process.env.DB_PASSWORD || "root",
199
+ database: process.env.DB_NAME || "blue_bird",
200
+ port: parseInt(process.env.DB_PORT, 10) || (this.type === "postgres" ? 5432 : 3306),
201
+ charset: "utf8mb4",
202
+ waitForConnections: true,
203
+ connectionLimit: connectionLimit,
204
+ queueLimit: queueLimit,
205
+ max: connectionLimit,
206
+ };
207
+
208
+ if (process.env.DATABASE_URL && !process.env.DATABASE_URL.startsWith("#")) {
209
+ try {
210
+ if (
211
+ process.env.DATABASE_URL.startsWith("mysql://") ||
212
+ process.env.DATABASE_URL.startsWith("postgres://") ||
213
+ process.env.DATABASE_URL.startsWith("postgresql://")
214
+ ) {
215
+ const url = new URL(process.env.DATABASE_URL);
216
+ this.config.host = url.hostname;
217
+ this.config.port = parseInt(url.port, 10) || (this.type === "postgres" ? 5432 : 3306);
218
+ this.config.user = url.username;
219
+ this.config.password = url.password;
220
+ this.config.database = url.pathname.substring(1);
221
+ this.config.connectionString = process.env.DATABASE_URL;
222
+ }
223
+ } catch (err) {
224
+ console.error("[DATABASE ERROR] Failed to parse DATABASE_URL:", err.message);
225
+ }
226
+ }
227
+ }
228
+
229
+ /**
230
+ * Retrieves or creates a prepared statement with LRU caching.
231
+ * @private
232
+ * @param {string} sql
233
+ * @returns {*} Prepared statement.
234
+ */
235
+ _getPreparedStatement(sql) {
236
+ let stmt = this._stmtCache.get(sql);
237
+ if (stmt) return stmt;
238
+
239
+ stmt = this.db.prepare(sql);
240
+ if (this._stmtCache.size >= this._maxStatements) {
241
+ const oldestKey = this._stmtCache.keys().next().value;
242
+ if (oldestKey !== undefined) this._stmtCache.delete(oldestKey);
243
+ }
244
+ this._stmtCache.set(sql, stmt);
245
+ return stmt;
246
+ }
247
+
248
+ /**
249
+ * Initializes connection pool or SQLite database.
250
+ * @param {number} [retries=3]
251
+ * @returns {Promise<boolean>}
252
+ */
253
+ async init(retries = 3) {
254
+ if (!mysqlPromise && !pgPromise && !sqlitePromise) return false;
255
+ if (this.pool || this.db) return true;
256
+
257
+ if (this.type === "sqlite" && sqlitePromise) {
258
+ try {
259
+ const isMemoryDb = this.sqliteConfig.filename === ":memory:";
260
+ const userDataBase = Config.userDataDir();
261
+ const dbFilePath = isMemoryDb
262
+ ? ":memory:"
263
+ : path.isAbsolute(this.sqliteConfig.filename)
264
+ ? this.sqliteConfig.filename
265
+ : path.resolve(userDataBase, this.sqliteConfig.filename);
266
+
267
+ if (!isMemoryDb) {
268
+ const dir = path.dirname(dbFilePath);
269
+ if (!fs.existsSync(dir)) {
270
+ fs.mkdirSync(dir, { recursive: true });
271
+ }
272
+
273
+ if (userDataBase !== process.cwd() && !fs.existsSync(dbFilePath)) {
274
+ const bundledDbPath = path.resolve(process.cwd(), this.sqliteConfig.filename);
275
+ if (fs.existsSync(bundledDbPath)) {
276
+ try {
277
+ fs.copyFileSync(bundledDbPath, dbFilePath);
278
+ } catch {}
279
+ }
280
+ }
281
+ }
282
+
283
+ if (sqlitePromise.source === "node:sqlite") {
284
+ const { DatabaseSync } = sqlitePromise;
285
+ this.db = new DatabaseSync(dbFilePath);
286
+ this._sqliteDriver = "node:sqlite";
287
+ this.db.exec(`PRAGMA journal_mode = ${this.sqliteConfig.journalMode};`);
288
+ this.db.exec(`PRAGMA synchronous = ${this.sqliteConfig.synchronous};`);
289
+ this.db.exec(`PRAGMA busy_timeout = ${this.sqliteConfig.busyTimeout};`);
290
+ this.db.exec("PRAGMA foreign_keys = ON;");
291
+ this.db.exec("PRAGMA temp_store = MEMORY;");
292
+ this.db.exec("PRAGMA cache_size = -8000;");
293
+ this.db.exec("PRAGMA mmap_size = 268435456;");
294
+ } else {
295
+ const { BetterSqlite } = sqlitePromise;
296
+ this.db = new BetterSqlite(dbFilePath, { timeout: this.sqliteConfig.busyTimeout });
297
+ this._sqliteDriver = "better-sqlite3";
298
+ this.db.pragma(`journal_mode = ${this.sqliteConfig.journalMode}`);
299
+ this.db.pragma(`synchronous = ${this.sqliteConfig.synchronous}`);
300
+ this.db.pragma("foreign_keys = ON");
301
+ this.db.pragma(`busy_timeout = ${this.sqliteConfig.busyTimeout}`);
302
+ this.db.pragma("temp_store = MEMORY");
303
+ this.db.pragma("cache_size = -8000");
304
+ this.db.pragma("mmap_size = 268435456");
305
+ }
306
+
307
+ return true;
308
+ } catch (err) {
309
+ console.error("[DATABASE] Failed to initialize SQLite database:", err.message);
310
+ this.db = null;
311
+ return false;
312
+ }
313
+ }
314
+
315
+ for (let attempt = 1; attempt <= retries; attempt++) {
316
+ try {
317
+ if (this.type === "postgres" && pgPromise) {
318
+ const pg = pgPromise.default || pgPromise;
319
+ this.pool = new pg.Pool(this.config);
320
+ await this.pool.query("SELECT 1");
321
+ } else if (mysqlPromise) {
322
+ const { max, connectionString, ...mysqlConfig } = this.config;
323
+ this.pool = mysqlPromise.createPool(mysqlConfig);
324
+ await this.pool.query("SELECT 1");
325
+ }
326
+ return true;
327
+ } catch (err) {
328
+ this.pool = null;
329
+ if (attempt === retries) {
330
+ console.error(`[DATABASE ERROR] Connection failed after ${retries} attempts:`, err.message);
331
+ return false;
332
+ }
333
+ await new Promise((resolve) => setTimeout(resolve, 1000));
334
+ }
335
+ }
336
+ return false;
337
+ }
338
+
339
+ /**
340
+ * Runs a SQL query with parameters and formatting options.
341
+ * Accurately classifies CTEs (WITH ... SELECT) and RETURNING clauses.
342
+ * Multi-level caching supports both in-memory and Redis backends.
343
+ * @param {string} sql - SQL query string.
344
+ * @param {Array} [params=[]] - Query parameter array.
345
+ * @param {Object|string} [options={}] - Query options.
346
+ * @returns {Promise<*>}
347
+ */
348
+ async query(sql, params = [], options = {}) {
349
+ if (!mysqlPromise && !pgPromise && !sqlitePromise) return false;
350
+ if (!this.pool && !this.db) {
351
+ const initialized = await this.init();
352
+ if (!initialized) return false;
353
+ }
354
+
355
+ const queryOptions = typeof options === "string" ? { [options]: true } : options;
356
+ const cleanSql = sql.trim();
357
+ const isSelect = /^\s*(select|pragma|explain|with)\b/i.test(cleanSql);
358
+ const hasReturning = /\breturning\b/i.test(cleanSql);
359
+ const isInsert = /^\s*insert\b/i.test(cleanSql);
360
+
361
+ let cacheKey = null;
362
+ const cacheTtl = queryOptions.cache ? parseInt(queryOptions.cache, 10) : 0;
363
+ if (isSelect && cacheTtl > 0) {
364
+ const hash = crypto
365
+ .createHash("sha256")
366
+ .update(cleanSql + JSON.stringify(params) + (queryOptions.return_row ? ":row" : ":all"))
367
+ .digest("hex");
368
+ const prefix = queryOptions.cachePrefix || "db:";
369
+ cacheKey = `${prefix}${hash}`;
370
+ const cached = await Cache.get(cacheKey);
371
+ if (cached !== null) {
372
+ return cached;
373
+ }
374
+ }
375
+
376
+ try {
377
+ if (this.type === "sqlite" && this.db) {
378
+ const stmt = this._getPreparedStatement(cleanSql);
379
+
380
+ if (isSelect || hasReturning) {
381
+ if (queryOptions.return_row) {
382
+ const row = stmt.get(...params);
383
+ const result = row || null;
384
+ if (cacheKey && cacheTtl > 0) {
385
+ await Cache.set(cacheKey, result, cacheTtl);
386
+ }
387
+ return result;
388
+ }
389
+
390
+ const rows = stmt.all(...params);
391
+ if (cacheKey && cacheTtl > 0) {
392
+ await Cache.set(cacheKey, rows, cacheTtl);
393
+ }
394
+ return rows;
395
+ }
396
+
397
+ if (isInsert) {
398
+ const info = stmt.run(...params);
399
+ return Number(info.lastInsertRowid);
400
+ }
401
+
402
+ const info = stmt.run(...params);
403
+ return info.changes;
404
+ } else if (this.type === "postgres" && pgPromise) {
405
+ const pgSql = toPostgresSql(cleanSql);
406
+ const res = await this.pool.query(pgSql, params);
407
+
408
+ if (isSelect || hasReturning) {
409
+ const rows = res.rows || [];
410
+ if (cacheKey && cacheTtl > 0) {
411
+ await Cache.set(cacheKey, rows, cacheTtl);
412
+ }
413
+ if (queryOptions.return_row) {
414
+ return rows.length > 0 ? rows[0] : null;
415
+ }
416
+ return rows;
417
+ }
418
+
419
+ if (isInsert) {
420
+ if (res.rows && res.rows.length > 0) {
421
+ return res.rows[0].id || res.rows[0];
422
+ }
423
+ return res.rowCount;
424
+ }
425
+
426
+ return res.rowCount;
427
+ } else {
428
+ const [results] = await this.pool.execute(cleanSql, params);
429
+
430
+ if (isSelect || hasReturning) {
431
+ const rows = Array.isArray(results) ? results : [];
432
+ if (cacheKey && cacheTtl > 0) {
433
+ await Cache.set(cacheKey, rows, cacheTtl);
434
+ }
435
+ if (queryOptions.return_row) {
436
+ return rows.length > 0 ? rows[0] : null;
437
+ }
438
+ return rows;
439
+ }
440
+
441
+ if (isInsert) {
442
+ return results.insertId || results;
443
+ }
444
+
445
+ return results;
446
+ }
447
+ } catch (err) {
448
+ console.error("[DATABASE ERROR] Query execution failed:", err.message);
449
+ throw err;
450
+ }
451
+ }
452
+
453
+ /**
454
+ * Executes a paginated SQL query.
455
+ * @param {string} sql - SQL query string.
456
+ * @param {Array} [params=[]] - Query parameters.
457
+ * @param {Object} [options={}] - Pagination options: page, limit, cache.
458
+ * @returns {Promise<{data: Array, total: number, page: number, limit: number, totalPages: number}>}
459
+ */
460
+ async paginate(sql, params = [], options = {}) {
461
+ const page = Math.max(1, parseInt(options.page, 10) || 1);
462
+ const limit = Math.max(1, parseInt(options.limit, 10) || 10);
463
+ const offset = (page - 1) * limit;
464
+
465
+ const cleanSql = sql.trim().replace(/;$/, "");
466
+ const countSql = `SELECT COUNT(*) as total FROM (${cleanSql}) as _count_subquery`;
467
+
468
+ const countResult = await this.query(countSql, params, { return_row: true });
469
+ const total = Number(countResult?.total || countResult?.count || 0);
470
+ const totalPages = Math.ceil(total / limit);
471
+
472
+ const paginatedSql = `${cleanSql} LIMIT ${limit} OFFSET ${offset}`;
473
+ const rows = await this.query(paginatedSql, params, options);
474
+
475
+ return {
476
+ data: Array.isArray(rows) ? rows : [],
477
+ total,
478
+ page,
479
+ limit,
480
+ totalPages,
481
+ };
482
+ }
483
+
484
+ /**
485
+ * Executes a database transaction with automatic commit and rollback.
486
+ * @param {Function} callback - Async function receiving transaction client: async (tx) => { ... }
487
+ * @returns {Promise<*>}
488
+ */
489
+ async transaction(callback) {
490
+ if (!mysqlPromise && !pgPromise && !sqlitePromise) throw new Error("[DATABASE ERROR] No database driver available.");
491
+ if (!this.pool && !this.db) {
492
+ const initialized = await this.init();
493
+ if (!initialized) throw new Error("[DATABASE ERROR] Failed to initialize database pool.");
494
+ }
495
+
496
+ if (this.type === "sqlite" && this.db) {
497
+ this.db.exec("BEGIN IMMEDIATE");
498
+ try {
499
+ const tx = {
500
+ query: async (sql, params = [], options = {}) => {
501
+ const queryOptions = typeof options === "string" ? { [options]: true } : options;
502
+ const cleanSql = sql.trim();
503
+ const isSelect = /^\s*(select|pragma|explain|with)\b/i.test(cleanSql);
504
+ const hasReturning = /\breturning\b/i.test(cleanSql);
505
+ const isInsert = /^\s*insert\b/i.test(cleanSql);
506
+
507
+ const stmt = this._getPreparedStatement(cleanSql);
508
+ if (isSelect || hasReturning) {
509
+ if (queryOptions.return_row) {
510
+ const row = stmt.get(...params);
511
+ return row || null;
512
+ }
513
+ return stmt.all(...params);
514
+ }
515
+ if (isInsert) {
516
+ const info = stmt.run(...params);
517
+ return Number(info.lastInsertRowid);
518
+ }
519
+ const info = stmt.run(...params);
520
+ return info.changes;
521
+ },
522
+ };
523
+
524
+ const result = await callback(tx);
525
+ this.db.exec("COMMIT");
526
+ return result;
527
+ } catch (err) {
528
+ this.db.exec("ROLLBACK");
529
+ console.error("[DATABASE ERROR] Transaction rolled back:", err.message);
530
+ throw err;
531
+ }
532
+ } else if (this.type === "postgres" && pgPromise) {
533
+ const client = await this.pool.connect();
534
+ try {
535
+ await client.query("BEGIN");
536
+
537
+ const tx = {
538
+ query: async (sql, params = [], options = {}) => {
539
+ const queryOptions = typeof options === "string" ? { [options]: true } : options;
540
+ const cleanSql = sql.trim();
541
+ const isSelect = /^\s*(select|pragma|explain|with)\b/i.test(cleanSql);
542
+ const hasReturning = /\breturning\b/i.test(cleanSql);
543
+ const isInsert = /^\s*insert\b/i.test(cleanSql);
544
+
545
+ const pgSql = toPostgresSql(cleanSql);
546
+ const res = await client.query(pgSql, params);
547
+
548
+ if (isSelect || hasReturning) {
549
+ const rows = res.rows || [];
550
+ return queryOptions.return_row ? (rows[0] || null) : rows;
551
+ }
552
+ if (isInsert) {
553
+ if (res.rows && res.rows.length > 0) return res.rows[0].id || res.rows[0];
554
+ return res.rowCount;
555
+ }
556
+ return res.rowCount;
557
+ },
558
+ };
559
+
560
+ const result = await callback(tx);
561
+ await client.query("COMMIT");
562
+ return result;
563
+ } catch (err) {
564
+ await client.query("ROLLBACK").catch(() => {});
565
+ console.error("[DATABASE ERROR] Transaction rolled back:", err.message);
566
+ throw err;
567
+ } finally {
568
+ client.release();
569
+ }
570
+ } else {
571
+ const connection = await this.pool.getConnection();
572
+ try {
573
+ await connection.beginTransaction();
574
+
575
+ const tx = {
576
+ query: async (sql, params = [], options = {}) => {
577
+ const queryOptions = typeof options === "string" ? { [options]: true } : options;
578
+ const cleanSql = sql.trim();
579
+ const isSelect = /^\s*(select|pragma|explain|with)\b/i.test(cleanSql);
580
+ const hasReturning = /\breturning\b/i.test(cleanSql);
581
+ const isInsert = /^\s*insert\b/i.test(cleanSql);
582
+
583
+ const [results] = await connection.execute(cleanSql, params);
584
+
585
+ if (isSelect || hasReturning) {
586
+ const rows = Array.isArray(results) ? results : [];
587
+ return queryOptions.return_row ? (rows[0] || null) : rows;
588
+ }
589
+ if (isInsert) {
590
+ return results.insertId || results;
591
+ }
592
+ return results;
593
+ },
594
+ };
595
+
596
+ const result = await callback(tx);
597
+ await connection.commit();
598
+ return result;
599
+ } catch (err) {
600
+ await connection.rollback().catch(() => {});
601
+ console.error("[DATABASE ERROR] Transaction rolled back:", err.message);
602
+ throw err;
603
+ } finally {
604
+ connection.release();
605
+ }
606
+ }
607
+ }
608
+
609
+ /**
610
+ * Alias for transaction().
611
+ * @param {Function} callback
612
+ */
613
+ async executeTransaction(callback) {
614
+ return this.transaction(callback);
615
+ }
616
+
617
+ /**
618
+ * Closes the database connection pool or SQLite instance.
619
+ */
620
+ async close() {
621
+ this._stmtCache.clear();
622
+ if (this.db) {
623
+ this.db.close();
624
+ this.db = null;
625
+ }
626
+ if (this.pool) {
627
+ if (typeof this.pool.end === "function") {
628
+ await this.pool.end();
629
+ }
630
+ this.pool = null;
631
+ }
632
+ }
633
+ }
634
+
635
+ export { Database, DB_TYPE };
636
+ export default Database;