@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/model.js CHANGED
@@ -1,600 +1,600 @@
1
- import Database from "./database.js";
2
- import Validator from "./validate.js";
3
- import Cache from "./cache.js";
4
- import Hash from "./hash.js";
5
-
6
- /**
7
- * Builds parameterized WHERE clauses from a condition object, validating column identifiers.
8
- * @param {Object} where
9
- * @returns {{whereClauses: string[], params: any[], whereSql: string}}
10
- */
11
- function buildWhere(where) {
12
- const whereClauses = [];
13
- const params = [];
14
-
15
- for (const [col, val] of Object.entries(where)) {
16
- if (!/^[a-zA-Z0-9_]+$/.test(col)) {
17
- throw new Error(`[MODEL ERROR] Invalid column identifier '${col}'`);
18
- }
19
- if (val === null) {
20
- whereClauses.push(`${col} IS NULL`);
21
- } else {
22
- whereClauses.push(`${col} = ?`);
23
- params.push(val);
24
- }
25
- }
26
-
27
- const whereSql = whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : "";
28
- return { whereClauses, params, whereSql };
29
- }
30
-
31
- /**
32
- * Validates and builds an ORDER BY clause from a string or array of expressions.
33
- * Prevents SQL injection in dynamic sort parameters.
34
- * @param {string|string[]} [order]
35
- * @returns {string}
36
- */
37
- function buildOrder(order) {
38
- if (!order) return "";
39
- const rawParts = Array.isArray(order) ? order : String(order).split(",");
40
- const safeParts = [];
41
-
42
- for (const part of rawParts) {
43
- const trimmed = String(part).trim();
44
- if (!trimmed) continue;
45
- if (!/^[a-zA-Z0-9_]+(\s+(ASC|DESC))?$/i.test(trimmed)) {
46
- throw new Error(`[MODEL ERROR] Invalid ORDER BY expression '${trimmed}'`);
47
- }
48
- safeParts.push(trimmed);
49
- }
50
-
51
- return safeParts.length > 0 ? `ORDER BY ${safeParts.join(", ")}` : "";
52
- }
53
-
54
- /**
55
- * Lightweight, zero-dependency BaseModel providing static schema definitions,
56
- * query shortcuts, smart relations, soft deletes, and validation bridges.
57
- * Designed for rapid application development and transparent database structure.
58
- * Note: For complex multi-tier enterprise ORM mapping, Prisma is recommended.
59
- */
60
- class Model {
61
- /** @type {string} */
62
- static table = "models";
63
-
64
- /** @type {string} */
65
- static primaryKey = "id";
66
-
67
- /** @type {boolean} */
68
- static timestamps = true;
69
-
70
- /** @type {boolean} */
71
- static softDelete = false;
72
-
73
- /** @type {Object<string, Object>} */
74
- static schema = {};
75
-
76
- /** @type {Database|null} */
77
- static _dbInstance = null;
78
-
79
- /**
80
- * Retrieves or initializes the shared Database instance for this model.
81
- * @returns {Database}
82
- */
83
- static getDatabase() {
84
- if (!this._dbInstance) {
85
- this._dbInstance = new Database();
86
- }
87
- return this._dbInstance;
88
- }
89
-
90
- /**
91
- * Sets a custom Database instance for this model.
92
- * @param {Database} db
93
- */
94
- static setDatabase(db) {
95
- this._dbInstance = db;
96
- }
97
-
98
- /**
99
- * Executes a direct SQL query through the model's database connection.
100
- * @param {string} sql - SQL query string.
101
- * @param {Array} [params=[]] - Query parameters.
102
- * @param {Object|string} [options={}] - Query options.
103
- * @returns {Promise<*>}
104
- */
105
- static async query(sql, params = [], options = {}) {
106
- return this.getDatabase().query(sql, params, options);
107
- }
108
-
109
- /**
110
- * Executes a database transaction through the model's connection.
111
- * @param {Function} callback - Async transaction callback: async (tx) => { ... }
112
- * @returns {Promise<*>}
113
- */
114
- static async transaction(callback) {
115
- return this.getDatabase().transaction(callback);
116
- }
117
-
118
- /**
119
- * Generates cache key for table versioning.
120
- * @returns {string}
121
- */
122
- static getVersionKey() {
123
- return `bb:m:${this.table}:v`;
124
- }
125
-
126
- /**
127
- * Invalidates cached queries associated with this model's table.
128
- * @returns {Promise<void>}
129
- */
130
- static async invalidateCache() {
131
- await Cache.deletePrefix(`db:${this.table}:`);
132
- await Cache.set(this.getVersionKey(), Date.now(), 86400);
133
- }
134
-
135
- /**
136
- * Filters out columns marked as hidden from record objects.
137
- * @param {Object} row
138
- * @param {boolean} [withHidden=false]
139
- * @returns {Object}
140
- */
141
- static filterHidden(row, withHidden = false) {
142
- if (!row || typeof row !== "object" || withHidden) return row;
143
- const clean = { ...row };
144
- for (const [col, config] of Object.entries(this.schema)) {
145
- if (config.hidden && col in clean) {
146
- delete clean[col];
147
- }
148
- }
149
- return clean;
150
- }
151
-
152
- /**
153
- * Resolves the foreign key linking another model to this table.
154
- * @param {typeof Model} targetModel
155
- * @returns {string}
156
- */
157
- static resolveForeignKey(targetModel) {
158
- for (const [col, def] of Object.entries(targetModel.schema)) {
159
- if (def.references === this.table || def.references === `${this.table}.${this.primaryKey}`) {
160
- return col;
161
- }
162
- }
163
-
164
- const singular = this.table.endsWith("s") ? this.table.slice(0, -1) : this.table;
165
- const candidates = [`${singular}_id`, `${this.table}_id`, `id_${singular}`, `id_${this.table}`];
166
-
167
- for (const c of candidates) {
168
- if (targetModel.schema[c]) {
169
- return c;
170
- }
171
- }
172
-
173
- return `${singular}_id`;
174
- }
175
-
176
- /**
177
- * Finds a single record by primary key or conditions object.
178
- * Supports smart relations lookup via oneMany and belongsTo options.
179
- * @param {number|string|Object} idOrConditions
180
- * @param {Object} [options={}]
181
- * @param {boolean} [options.withDeleted=false]
182
- * @param {boolean} [options.withHidden=false]
183
- * @param {number} [options.cache]
184
- * @param {typeof Model|Array<typeof Model>} [options.oneMany]
185
- * @param {typeof Model|Array<typeof Model>} [options.belongsTo]
186
- * @returns {Promise<Object|null>}
187
- */
188
- static async find(idOrConditions, options = {}) {
189
- const where = typeof idOrConditions === "object" && idOrConditions !== null
190
- ? { ...idOrConditions }
191
- : { [this.primaryKey]: idOrConditions };
192
-
193
- if (this.softDelete && !options.withDeleted && !("deleted_at" in where)) {
194
- where.deleted_at = null;
195
- }
196
-
197
- const { params, whereSql } = buildWhere(where);
198
- const sql = `SELECT * FROM ${this.table} ${whereSql} LIMIT 1`;
199
-
200
- const cacheTtl = options.cache;
201
- const dedupeKey = `find:${this.table}:${JSON.stringify(where)}`;
202
-
203
- const row = await Cache.deduplicate(dedupeKey, async () => {
204
- return this.getDatabase().query(sql, params, {
205
- return_row: true,
206
- cache: cacheTtl,
207
- cachePrefix: `db:${this.table}:`,
208
- });
209
- });
210
-
211
- if (!row) return null;
212
-
213
- let result = this.filterHidden(row, options.withHidden);
214
-
215
- if (options.oneMany) {
216
- const targets = Array.isArray(options.oneMany) ? options.oneMany : [options.oneMany];
217
- for (const target of targets) {
218
- const fk = this.resolveForeignKey(target);
219
- const related = await target.all({
220
- where: { [fk]: result[this.primaryKey] },
221
- withDeleted: options.withDeleted,
222
- withHidden: options.withHidden,
223
- });
224
- result[target.table] = related;
225
- }
226
- }
227
-
228
- if (options.belongsTo) {
229
- const parents = Array.isArray(options.belongsTo) ? options.belongsTo : [options.belongsTo];
230
- for (const parent of parents) {
231
- const fk = parent.resolveForeignKey(this);
232
- const parentId = result[fk];
233
- if (parentId !== undefined && parentId !== null) {
234
- const parentRow = await parent.find(parentId, {
235
- withDeleted: options.withDeleted,
236
- withHidden: options.withHidden,
237
- });
238
- const singularParent = parent.table.endsWith("s") ? parent.table.slice(0, -1) : parent.table;
239
- result[singularParent] = parentRow;
240
- }
241
- }
242
- }
243
-
244
- return result;
245
- }
246
-
247
- /**
248
- * Retrieves all records matching the given criteria.
249
- * @param {Object} [options={}]
250
- * @param {Object} [options.where={}]
251
- * @param {string|Array<string>} [options.order]
252
- * @param {number} [options.limit]
253
- * @param {number} [options.offset]
254
- * @param {boolean} [options.withDeleted=false]
255
- * @param {boolean} [options.withHidden=false]
256
- * @param {number} [options.cache]
257
- * @param {typeof Model|Array<typeof Model>} [options.oneMany]
258
- * @param {typeof Model|Array<typeof Model>} [options.belongsTo]
259
- * @returns {Promise<Array<Object>>}
260
- */
261
- static async all(options = {}) {
262
- const where = { ...(options.where || {}) };
263
- if (this.softDelete && !options.withDeleted && !("deleted_at" in where)) {
264
- where.deleted_at = null;
265
- }
266
-
267
- const { params, whereSql } = buildWhere(where);
268
- const orderSql = buildOrder(options.order);
269
-
270
- let limitSql = "";
271
- if (options.limit) {
272
- limitSql = `LIMIT ${parseInt(options.limit, 10)}`;
273
- if (options.offset) {
274
- limitSql += ` OFFSET ${parseInt(options.offset, 10)}`;
275
- }
276
- }
277
-
278
- const sql = `SELECT * FROM ${this.table} ${whereSql} ${orderSql} ${limitSql}`.trim();
279
- const rows =
280
- (await this.getDatabase().query(sql, params, {
281
- cache: options.cache,
282
- cachePrefix: `db:${this.table}:`,
283
- })) || [];
284
-
285
- const results = rows.map((r) => this.filterHidden(r, options.withHidden));
286
-
287
- if (options.oneMany || options.belongsTo) {
288
- for (const item of results) {
289
- if (options.oneMany) {
290
- const targets = Array.isArray(options.oneMany) ? options.oneMany : [options.oneMany];
291
- for (const target of targets) {
292
- const fk = this.resolveForeignKey(target);
293
- item[target.table] = await target.all({
294
- where: { [fk]: item[this.primaryKey] },
295
- withDeleted: options.withDeleted,
296
- withHidden: options.withHidden,
297
- });
298
- }
299
- }
300
- if (options.belongsTo) {
301
- const parents = Array.isArray(options.belongsTo) ? options.belongsTo : [options.belongsTo];
302
- for (const parent of parents) {
303
- const fk = parent.resolveForeignKey(this);
304
- const parentId = item[fk];
305
- if (parentId !== undefined && parentId !== null) {
306
- const singularParent = parent.table.endsWith("s") ? parent.table.slice(0, -1) : parent.table;
307
- item[singularParent] = await parent.find(parentId, {
308
- withDeleted: options.withDeleted,
309
- withHidden: options.withHidden,
310
- });
311
- }
312
- }
313
- }
314
- }
315
- }
316
-
317
- return results;
318
- }
319
-
320
- /**
321
- * Retrieves a paginated list of records.
322
- * @param {Object} [options={}]
323
- * @returns {Promise<{data: Array<Object>, total: number, page: number, limit: number, totalPages: number}>}
324
- */
325
- static async paginate(options = {}) {
326
- const page = Math.max(1, parseInt(options.page, 10) || 1);
327
- const limit = Math.max(1, parseInt(options.limit, 10) || 10);
328
- const where = { ...(options.where || {}) };
329
-
330
- if (this.softDelete && !options.withDeleted && !("deleted_at" in where)) {
331
- where.deleted_at = null;
332
- }
333
-
334
- const { params, whereSql } = buildWhere(where);
335
- const orderSql = buildOrder(options.order);
336
-
337
- const sql = `SELECT * FROM ${this.table} ${whereSql} ${orderSql}`.trim();
338
- const result = await this.getDatabase().paginate(sql, params, {
339
- page,
340
- limit,
341
- cache: options.cache,
342
- cachePrefix: `db:${this.table}:`,
343
- });
344
-
345
- result.data = result.data.map((r) => this.filterHidden(r, options.withHidden));
346
- return result;
347
- }
348
-
349
- /**
350
- * Inserts a new record, ignoring undeclared fields to prevent mass-assignment.
351
- * @param {Object} data
352
- * @returns {Promise<number|string>} Inserted record identifier.
353
- */
354
- static async create(data = {}) {
355
- const payload = {};
356
- const cols = [];
357
- const placeholders = [];
358
- const params = [];
359
-
360
- const now = new Date().toISOString();
361
-
362
- for (const [col, def] of Object.entries(this.schema)) {
363
- if (col === this.primaryKey && def.auto) continue;
364
-
365
- if (col in data) {
366
- let val = data[col];
367
- if (def.hash && typeof val === "string" && val.length > 0) {
368
- const isAlreadyHashed = val.startsWith("$scrypt$") || /^\$2[aby]\$\d{2}\$/.test(val);
369
- if (!isAlreadyHashed) {
370
- val = await Hash.make(val);
371
- }
372
- }
373
- payload[col] = val;
374
- } else if (def.default !== undefined) {
375
- payload[col] = typeof def.default === "function" ? def.default() : def.default;
376
- }
377
- }
378
-
379
- if (this.timestamps) {
380
- if (!("created_at" in payload)) payload.created_at = now;
381
- if (!("updated_at" in payload)) payload.updated_at = now;
382
- }
383
-
384
- for (const [col, val] of Object.entries(payload)) {
385
- cols.push(col);
386
- placeholders.push("?");
387
- params.push(val !== undefined ? val : null);
388
- }
389
-
390
- const db = this.getDatabase();
391
- const returningClause = db.type === "postgres" ? ` RETURNING ${this.primaryKey}` : "";
392
- const sql = `INSERT INTO ${this.table} (${cols.join(", ")}) VALUES (${placeholders.join(", ")})${returningClause}`;
393
- const insertRes = await db.query(sql, params, db.type === "postgres" ? { return_row: true } : {});
394
- const insertId =
395
- db.type === "postgres" && insertRes && typeof insertRes === "object"
396
- ? insertRes[this.primaryKey]
397
- : insertRes;
398
-
399
- await this.invalidateCache();
400
- return insertId;
401
- }
402
-
403
- /**
404
- * Updates an existing record by identifier or conditions.
405
- * @param {number|string|Object} idOrConditions
406
- * @param {Object} data
407
- * @returns {Promise<number>} Affected rows count.
408
- */
409
- static async update(idOrConditions, data = {}) {
410
- const where = typeof idOrConditions === "object" && idOrConditions !== null
411
- ? { ...idOrConditions }
412
- : { [this.primaryKey]: idOrConditions };
413
-
414
- const sets = [];
415
- const params = [];
416
-
417
- for (const [col, def] of Object.entries(this.schema)) {
418
- if (col === this.primaryKey) continue;
419
- if (col in data) {
420
- let val = data[col];
421
- if (def.hash && typeof val === "string" && val.length > 0) {
422
- const isAlreadyHashed = val.startsWith("$scrypt$") || /^\$2[aby]\$\d{2}\$/.test(val);
423
- if (!isAlreadyHashed) {
424
- val = await Hash.make(val);
425
- }
426
- }
427
- sets.push(`${col} = ?`);
428
- params.push(val);
429
- }
430
- }
431
-
432
- if (this.timestamps && !("updated_at" in data)) {
433
- sets.push("updated_at = ?");
434
- params.push(new Date().toISOString());
435
- }
436
-
437
- if (sets.length === 0) return 0;
438
-
439
- const { whereClauses, params: whereParams } = buildWhere(where);
440
- params.push(...whereParams);
441
-
442
- const sql = `UPDATE ${this.table} SET ${sets.join(", ")} WHERE ${whereClauses.join(" AND ")}`;
443
- const changes = await this.getDatabase().query(sql, params);
444
-
445
- await this.invalidateCache();
446
- return changes;
447
- }
448
-
449
- /**
450
- * Deletes one or more records with support for logical soft delete and cascading relations.
451
- * @param {number|string|Object} idOrConditions
452
- * @param {Object} [options={}]
453
- * @param {boolean} [options.force=false] - When true, forces physical DELETE even if softDelete is enabled.
454
- * @param {Array<typeof Model>} [options.cascade=[]] - Related models to cascade delete.
455
- * @returns {Promise<number>} Affected rows count.
456
- */
457
- static async delete(idOrConditions, options = {}) {
458
- const where = typeof idOrConditions === "object" && idOrConditions !== null
459
- ? { ...idOrConditions }
460
- : { [this.primaryKey]: idOrConditions };
461
-
462
- if (options.cascade && options.cascade.length > 0) {
463
- const records = await this.all({ where, withDeleted: true });
464
- for (const rec of records) {
465
- const id = rec[this.primaryKey];
466
- for (const childModel of options.cascade) {
467
- if (childModel !== this) {
468
- const fk = this.resolveForeignKey(childModel);
469
- await childModel.delete({ [fk]: id }, { force: options.force });
470
- }
471
- }
472
- }
473
- }
474
-
475
- const { whereClauses, params } = buildWhere(where);
476
-
477
- let sql = "";
478
- if (this.softDelete && !options.force) {
479
- const now = new Date().toISOString();
480
- sql = `UPDATE ${this.table} SET deleted_at = ? WHERE ${whereClauses.join(" AND ")}`;
481
- params.unshift(now);
482
- } else {
483
- sql = `DELETE FROM ${this.table} WHERE ${whereClauses.join(" AND ")}`;
484
- }
485
-
486
- const changes = await this.getDatabase().query(sql, params);
487
- await this.invalidateCache();
488
- return changes;
489
- }
490
-
491
- /**
492
- * Restores soft-deleted records by setting deleted_at to NULL.
493
- * @param {number|string|Object} idOrConditions
494
- * @returns {Promise<number>}
495
- */
496
- static async restore(idOrConditions) {
497
- if (!this.softDelete) return 0;
498
-
499
- const where = typeof idOrConditions === "object" && idOrConditions !== null
500
- ? { ...idOrConditions }
501
- : { [this.primaryKey]: idOrConditions };
502
-
503
- const { whereClauses, params } = buildWhere(where);
504
-
505
- const sql = `UPDATE ${this.table} SET deleted_at = NULL WHERE ${whereClauses.join(" AND ")}`;
506
- const changes = await this.getDatabase().query(sql, params);
507
-
508
- await this.invalidateCache();
509
- return changes;
510
- }
511
-
512
- /**
513
- * Generates a Blue Bird Validator instance based on the model's schema.
514
- * @param {"create"|"update"} [mode="create"]
515
- * @param {string} [lang="en"]
516
- * @returns {Validator}
517
- */
518
- static validator(mode = "create", lang = "en") {
519
- const rules = {};
520
-
521
- for (const [col, def] of Object.entries(this.schema)) {
522
- if (col === this.primaryKey && def.auto) continue;
523
- if (col === "created_at" || col === "updated_at" || col === "deleted_at") continue;
524
-
525
- const rule = { ...def };
526
- if (mode === "update") {
527
- rule.required = false;
528
- }
529
- rules[col] = rule;
530
- }
531
-
532
- return new Validator(rules, lang);
533
- }
534
-
535
- /**
536
- * Generates a SQL CREATE TABLE DDL string tailored to the target dialect.
537
- * @param {"sqlite"|"mysql"|"postgres"} [dialect="sqlite"]
538
- * @returns {string}
539
- */
540
- static toDDL(dialect = "sqlite") {
541
- const columns = [];
542
-
543
- for (const [col, def] of Object.entries(this.schema)) {
544
- const type = (def.type || "string").toLowerCase();
545
- let sqlCol = "";
546
-
547
- if (def.primary) {
548
- if (dialect === "postgres") {
549
- sqlCol = `${col} SERIAL PRIMARY KEY`;
550
- } else if (dialect === "mysql") {
551
- sqlCol = `${col} INT AUTO_INCREMENT PRIMARY KEY`;
552
- } else {
553
- sqlCol = `${col} INTEGER PRIMARY KEY AUTOINCREMENT`;
554
- }
555
- } else {
556
- let typeStr = "VARCHAR(255)";
557
- if (type === "int" || type === "integer") typeStr = dialect === "postgres" ? "INTEGER" : "INT";
558
- if (type === "bigint") typeStr = "BIGINT";
559
- if (type === "float" || type === "double" || type === "decimal") typeStr = "DECIMAL(10,2)";
560
- if (type === "text") typeStr = "TEXT";
561
- if (type === "boolean" || type === "bool") typeStr = dialect === "sqlite" ? "INTEGER" : "BOOLEAN";
562
- if (type === "date" || type === "datetime" || type === "timestamp") {
563
- typeStr = dialect === "mysql" ? "DATETIME" : "TIMESTAMP";
564
- }
565
- if (type === "json") typeStr = dialect === "postgres" ? "JSONB" : (dialect === "sqlite" ? "TEXT" : "JSON");
566
- if (type === "string") {
567
- typeStr = `VARCHAR(${def.length || 255})`;
568
- }
569
-
570
- sqlCol = `${col} ${typeStr}`;
571
- if (def.required && !def.nullable) sqlCol += " NOT NULL";
572
- if (def.unique) sqlCol += " UNIQUE";
573
- if (def.default !== undefined) {
574
- const defVal = typeof def.default === "string" ? `'${def.default}'` : def.default;
575
- sqlCol += ` DEFAULT ${defVal}`;
576
- }
577
- }
578
-
579
- columns.push(` ${sqlCol}`);
580
- }
581
-
582
- if (this.timestamps) {
583
- if (!this.schema.created_at) {
584
- columns.push(dialect === "mysql" ? " created_at DATETIME DEFAULT CURRENT_TIMESTAMP" : " created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP");
585
- }
586
- if (!this.schema.updated_at) {
587
- columns.push(dialect === "mysql" ? " updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP" : " updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP");
588
- }
589
- }
590
-
591
- if (this.softDelete && !this.schema.deleted_at) {
592
- columns.push(dialect === "mysql" ? " deleted_at DATETIME NULL" : " deleted_at TIMESTAMP NULL");
593
- }
594
-
595
- return `CREATE TABLE IF NOT EXISTS ${this.table} (\n${columns.join(",\n")}\n);`;
596
- }
597
- }
598
-
599
- export { Model };
600
- export default Model;
1
+ import Database from "./database.js";
2
+ import Validator from "./validate.js";
3
+ import Cache from "./cache.js";
4
+ import Hash from "./hash.js";
5
+
6
+ /**
7
+ * Builds parameterized WHERE clauses from a condition object, validating column identifiers.
8
+ * @param {Object} where
9
+ * @returns {{whereClauses: string[], params: any[], whereSql: string}}
10
+ */
11
+ function buildWhere(where) {
12
+ const whereClauses = [];
13
+ const params = [];
14
+
15
+ for (const [col, val] of Object.entries(where)) {
16
+ if (!/^[a-zA-Z0-9_]+$/.test(col)) {
17
+ throw new Error(`[MODEL ERROR] Invalid column identifier '${col}'`);
18
+ }
19
+ if (val === null) {
20
+ whereClauses.push(`${col} IS NULL`);
21
+ } else {
22
+ whereClauses.push(`${col} = ?`);
23
+ params.push(val);
24
+ }
25
+ }
26
+
27
+ const whereSql = whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : "";
28
+ return { whereClauses, params, whereSql };
29
+ }
30
+
31
+ /**
32
+ * Validates and builds an ORDER BY clause from a string or array of expressions.
33
+ * Prevents SQL injection in dynamic sort parameters.
34
+ * @param {string|string[]} [order]
35
+ * @returns {string}
36
+ */
37
+ function buildOrder(order) {
38
+ if (!order) return "";
39
+ const rawParts = Array.isArray(order) ? order : String(order).split(",");
40
+ const safeParts = [];
41
+
42
+ for (const part of rawParts) {
43
+ const trimmed = String(part).trim();
44
+ if (!trimmed) continue;
45
+ if (!/^[a-zA-Z0-9_]+(\s+(ASC|DESC))?$/i.test(trimmed)) {
46
+ throw new Error(`[MODEL ERROR] Invalid ORDER BY expression '${trimmed}'`);
47
+ }
48
+ safeParts.push(trimmed);
49
+ }
50
+
51
+ return safeParts.length > 0 ? `ORDER BY ${safeParts.join(", ")}` : "";
52
+ }
53
+
54
+ /**
55
+ * Lightweight, zero-dependency BaseModel providing static schema definitions,
56
+ * query shortcuts, smart relations, soft deletes, and validation bridges.
57
+ * Designed for rapid application development and transparent database structure.
58
+ * Note: For complex multi-tier enterprise ORM mapping, Prisma is recommended.
59
+ */
60
+ class Model {
61
+ /** @type {string} */
62
+ static table = "models";
63
+
64
+ /** @type {string} */
65
+ static primaryKey = "id";
66
+
67
+ /** @type {boolean} */
68
+ static timestamps = true;
69
+
70
+ /** @type {boolean} */
71
+ static softDelete = false;
72
+
73
+ /** @type {Object<string, Object>} */
74
+ static schema = {};
75
+
76
+ /** @type {Database|null} */
77
+ static _dbInstance = null;
78
+
79
+ /**
80
+ * Retrieves or initializes the shared Database instance for this model.
81
+ * @returns {Database}
82
+ */
83
+ static getDatabase() {
84
+ if (!this._dbInstance) {
85
+ this._dbInstance = new Database();
86
+ }
87
+ return this._dbInstance;
88
+ }
89
+
90
+ /**
91
+ * Sets a custom Database instance for this model.
92
+ * @param {Database} db
93
+ */
94
+ static setDatabase(db) {
95
+ this._dbInstance = db;
96
+ }
97
+
98
+ /**
99
+ * Executes a direct SQL query through the model's database connection.
100
+ * @param {string} sql - SQL query string.
101
+ * @param {Array} [params=[]] - Query parameters.
102
+ * @param {Object|string} [options={}] - Query options.
103
+ * @returns {Promise<*>}
104
+ */
105
+ static async query(sql, params = [], options = {}) {
106
+ return this.getDatabase().query(sql, params, options);
107
+ }
108
+
109
+ /**
110
+ * Executes a database transaction through the model's connection.
111
+ * @param {Function} callback - Async transaction callback: async (tx) => { ... }
112
+ * @returns {Promise<*>}
113
+ */
114
+ static async transaction(callback) {
115
+ return this.getDatabase().transaction(callback);
116
+ }
117
+
118
+ /**
119
+ * Generates cache key for table versioning.
120
+ * @returns {string}
121
+ */
122
+ static getVersionKey() {
123
+ return `bb:m:${this.table}:v`;
124
+ }
125
+
126
+ /**
127
+ * Invalidates cached queries associated with this model's table.
128
+ * @returns {Promise<void>}
129
+ */
130
+ static async invalidateCache() {
131
+ await Cache.deletePrefix(`db:${this.table}:`);
132
+ await Cache.set(this.getVersionKey(), Date.now(), 86400);
133
+ }
134
+
135
+ /**
136
+ * Filters out columns marked as hidden from record objects.
137
+ * @param {Object} row
138
+ * @param {boolean} [withHidden=false]
139
+ * @returns {Object}
140
+ */
141
+ static filterHidden(row, withHidden = false) {
142
+ if (!row || typeof row !== "object" || withHidden) return row;
143
+ const clean = { ...row };
144
+ for (const [col, config] of Object.entries(this.schema)) {
145
+ if (config.hidden && col in clean) {
146
+ delete clean[col];
147
+ }
148
+ }
149
+ return clean;
150
+ }
151
+
152
+ /**
153
+ * Resolves the foreign key linking another model to this table.
154
+ * @param {typeof Model} targetModel
155
+ * @returns {string}
156
+ */
157
+ static resolveForeignKey(targetModel) {
158
+ for (const [col, def] of Object.entries(targetModel.schema)) {
159
+ if (def.references === this.table || def.references === `${this.table}.${this.primaryKey}`) {
160
+ return col;
161
+ }
162
+ }
163
+
164
+ const singular = this.table.endsWith("s") ? this.table.slice(0, -1) : this.table;
165
+ const candidates = [`${singular}_id`, `${this.table}_id`, `id_${singular}`, `id_${this.table}`];
166
+
167
+ for (const c of candidates) {
168
+ if (targetModel.schema[c]) {
169
+ return c;
170
+ }
171
+ }
172
+
173
+ return `${singular}_id`;
174
+ }
175
+
176
+ /**
177
+ * Finds a single record by primary key or conditions object.
178
+ * Supports smart relations lookup via oneMany and belongsTo options.
179
+ * @param {number|string|Object} idOrConditions
180
+ * @param {Object} [options={}]
181
+ * @param {boolean} [options.withDeleted=false]
182
+ * @param {boolean} [options.withHidden=false]
183
+ * @param {number} [options.cache]
184
+ * @param {typeof Model|Array<typeof Model>} [options.oneMany]
185
+ * @param {typeof Model|Array<typeof Model>} [options.belongsTo]
186
+ * @returns {Promise<Object|null>}
187
+ */
188
+ static async find(idOrConditions, options = {}) {
189
+ const where = typeof idOrConditions === "object" && idOrConditions !== null
190
+ ? { ...idOrConditions }
191
+ : { [this.primaryKey]: idOrConditions };
192
+
193
+ if (this.softDelete && !options.withDeleted && !("deleted_at" in where)) {
194
+ where.deleted_at = null;
195
+ }
196
+
197
+ const { params, whereSql } = buildWhere(where);
198
+ const sql = `SELECT * FROM ${this.table} ${whereSql} LIMIT 1`;
199
+
200
+ const cacheTtl = options.cache;
201
+ const dedupeKey = `find:${this.table}:${JSON.stringify(where)}`;
202
+
203
+ const row = await Cache.deduplicate(dedupeKey, async () => {
204
+ return this.getDatabase().query(sql, params, {
205
+ return_row: true,
206
+ cache: cacheTtl,
207
+ cachePrefix: `db:${this.table}:`,
208
+ });
209
+ });
210
+
211
+ if (!row) return null;
212
+
213
+ let result = this.filterHidden(row, options.withHidden);
214
+
215
+ if (options.oneMany) {
216
+ const targets = Array.isArray(options.oneMany) ? options.oneMany : [options.oneMany];
217
+ for (const target of targets) {
218
+ const fk = this.resolveForeignKey(target);
219
+ const related = await target.all({
220
+ where: { [fk]: result[this.primaryKey] },
221
+ withDeleted: options.withDeleted,
222
+ withHidden: options.withHidden,
223
+ });
224
+ result[target.table] = related;
225
+ }
226
+ }
227
+
228
+ if (options.belongsTo) {
229
+ const parents = Array.isArray(options.belongsTo) ? options.belongsTo : [options.belongsTo];
230
+ for (const parent of parents) {
231
+ const fk = parent.resolveForeignKey(this);
232
+ const parentId = result[fk];
233
+ if (parentId !== undefined && parentId !== null) {
234
+ const parentRow = await parent.find(parentId, {
235
+ withDeleted: options.withDeleted,
236
+ withHidden: options.withHidden,
237
+ });
238
+ const singularParent = parent.table.endsWith("s") ? parent.table.slice(0, -1) : parent.table;
239
+ result[singularParent] = parentRow;
240
+ }
241
+ }
242
+ }
243
+
244
+ return result;
245
+ }
246
+
247
+ /**
248
+ * Retrieves all records matching the given criteria.
249
+ * @param {Object} [options={}]
250
+ * @param {Object} [options.where={}]
251
+ * @param {string|Array<string>} [options.order]
252
+ * @param {number} [options.limit]
253
+ * @param {number} [options.offset]
254
+ * @param {boolean} [options.withDeleted=false]
255
+ * @param {boolean} [options.withHidden=false]
256
+ * @param {number} [options.cache]
257
+ * @param {typeof Model|Array<typeof Model>} [options.oneMany]
258
+ * @param {typeof Model|Array<typeof Model>} [options.belongsTo]
259
+ * @returns {Promise<Array<Object>>}
260
+ */
261
+ static async all(options = {}) {
262
+ const where = { ...(options.where || {}) };
263
+ if (this.softDelete && !options.withDeleted && !("deleted_at" in where)) {
264
+ where.deleted_at = null;
265
+ }
266
+
267
+ const { params, whereSql } = buildWhere(where);
268
+ const orderSql = buildOrder(options.order);
269
+
270
+ let limitSql = "";
271
+ if (options.limit) {
272
+ limitSql = `LIMIT ${parseInt(options.limit, 10)}`;
273
+ if (options.offset) {
274
+ limitSql += ` OFFSET ${parseInt(options.offset, 10)}`;
275
+ }
276
+ }
277
+
278
+ const sql = `SELECT * FROM ${this.table} ${whereSql} ${orderSql} ${limitSql}`.trim();
279
+ const rows =
280
+ (await this.getDatabase().query(sql, params, {
281
+ cache: options.cache,
282
+ cachePrefix: `db:${this.table}:`,
283
+ })) || [];
284
+
285
+ const results = rows.map((r) => this.filterHidden(r, options.withHidden));
286
+
287
+ if (options.oneMany || options.belongsTo) {
288
+ for (const item of results) {
289
+ if (options.oneMany) {
290
+ const targets = Array.isArray(options.oneMany) ? options.oneMany : [options.oneMany];
291
+ for (const target of targets) {
292
+ const fk = this.resolveForeignKey(target);
293
+ item[target.table] = await target.all({
294
+ where: { [fk]: item[this.primaryKey] },
295
+ withDeleted: options.withDeleted,
296
+ withHidden: options.withHidden,
297
+ });
298
+ }
299
+ }
300
+ if (options.belongsTo) {
301
+ const parents = Array.isArray(options.belongsTo) ? options.belongsTo : [options.belongsTo];
302
+ for (const parent of parents) {
303
+ const fk = parent.resolveForeignKey(this);
304
+ const parentId = item[fk];
305
+ if (parentId !== undefined && parentId !== null) {
306
+ const singularParent = parent.table.endsWith("s") ? parent.table.slice(0, -1) : parent.table;
307
+ item[singularParent] = await parent.find(parentId, {
308
+ withDeleted: options.withDeleted,
309
+ withHidden: options.withHidden,
310
+ });
311
+ }
312
+ }
313
+ }
314
+ }
315
+ }
316
+
317
+ return results;
318
+ }
319
+
320
+ /**
321
+ * Retrieves a paginated list of records.
322
+ * @param {Object} [options={}]
323
+ * @returns {Promise<{data: Array<Object>, total: number, page: number, limit: number, totalPages: number}>}
324
+ */
325
+ static async paginate(options = {}) {
326
+ const page = Math.max(1, parseInt(options.page, 10) || 1);
327
+ const limit = Math.max(1, parseInt(options.limit, 10) || 10);
328
+ const where = { ...(options.where || {}) };
329
+
330
+ if (this.softDelete && !options.withDeleted && !("deleted_at" in where)) {
331
+ where.deleted_at = null;
332
+ }
333
+
334
+ const { params, whereSql } = buildWhere(where);
335
+ const orderSql = buildOrder(options.order);
336
+
337
+ const sql = `SELECT * FROM ${this.table} ${whereSql} ${orderSql}`.trim();
338
+ const result = await this.getDatabase().paginate(sql, params, {
339
+ page,
340
+ limit,
341
+ cache: options.cache,
342
+ cachePrefix: `db:${this.table}:`,
343
+ });
344
+
345
+ result.data = result.data.map((r) => this.filterHidden(r, options.withHidden));
346
+ return result;
347
+ }
348
+
349
+ /**
350
+ * Inserts a new record, ignoring undeclared fields to prevent mass-assignment.
351
+ * @param {Object} data
352
+ * @returns {Promise<number|string>} Inserted record identifier.
353
+ */
354
+ static async create(data = {}) {
355
+ const payload = {};
356
+ const cols = [];
357
+ const placeholders = [];
358
+ const params = [];
359
+
360
+ const now = new Date().toISOString();
361
+
362
+ for (const [col, def] of Object.entries(this.schema)) {
363
+ if (col === this.primaryKey && def.auto) continue;
364
+
365
+ if (col in data) {
366
+ let val = data[col];
367
+ if (def.hash && typeof val === "string" && val.length > 0) {
368
+ const isAlreadyHashed = val.startsWith("$scrypt$") || /^\$2[aby]\$\d{2}\$/.test(val);
369
+ if (!isAlreadyHashed) {
370
+ val = await Hash.make(val);
371
+ }
372
+ }
373
+ payload[col] = val;
374
+ } else if (def.default !== undefined) {
375
+ payload[col] = typeof def.default === "function" ? def.default() : def.default;
376
+ }
377
+ }
378
+
379
+ if (this.timestamps) {
380
+ if (!("created_at" in payload)) payload.created_at = now;
381
+ if (!("updated_at" in payload)) payload.updated_at = now;
382
+ }
383
+
384
+ for (const [col, val] of Object.entries(payload)) {
385
+ cols.push(col);
386
+ placeholders.push("?");
387
+ params.push(val !== undefined ? val : null);
388
+ }
389
+
390
+ const db = this.getDatabase();
391
+ const returningClause = db.type === "postgres" ? ` RETURNING ${this.primaryKey}` : "";
392
+ const sql = `INSERT INTO ${this.table} (${cols.join(", ")}) VALUES (${placeholders.join(", ")})${returningClause}`;
393
+ const insertRes = await db.query(sql, params, db.type === "postgres" ? { return_row: true } : {});
394
+ const insertId =
395
+ db.type === "postgres" && insertRes && typeof insertRes === "object"
396
+ ? insertRes[this.primaryKey]
397
+ : insertRes;
398
+
399
+ await this.invalidateCache();
400
+ return insertId;
401
+ }
402
+
403
+ /**
404
+ * Updates an existing record by identifier or conditions.
405
+ * @param {number|string|Object} idOrConditions
406
+ * @param {Object} data
407
+ * @returns {Promise<number>} Affected rows count.
408
+ */
409
+ static async update(idOrConditions, data = {}) {
410
+ const where = typeof idOrConditions === "object" && idOrConditions !== null
411
+ ? { ...idOrConditions }
412
+ : { [this.primaryKey]: idOrConditions };
413
+
414
+ const sets = [];
415
+ const params = [];
416
+
417
+ for (const [col, def] of Object.entries(this.schema)) {
418
+ if (col === this.primaryKey) continue;
419
+ if (col in data) {
420
+ let val = data[col];
421
+ if (def.hash && typeof val === "string" && val.length > 0) {
422
+ const isAlreadyHashed = val.startsWith("$scrypt$") || /^\$2[aby]\$\d{2}\$/.test(val);
423
+ if (!isAlreadyHashed) {
424
+ val = await Hash.make(val);
425
+ }
426
+ }
427
+ sets.push(`${col} = ?`);
428
+ params.push(val);
429
+ }
430
+ }
431
+
432
+ if (this.timestamps && !("updated_at" in data)) {
433
+ sets.push("updated_at = ?");
434
+ params.push(new Date().toISOString());
435
+ }
436
+
437
+ if (sets.length === 0) return 0;
438
+
439
+ const { whereClauses, params: whereParams } = buildWhere(where);
440
+ params.push(...whereParams);
441
+
442
+ const sql = `UPDATE ${this.table} SET ${sets.join(", ")} WHERE ${whereClauses.join(" AND ")}`;
443
+ const changes = await this.getDatabase().query(sql, params);
444
+
445
+ await this.invalidateCache();
446
+ return changes;
447
+ }
448
+
449
+ /**
450
+ * Deletes one or more records with support for logical soft delete and cascading relations.
451
+ * @param {number|string|Object} idOrConditions
452
+ * @param {Object} [options={}]
453
+ * @param {boolean} [options.force=false] - When true, forces physical DELETE even if softDelete is enabled.
454
+ * @param {Array<typeof Model>} [options.cascade=[]] - Related models to cascade delete.
455
+ * @returns {Promise<number>} Affected rows count.
456
+ */
457
+ static async delete(idOrConditions, options = {}) {
458
+ const where = typeof idOrConditions === "object" && idOrConditions !== null
459
+ ? { ...idOrConditions }
460
+ : { [this.primaryKey]: idOrConditions };
461
+
462
+ if (options.cascade && options.cascade.length > 0) {
463
+ const records = await this.all({ where, withDeleted: true });
464
+ for (const rec of records) {
465
+ const id = rec[this.primaryKey];
466
+ for (const childModel of options.cascade) {
467
+ if (childModel !== this) {
468
+ const fk = this.resolveForeignKey(childModel);
469
+ await childModel.delete({ [fk]: id }, { force: options.force });
470
+ }
471
+ }
472
+ }
473
+ }
474
+
475
+ const { whereClauses, params } = buildWhere(where);
476
+
477
+ let sql = "";
478
+ if (this.softDelete && !options.force) {
479
+ const now = new Date().toISOString();
480
+ sql = `UPDATE ${this.table} SET deleted_at = ? WHERE ${whereClauses.join(" AND ")}`;
481
+ params.unshift(now);
482
+ } else {
483
+ sql = `DELETE FROM ${this.table} WHERE ${whereClauses.join(" AND ")}`;
484
+ }
485
+
486
+ const changes = await this.getDatabase().query(sql, params);
487
+ await this.invalidateCache();
488
+ return changes;
489
+ }
490
+
491
+ /**
492
+ * Restores soft-deleted records by setting deleted_at to NULL.
493
+ * @param {number|string|Object} idOrConditions
494
+ * @returns {Promise<number>}
495
+ */
496
+ static async restore(idOrConditions) {
497
+ if (!this.softDelete) return 0;
498
+
499
+ const where = typeof idOrConditions === "object" && idOrConditions !== null
500
+ ? { ...idOrConditions }
501
+ : { [this.primaryKey]: idOrConditions };
502
+
503
+ const { whereClauses, params } = buildWhere(where);
504
+
505
+ const sql = `UPDATE ${this.table} SET deleted_at = NULL WHERE ${whereClauses.join(" AND ")}`;
506
+ const changes = await this.getDatabase().query(sql, params);
507
+
508
+ await this.invalidateCache();
509
+ return changes;
510
+ }
511
+
512
+ /**
513
+ * Generates a Blue Bird Validator instance based on the model's schema.
514
+ * @param {"create"|"update"} [mode="create"]
515
+ * @param {string} [lang="en"]
516
+ * @returns {Validator}
517
+ */
518
+ static validator(mode = "create", lang = "en") {
519
+ const rules = {};
520
+
521
+ for (const [col, def] of Object.entries(this.schema)) {
522
+ if (col === this.primaryKey && def.auto) continue;
523
+ if (col === "created_at" || col === "updated_at" || col === "deleted_at") continue;
524
+
525
+ const rule = { ...def };
526
+ if (mode === "update") {
527
+ rule.required = false;
528
+ }
529
+ rules[col] = rule;
530
+ }
531
+
532
+ return new Validator(rules, lang);
533
+ }
534
+
535
+ /**
536
+ * Generates a SQL CREATE TABLE DDL string tailored to the target dialect.
537
+ * @param {"sqlite"|"mysql"|"postgres"} [dialect="sqlite"]
538
+ * @returns {string}
539
+ */
540
+ static toDDL(dialect = "sqlite") {
541
+ const columns = [];
542
+
543
+ for (const [col, def] of Object.entries(this.schema)) {
544
+ const type = (def.type || "string").toLowerCase();
545
+ let sqlCol = "";
546
+
547
+ if (def.primary) {
548
+ if (dialect === "postgres") {
549
+ sqlCol = `${col} SERIAL PRIMARY KEY`;
550
+ } else if (dialect === "mysql") {
551
+ sqlCol = `${col} INT AUTO_INCREMENT PRIMARY KEY`;
552
+ } else {
553
+ sqlCol = `${col} INTEGER PRIMARY KEY AUTOINCREMENT`;
554
+ }
555
+ } else {
556
+ let typeStr = "VARCHAR(255)";
557
+ if (type === "int" || type === "integer") typeStr = dialect === "postgres" ? "INTEGER" : "INT";
558
+ if (type === "bigint") typeStr = "BIGINT";
559
+ if (type === "float" || type === "double" || type === "decimal") typeStr = "DECIMAL(10,2)";
560
+ if (type === "text") typeStr = "TEXT";
561
+ if (type === "boolean" || type === "bool") typeStr = dialect === "sqlite" ? "INTEGER" : "BOOLEAN";
562
+ if (type === "date" || type === "datetime" || type === "timestamp") {
563
+ typeStr = dialect === "mysql" ? "DATETIME" : "TIMESTAMP";
564
+ }
565
+ if (type === "json") typeStr = dialect === "postgres" ? "JSONB" : (dialect === "sqlite" ? "TEXT" : "JSON");
566
+ if (type === "string") {
567
+ typeStr = `VARCHAR(${def.length || 255})`;
568
+ }
569
+
570
+ sqlCol = `${col} ${typeStr}`;
571
+ if (def.required && !def.nullable) sqlCol += " NOT NULL";
572
+ if (def.unique) sqlCol += " UNIQUE";
573
+ if (def.default !== undefined) {
574
+ const defVal = typeof def.default === "string" ? `'${def.default}'` : def.default;
575
+ sqlCol += ` DEFAULT ${defVal}`;
576
+ }
577
+ }
578
+
579
+ columns.push(` ${sqlCol}`);
580
+ }
581
+
582
+ if (this.timestamps) {
583
+ if (!this.schema.created_at) {
584
+ columns.push(dialect === "mysql" ? " created_at DATETIME DEFAULT CURRENT_TIMESTAMP" : " created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP");
585
+ }
586
+ if (!this.schema.updated_at) {
587
+ columns.push(dialect === "mysql" ? " updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP" : " updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP");
588
+ }
589
+ }
590
+
591
+ if (this.softDelete && !this.schema.deleted_at) {
592
+ columns.push(dialect === "mysql" ? " deleted_at DATETIME NULL" : " deleted_at TIMESTAMP NULL");
593
+ }
594
+
595
+ return `CREATE TABLE IF NOT EXISTS ${this.table} (\n${columns.join(",\n")}\n);`;
596
+ }
597
+ }
598
+
599
+ export { Model };
600
+ export default Model;