@zero-server/sdk 0.9.1 → 0.9.3

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 (128) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +460 -443
  3. package/index.js +414 -412
  4. package/lib/app.js +1172 -1172
  5. package/lib/auth/authorize.js +399 -399
  6. package/lib/auth/enrollment.js +367 -367
  7. package/lib/auth/index.js +57 -57
  8. package/lib/auth/jwt.js +731 -731
  9. package/lib/auth/oauth.js +362 -362
  10. package/lib/auth/session.js +588 -588
  11. package/lib/auth/trustedDevice.js +409 -409
  12. package/lib/auth/twoFactor.js +1150 -1150
  13. package/lib/auth/webauthn.js +946 -946
  14. package/lib/body/index.js +14 -14
  15. package/lib/body/json.js +109 -109
  16. package/lib/body/multipart.js +440 -440
  17. package/lib/body/raw.js +71 -71
  18. package/lib/body/rawBuffer.js +160 -160
  19. package/lib/body/sendError.js +25 -25
  20. package/lib/body/text.js +75 -75
  21. package/lib/body/typeMatch.js +41 -41
  22. package/lib/body/urlencoded.js +235 -235
  23. package/lib/cli.js +845 -845
  24. package/lib/cluster.js +666 -666
  25. package/lib/debug.js +372 -372
  26. package/lib/env/index.js +465 -465
  27. package/lib/errors.js +683 -683
  28. package/lib/fetch/index.js +256 -256
  29. package/lib/grpc/balancer.js +378 -378
  30. package/lib/grpc/call.js +708 -708
  31. package/lib/grpc/client.js +764 -764
  32. package/lib/grpc/codec.js +1221 -1221
  33. package/lib/grpc/credentials.js +398 -398
  34. package/lib/grpc/frame.js +262 -262
  35. package/lib/grpc/health.js +287 -287
  36. package/lib/grpc/index.js +121 -121
  37. package/lib/grpc/metadata.js +461 -461
  38. package/lib/grpc/proto.js +821 -821
  39. package/lib/grpc/reflection.js +590 -590
  40. package/lib/grpc/server.js +445 -445
  41. package/lib/grpc/status.js +118 -118
  42. package/lib/grpc/watch.js +173 -173
  43. package/lib/http/index.js +10 -10
  44. package/lib/http/request.js +727 -727
  45. package/lib/http/response.js +799 -799
  46. package/lib/lifecycle.js +557 -557
  47. package/lib/middleware/compress.js +230 -230
  48. package/lib/middleware/cookieParser.js +237 -237
  49. package/lib/middleware/cors.js +93 -93
  50. package/lib/middleware/csrf.js +137 -137
  51. package/lib/middleware/errorHandler.js +101 -101
  52. package/lib/middleware/helmet.js +175 -175
  53. package/lib/middleware/index.js +19 -17
  54. package/lib/middleware/logger.js +74 -74
  55. package/lib/middleware/rateLimit.js +88 -88
  56. package/lib/middleware/requestId.js +53 -53
  57. package/lib/middleware/static.js +326 -326
  58. package/lib/middleware/timeout.js +71 -71
  59. package/lib/middleware/validator.js +255 -255
  60. package/lib/observe/health.js +326 -326
  61. package/lib/observe/index.js +50 -50
  62. package/lib/observe/logger.js +359 -359
  63. package/lib/observe/metrics.js +805 -805
  64. package/lib/observe/tracing.js +592 -592
  65. package/lib/orm/adapters/json.js +290 -290
  66. package/lib/orm/adapters/memory.js +764 -764
  67. package/lib/orm/adapters/mongo.js +764 -764
  68. package/lib/orm/adapters/mysql.js +933 -933
  69. package/lib/orm/adapters/postgres.js +1144 -1144
  70. package/lib/orm/adapters/redis.js +1534 -1534
  71. package/lib/orm/adapters/sql-base.js +212 -212
  72. package/lib/orm/adapters/sqlite.js +858 -858
  73. package/lib/orm/audit.js +649 -649
  74. package/lib/orm/cache.js +394 -394
  75. package/lib/orm/geo.js +387 -387
  76. package/lib/orm/index.js +784 -784
  77. package/lib/orm/migrate.js +432 -432
  78. package/lib/orm/model.js +1706 -1706
  79. package/lib/orm/plugin.js +375 -375
  80. package/lib/orm/procedures.js +836 -836
  81. package/lib/orm/profiler.js +233 -233
  82. package/lib/orm/query.js +1772 -1772
  83. package/lib/orm/replicas.js +241 -241
  84. package/lib/orm/schema.js +307 -307
  85. package/lib/orm/search.js +380 -380
  86. package/lib/orm/seed/data/commerce.js +136 -136
  87. package/lib/orm/seed/data/internet.js +111 -111
  88. package/lib/orm/seed/data/locations.js +204 -204
  89. package/lib/orm/seed/data/names.js +338 -338
  90. package/lib/orm/seed/data/person.js +128 -128
  91. package/lib/orm/seed/data/phone.js +211 -211
  92. package/lib/orm/seed/data/words.js +134 -134
  93. package/lib/orm/seed/factory.js +178 -178
  94. package/lib/orm/seed/fake.js +1186 -1186
  95. package/lib/orm/seed/index.js +18 -18
  96. package/lib/orm/seed/rng.js +70 -70
  97. package/lib/orm/seed/seeder.js +124 -124
  98. package/lib/orm/seed/unique.js +68 -68
  99. package/lib/orm/snapshot.js +366 -366
  100. package/lib/orm/tenancy.js +605 -605
  101. package/lib/orm/views.js +350 -350
  102. package/lib/router/index.js +436 -436
  103. package/lib/sse/index.js +8 -8
  104. package/lib/sse/stream.js +349 -349
  105. package/lib/ws/connection.js +451 -451
  106. package/lib/ws/handshake.js +125 -125
  107. package/lib/ws/index.js +14 -14
  108. package/lib/ws/room.js +223 -223
  109. package/package.json +73 -73
  110. package/types/app.d.ts +223 -223
  111. package/types/auth.d.ts +520 -520
  112. package/types/body.d.ts +14 -0
  113. package/types/cli.d.ts +2 -0
  114. package/types/cluster.d.ts +75 -75
  115. package/types/env.d.ts +80 -80
  116. package/types/errors.d.ts +316 -316
  117. package/types/fetch.d.ts +43 -43
  118. package/types/grpc.d.ts +432 -432
  119. package/types/index.d.ts +384 -384
  120. package/types/lifecycle.d.ts +60 -60
  121. package/types/middleware.d.ts +320 -320
  122. package/types/observe.d.ts +304 -304
  123. package/types/orm.d.ts +1887 -1887
  124. package/types/request.d.ts +109 -109
  125. package/types/response.d.ts +157 -157
  126. package/types/router.d.ts +78 -78
  127. package/types/sse.d.ts +78 -78
  128. package/types/websocket.d.ts +126 -126
@@ -1,764 +1,764 @@
1
- /**
2
- * @module orm/adapters/memory
3
- * @description In-memory database adapter.
4
- * Zero-dependency, perfect for testing, prototyping, and
5
- * applications that don't need persistence beyond the process lifecycle.
6
- *
7
- * All data is stored in plain JavaScript Maps and arrays.
8
- * Supports full CRUD, filtering, ordering, pagination, and counting.
9
- *
10
- * @example
11
- * const { Database, Model, TYPES } = require('@zero-server/sdk');
12
- *
13
- * const db = Database.connect('memory');
14
- *
15
- * class Task extends Model {
16
- * static table = 'tasks';
17
- * static schema = {
18
- * id: { type: TYPES.INTEGER, primaryKey: true, autoIncrement: true },
19
- * title: { type: TYPES.STRING, required: true },
20
- * done: { type: TYPES.BOOLEAN, default: false },
21
- * };
22
- * }
23
- *
24
- * db.register(Task);
25
- * await db.sync();
26
- *
27
- * await Task.create({ title: 'Write tests' });
28
- * const pending = await Task.find({ done: false });
29
- */
30
-
31
- /**
32
- * ReDoS-safe SQL LIKE matcher using iterative DP.
33
- * % = any sequence of chars, _ = any single char. Case-insensitive.
34
- * @private
35
- */
36
- function _likeSafe(str, pattern)
37
- {
38
- const s = str.toLowerCase();
39
- const p = pattern.toLowerCase();
40
- const sLen = s.length, pLen = p.length;
41
- let dp = new Array(pLen + 1).fill(false);
42
- dp[0] = true;
43
- for (let j = 0; j < pLen; j++) { if (p[j] === '%') dp[j + 1] = dp[j]; }
44
- for (let i = 1; i <= sLen; i++)
45
- {
46
- const next = new Array(pLen + 1).fill(false);
47
- for (let j = 1; j <= pLen; j++)
48
- {
49
- if (p[j - 1] === '%') next[j] = dp[j] || next[j - 1];
50
- else if (p[j - 1] === '_') next[j] = dp[j - 1];
51
- else next[j] = dp[j - 1] && s[i - 1] === p[j - 1];
52
- }
53
- dp = next;
54
- }
55
- return dp[pLen];
56
- }
57
-
58
- class MemoryAdapter
59
- {
60
- /** @constructor */
61
- constructor()
62
- {
63
- /** @private */ this._tables = new Map();
64
- /** @private */ this._autoIncrements = new Map();
65
- /** @private */ this._schemas = new Map();
66
- /** @private */ this._indexes = new Map();
67
- }
68
-
69
- /**
70
- * Create a table (register schema).
71
- * @param {string} table - Table name.
72
- * @param {object} schema - Column definitions.
73
- */
74
- async createTable(table, schema)
75
- {
76
- if (!this._tables.has(table))
77
- {
78
- this._tables.set(table, []);
79
- this._autoIncrements.set(table, 1);
80
- }
81
- if (schema) this._schemas.set(table, schema);
82
- }
83
-
84
- /**
85
- * Drop a table.
86
- * @param {string} table - Table name.
87
- */
88
- async dropTable(table)
89
- {
90
- this._tables.delete(table);
91
- this._autoIncrements.delete(table);
92
- }
93
-
94
- /**
95
- * Insert a row.
96
- * @param {string} table - Table name.
97
- * @param {object} data - Row data.
98
- * @returns {Promise<object>} Inserted row (with auto-increment ID if applicable).
99
- */
100
- async insert(table, data)
101
- {
102
- const rows = this._getTable(table);
103
- const row = { ...data };
104
-
105
- // Auto-increment: find any key not provided
106
- if (row.id === undefined || row.id === null)
107
- {
108
- row.id = this._autoIncrements.get(table) || 1;
109
- this._autoIncrements.set(table, row.id + 1);
110
- }
111
-
112
- // Serialize Date objects
113
- for (const [k, v] of Object.entries(row))
114
- {
115
- if (v instanceof Date) row[k] = v.toISOString();
116
- }
117
-
118
- // Enforce unique constraints from schema
119
- this._enforceUnique(table, row);
120
-
121
- rows.push(row);
122
- return row;
123
- }
124
-
125
- /**
126
- * Insert multiple rows at once.
127
- * @param {string} table - Table name.
128
- * @param {object[]} dataArray - Array of row data.
129
- * @returns {Promise<object[]>} Array of inserted rows.
130
- */
131
- async insertMany(table, dataArray)
132
- {
133
- const results = [];
134
- for (const data of dataArray) results.push(await this.insert(table, data));
135
- return results;
136
- }
137
-
138
- /**
139
- * Update a row by primary key.
140
- * @param {string} table - Table name.
141
- * @param {string} pk - Primary key column name.
142
- * @param {*} pkVal - Primary key value.
143
- * @param {object} data - Fields to update.
144
- */
145
- async update(table, pk, pkVal, data)
146
- {
147
- const rows = this._getTable(table);
148
- const row = rows.find(r => r[pk] === pkVal);
149
- if (row)
150
- {
151
- for (const [k, v] of Object.entries(data))
152
- {
153
- row[k] = v instanceof Date ? v.toISOString() : v;
154
- }
155
- }
156
- }
157
-
158
- /**
159
- * Update all rows matching conditions.
160
- * @param {string} table - Table name.
161
- * @param {object} conditions - WHERE conditions.
162
- * @param {object} data - Fields to update.
163
- * @returns {Promise<number>} Number of updated rows.
164
- */
165
- async updateWhere(table, conditions, data)
166
- {
167
- const rows = this._getTable(table);
168
- let count = 0;
169
- for (const row of rows)
170
- {
171
- if (this._matchConditions(row, conditions))
172
- {
173
- for (const [k, v] of Object.entries(data))
174
- {
175
- row[k] = v instanceof Date ? v.toISOString() : v;
176
- }
177
- count++;
178
- }
179
- }
180
- return count;
181
- }
182
-
183
- /**
184
- * Remove a row by primary key.
185
- * @param {string} table - Table name.
186
- * @param {string} pk - Primary key column name.
187
- * @param {*} pkVal - Primary key value.
188
- */
189
- async remove(table, pk, pkVal)
190
- {
191
- const rows = this._getTable(table);
192
- const idx = rows.findIndex(r => r[pk] === pkVal);
193
- if (idx !== -1) rows.splice(idx, 1);
194
- }
195
-
196
- /**
197
- * Delete all rows matching conditions.
198
- * @param {string} table - Table name.
199
- * @param {object} conditions - Filter conditions.
200
- * @returns {Promise<number>} Number of deleted rows.
201
- */
202
- async deleteWhere(table, conditions)
203
- {
204
- const rows = this._getTable(table);
205
- let count = 0;
206
- for (let i = rows.length - 1; i >= 0; i--)
207
- {
208
- if (this._matchConditions(rows[i], conditions))
209
- {
210
- rows.splice(i, 1);
211
- count++;
212
- }
213
- }
214
- return count;
215
- }
216
-
217
- /**
218
- * Execute a query descriptor (from the Query builder).
219
- * @param {object} descriptor - Abstract query descriptor.
220
- * @returns {Promise<Array|number>} Matching rows, or count if action is `'count'`.
221
- */
222
- async execute(descriptor)
223
- {
224
- const { action, table, fields, where, orderBy, limit, offset, distinct, includeDeleted, groupBy, having } = descriptor;
225
- let rows = [...this._getTable(table)];
226
-
227
- // Apply WHERE filters
228
- if (where && where.length > 0)
229
- {
230
- rows = rows.filter(row => this._applyWhereChain(row, where));
231
- }
232
-
233
- // Count action
234
- if (action === 'count') return rows.length;
235
-
236
- // GROUP BY
237
- if (groupBy && groupBy.length > 0)
238
- {
239
- const groups = new Map();
240
- for (const row of rows)
241
- {
242
- const key = groupBy.map(f => row[f]).join('\0');
243
- if (!groups.has(key)) groups.set(key, { _key: {}, _rows: [] });
244
- const g = groups.get(key);
245
- for (const f of groupBy) g._key[f] = row[f];
246
- g._rows.push(row);
247
- }
248
- // Produce one row per group with GROUP BY fields + any selected fields
249
- rows = [];
250
- for (const g of groups.values())
251
- {
252
- const row = { ...g._key };
253
- // Support aggregate expressions in select fields (COUNT(*), etc.) later
254
- row._groupRows = g._rows;
255
- rows.push(row);
256
- }
257
-
258
- // HAVING filter
259
- if (having && having.length > 0)
260
- {
261
- rows = rows.filter(row =>
262
- {
263
- for (const h of having)
264
- {
265
- const field = h.field;
266
- let actual;
267
- // Handle COUNT(*) etc.
268
- if (field === 'COUNT(*)' || field.startsWith('COUNT'))
269
- {
270
- actual = row._groupRows.length;
271
- }
272
- else
273
- {
274
- actual = row[field];
275
- }
276
- const comp = this._compareOp(actual, h.op, h.value);
277
- if (!comp) return false;
278
- }
279
- return true;
280
- });
281
- }
282
-
283
- // Clean up internal _groupRows
284
- for (const row of rows) delete row._groupRows;
285
- }
286
-
287
- // ORDER BY
288
- if (orderBy && orderBy.length > 0)
289
- {
290
- rows.sort((a, b) =>
291
- {
292
- for (const { field, dir } of orderBy)
293
- {
294
- const av = a[field], bv = b[field];
295
- if (av < bv) return dir === 'ASC' ? -1 : 1;
296
- if (av > bv) return dir === 'ASC' ? 1 : -1;
297
- }
298
- return 0;
299
- });
300
- }
301
-
302
- // OFFSET
303
- if (offset) rows = rows.slice(offset);
304
-
305
- // LIMIT
306
- if (limit) rows = rows.slice(0, limit);
307
-
308
- // SELECT specific fields
309
- if (fields && fields.length > 0)
310
- {
311
- rows = rows.map(row =>
312
- {
313
- const filtered = {};
314
- for (const f of fields) filtered[f] = row[f];
315
- return filtered;
316
- });
317
- }
318
-
319
- // DISTINCT
320
- if (distinct)
321
- {
322
- const seen = new Set();
323
- rows = rows.filter(row =>
324
- {
325
- const key = JSON.stringify(row);
326
- if (seen.has(key)) return false;
327
- seen.add(key);
328
- return true;
329
- });
330
- }
331
-
332
- return rows;
333
- }
334
-
335
- /**
336
- * Compute an aggregate value in memory.
337
- * @param {object} descriptor - Query descriptor object.
338
- * @returns {Promise<number|null>} Computed aggregate value.
339
- */
340
- async aggregate(descriptor)
341
- {
342
- const { table, where, aggregateFn, aggregateField } = descriptor;
343
- let rows = [...this._getTable(table)];
344
- if (where && where.length > 0) rows = rows.filter(row => this._applyWhereChain(row, where));
345
- const fn = aggregateFn.toLowerCase();
346
- if (!rows.length) return (fn === 'count' || fn === 'avg' || fn === 'sum') ? 0 : null;
347
- switch (fn)
348
- {
349
- case 'sum': return rows.reduce((acc, r) => acc + (Number(r[aggregateField]) || 0), 0);
350
- case 'avg': return rows.reduce((acc, r) => acc + (Number(r[aggregateField]) || 0), 0) / rows.length;
351
- case 'min': return rows.reduce((m, r) => (r[aggregateField] < m ? r[aggregateField] : m), rows[0][aggregateField]);
352
- case 'max': return rows.reduce((m, r) => (r[aggregateField] > m ? r[aggregateField] : m), rows[0][aggregateField]);
353
- case 'count': return rows.length;
354
- default: return null;
355
- }
356
- }
357
-
358
- /**
359
- * Get the query execution plan (memory adapter).
360
- * Returns a description object since there is no real query plan.
361
- * @param {object} descriptor - Query descriptor.
362
- * @returns {{ adapter: string, plan: string, table: string, action: string, estimatedRows: number, filters: number }}
363
- */
364
- explain(descriptor)
365
- {
366
- return {
367
- adapter: 'memory',
368
- plan: 'Full table scan (in-memory)',
369
- table: descriptor.table || '',
370
- action: descriptor.action || 'select',
371
- estimatedRows: this._getTable(descriptor.table || '').length,
372
- filters: descriptor.where ? descriptor.where.length : 0,
373
- };
374
- }
375
-
376
- /**
377
- * Clear all data (for testing).
378
- * @returns {Promise<void>}
379
- */
380
- async clear()
381
- {
382
- for (const key of this._tables.keys())
383
- {
384
- this._tables.set(key, []);
385
- this._autoIncrements.set(key, 1);
386
- }
387
- }
388
-
389
- // -- Internal Helpers -------------------------------
390
-
391
- /** @private Get or create table array. */
392
- _getTable(table)
393
- {
394
- if (!this._tables.has(table)) this._tables.set(table, []);
395
- return this._tables.get(table);
396
- }
397
-
398
- /** @private Match simple object conditions { key: value }. */
399
- _matchConditions(row, conditions)
400
- {
401
- if (!conditions || typeof conditions !== 'object') return true;
402
- for (const [k, v] of Object.entries(conditions))
403
- {
404
- if (row[k] !== v) return false;
405
- }
406
- return true;
407
- }
408
-
409
- /** @private Apply the where chain from query builder. */
410
- _applyWhereChain(row, where)
411
- {
412
- let result = true;
413
- for (let i = 0; i < where.length; i++)
414
- {
415
- const clause = where[i];
416
- // Skip raw SQL clauses — not supported in memory adapter
417
- if (clause.raw) continue;
418
- const matches = this._matchClause(row, clause);
419
-
420
- if (i === 0 || clause.logic === 'AND')
421
- {
422
- result = i === 0 ? matches : (result && matches);
423
- }
424
- else if (clause.logic === 'OR')
425
- {
426
- result = result || matches;
427
- }
428
- }
429
- return result;
430
- }
431
-
432
- /** @private Match a single WHERE clause. */
433
- _matchClause(row, clause)
434
- {
435
- const val = row[clause.field];
436
- const { op, value } = clause;
437
-
438
- switch (op)
439
- {
440
- case '=': return val === value;
441
- case '!=':
442
- case '<>': return val !== value;
443
- case '>': return val > value;
444
- case '<': return val < value;
445
- case '>=': return val >= value;
446
- case '<=': return val <= value;
447
- case 'LIKE': return _likeSafe(String(val), String(value));
448
- case 'IN': return Array.isArray(value) && value.includes(val);
449
- case 'NOT IN': return Array.isArray(value) && !value.includes(val);
450
- case 'BETWEEN': return Array.isArray(value) && val >= value[0] && val <= value[1];
451
- case 'NOT BETWEEN': return Array.isArray(value) && (val < value[0] || val > value[1]);
452
- case 'IS NULL': return val === null || val === undefined;
453
- case 'IS NOT NULL': return val !== null && val !== undefined;
454
- default: return val === value;
455
- }
456
- }
457
-
458
- /** @private Compare a value using an operator. */
459
- _compareOp(actual, op, value)
460
- {
461
- switch (op.toUpperCase())
462
- {
463
- case '=': return actual === value;
464
- case '!=':
465
- case '<>': return actual !== value;
466
- case '>': return actual > value;
467
- case '<': return actual < value;
468
- case '>=': return actual >= value;
469
- case '<=': return actual <= value;
470
- default: return actual === value;
471
- }
472
- }
473
-
474
- // -- Memory Adapter Utilities ------------------------
475
-
476
- /**
477
- * List all registered table names.
478
- * @returns {string[]} Array of table names.
479
- */
480
- tables()
481
- {
482
- return [...this._tables.keys()];
483
- }
484
-
485
- /**
486
- * Get the total number of rows across all tables.
487
- * @returns {number} Total row count across all tables.
488
- */
489
- totalRows()
490
- {
491
- let total = 0;
492
- for (const rows of this._tables.values()) total += rows.length;
493
- return total;
494
- }
495
-
496
- /**
497
- * Get memory usage stats.
498
- * @returns {{ tables: number, totalRows: number, estimatedBytes: number }}
499
- */
500
- stats()
501
- {
502
- const tables = this._tables.size;
503
- let totalRows = 0;
504
- let estimatedBytes = 0;
505
- for (const rows of this._tables.values())
506
- {
507
- totalRows += rows.length;
508
- estimatedBytes += JSON.stringify(rows).length * 2; // rough UTF-16 estimate
509
- }
510
- return { tables, totalRows, estimatedBytes };
511
- }
512
-
513
- /**
514
- * Export all data as a plain object.
515
- * @returns {object} { tableName: rows[], ... }
516
- */
517
- toJSON()
518
- {
519
- const out = {};
520
- for (const [table, rows] of this._tables) out[table] = [...rows];
521
- return out;
522
- }
523
-
524
- /**
525
- * Import data from a plain object, merging with existing data.
526
- * @param {object} data - { tableName: rows[], ... }
527
- */
528
- fromJSON(data)
529
- {
530
- for (const [table, rows] of Object.entries(data))
531
- {
532
- if (!this._tables.has(table)) this._tables.set(table, []);
533
- const existing = this._tables.get(table);
534
- for (const row of rows) existing.push({ ...row });
535
- // Update auto-increment
536
- const maxId = rows.reduce((max, r) => Math.max(max, r.id || 0), 0);
537
- const currentAi = this._autoIncrements.get(table) || 1;
538
- if (maxId >= currentAi) this._autoIncrements.set(table, maxId + 1);
539
- }
540
- }
541
-
542
- /**
543
- * Clone the entire database state (deep copy).
544
- * @returns {MemoryAdapter} Deep copy of this adapter.
545
- */
546
- clone()
547
- {
548
- const copy = new MemoryAdapter();
549
- copy.fromJSON(this.toJSON());
550
- for (const [t, s] of this._schemas) copy._schemas.set(t, { ...s });
551
- return copy;
552
- }
553
-
554
- // -- Unique constraint enforcement -------------------
555
-
556
- /** @private Enforce unique constraints defined in schema. */
557
- _enforceUnique(table, row, excludeRow)
558
- {
559
- const schema = this._schemas.get(table);
560
- if (!schema) return;
561
- const rows = this._getTable(table);
562
-
563
- for (const [col, def] of Object.entries(schema))
564
- {
565
- if (def.unique && row[col] !== undefined && row[col] !== null)
566
- {
567
- const duplicate = rows.find(r => r !== excludeRow && r[col] === row[col]);
568
- if (duplicate)
569
- {
570
- throw new Error(`UNIQUE constraint failed: ${table}.${col}`);
571
- }
572
- }
573
- }
574
-
575
- // Composite unique constraints
576
- const groups = {};
577
- for (const [col, def] of Object.entries(schema))
578
- {
579
- if (def.compositeUnique)
580
- {
581
- const g = typeof def.compositeUnique === 'string' ? def.compositeUnique : 'default';
582
- if (!groups[g]) groups[g] = [];
583
- groups[g].push(col);
584
- }
585
- }
586
- for (const cols of Object.values(groups))
587
- {
588
- const duplicate = rows.find(r =>
589
- r !== excludeRow && cols.every(c => r[c] === row[c])
590
- );
591
- if (duplicate)
592
- {
593
- throw new Error(`UNIQUE constraint failed: ${table}.(${cols.join(', ')})`);
594
- }
595
- }
596
- }
597
-
598
- // -- Migration / DDL Methods -------------------------
599
-
600
- /**
601
- * Add a column to an existing table (sets default for existing rows).
602
- * @param {string} table - Table name.
603
- * @param {string} column - Column name.
604
- * @param {object} def - Column definition.
605
- * @returns {Promise<void>}
606
- */
607
- async addColumn(table, column, def)
608
- {
609
- const schema = this._schemas.get(table);
610
- if (schema) schema[column] = def;
611
- const defaultVal = def.default !== undefined ? (typeof def.default === 'function' ? def.default() : def.default) : null;
612
- const rows = this._getTable(table);
613
- for (const row of rows)
614
- {
615
- if (row[column] === undefined) row[column] = defaultVal;
616
- }
617
- }
618
-
619
- /**
620
- * Drop a column from a table.
621
- * @param {string} table - Table name.
622
- * @param {string} column - Column name.
623
- * @returns {Promise<void>}
624
- */
625
- async dropColumn(table, column)
626
- {
627
- const schema = this._schemas.get(table);
628
- if (schema) delete schema[column];
629
- const rows = this._getTable(table);
630
- for (const row of rows) delete row[column];
631
- }
632
-
633
- /**
634
- * Rename a column.
635
- * @param {string} table - Table name.
636
- * @param {string} oldName - Current name.
637
- * @param {string} newName - New name.
638
- * @returns {Promise<void>}
639
- */
640
- async renameColumn(table, oldName, newName)
641
- {
642
- const schema = this._schemas.get(table);
643
- if (schema && schema[oldName])
644
- {
645
- schema[newName] = schema[oldName];
646
- delete schema[oldName];
647
- }
648
- const rows = this._getTable(table);
649
- for (const row of rows)
650
- {
651
- if (oldName in row)
652
- {
653
- row[newName] = row[oldName];
654
- delete row[oldName];
655
- }
656
- }
657
- }
658
-
659
- /**
660
- * Rename a table.
661
- * @param {string} oldName - Current name.
662
- * @param {string} newName - New name.
663
- * @returns {Promise<void>}
664
- */
665
- async renameTable(oldName, newName)
666
- {
667
- if (this._tables.has(oldName))
668
- {
669
- this._tables.set(newName, this._tables.get(oldName));
670
- this._tables.delete(oldName);
671
- this._autoIncrements.set(newName, this._autoIncrements.get(oldName) || 1);
672
- this._autoIncrements.delete(oldName);
673
- if (this._schemas.has(oldName))
674
- {
675
- this._schemas.set(newName, this._schemas.get(oldName));
676
- this._schemas.delete(oldName);
677
- }
678
- }
679
- }
680
-
681
- /**
682
- * Create an index (tracked in metadata, no-op for queries).
683
- * @param {string} table - Table name.
684
- * @param {string|string[]} columns - Column name(s).
685
- * @param {{ name?: string, unique?: boolean }} [options={}]
686
- * @returns {Promise<void>}
687
- */
688
- async createIndex(table, columns, options = {})
689
- {
690
- const cols = Array.isArray(columns) ? columns : [columns];
691
- const name = options.name || `idx_${table}_${cols.join('_')}`;
692
- if (!this._indexes.has(table)) this._indexes.set(table, []);
693
- this._indexes.get(table).push({ name, columns: cols, unique: !!options.unique });
694
- }
695
-
696
- /**
697
- * Drop an index.
698
- * @param {string} _table - Table name (unused — searches all tables).
699
- * @param {string} name - Index name.
700
- * @returns {Promise<void>}
701
- */
702
- async dropIndex(_table, name)
703
- {
704
- for (const [table, indexes] of this._indexes)
705
- {
706
- const idx = indexes.findIndex(i => i.name === name);
707
- if (idx !== -1) { indexes.splice(idx, 1); return; }
708
- }
709
- }
710
-
711
- /**
712
- * Check if a table exists.
713
- * @param {string} table - Table name.
714
- * @returns {Promise<boolean>} `true` if the table exists.
715
- */
716
- async hasTable(table)
717
- {
718
- return this._tables.has(table);
719
- }
720
-
721
- /**
722
- * Check if a column exists on a table.
723
- * @param {string} table - Table name.
724
- * @param {string} column - Column name.
725
- * @returns {Promise<boolean>} `true` if the column exists.
726
- */
727
- async hasColumn(table, column)
728
- {
729
- const schema = this._schemas.get(table);
730
- if (schema) return column in schema;
731
- const rows = this._getTable(table);
732
- return rows.length > 0 && column in rows[0];
733
- }
734
-
735
- /**
736
- * Get column info for a table.
737
- * @param {string} table - Table name.
738
- * @returns {Promise<Array<{ name: string, type: string, nullable: boolean, defaultValue: *, primaryKey: boolean }>>}
739
- */
740
- async describeTable(table)
741
- {
742
- const schema = this._schemas.get(table);
743
- if (!schema) return [];
744
- return Object.entries(schema).map(([name, def]) => ({
745
- name,
746
- type: def.type || 'TEXT',
747
- nullable: !def.required,
748
- defaultValue: def.default !== undefined ? def.default : null,
749
- primaryKey: !!def.primaryKey,
750
- }));
751
- }
752
-
753
- /**
754
- * Get indexes for a table.
755
- * @param {string} table - Table name.
756
- * @returns {Promise<Array<{ name: string, columns: string[], unique: boolean }>>}
757
- */
758
- async indexes(table)
759
- {
760
- return this._indexes.get(table) || [];
761
- }
762
- }
763
-
764
- module.exports = MemoryAdapter;
1
+ /**
2
+ * @module orm/adapters/memory
3
+ * @description In-memory database adapter.
4
+ * Zero-dependency, perfect for testing, prototyping, and
5
+ * applications that don't need persistence beyond the process lifecycle.
6
+ *
7
+ * All data is stored in plain JavaScript Maps and arrays.
8
+ * Supports full CRUD, filtering, ordering, pagination, and counting.
9
+ *
10
+ * @example
11
+ * const { Database, Model, TYPES } = require('@zero-server/sdk');
12
+ *
13
+ * const db = Database.connect('memory');
14
+ *
15
+ * class Task extends Model {
16
+ * static table = 'tasks';
17
+ * static schema = {
18
+ * id: { type: TYPES.INTEGER, primaryKey: true, autoIncrement: true },
19
+ * title: { type: TYPES.STRING, required: true },
20
+ * done: { type: TYPES.BOOLEAN, default: false },
21
+ * };
22
+ * }
23
+ *
24
+ * db.register(Task);
25
+ * await db.sync();
26
+ *
27
+ * await Task.create({ title: 'Write tests' });
28
+ * const pending = await Task.find({ done: false });
29
+ */
30
+
31
+ /**
32
+ * ReDoS-safe SQL LIKE matcher using iterative DP.
33
+ * % = any sequence of chars, _ = any single char. Case-insensitive.
34
+ * @private
35
+ */
36
+ function _likeSafe(str, pattern)
37
+ {
38
+ const s = str.toLowerCase();
39
+ const p = pattern.toLowerCase();
40
+ const sLen = s.length, pLen = p.length;
41
+ let dp = new Array(pLen + 1).fill(false);
42
+ dp[0] = true;
43
+ for (let j = 0; j < pLen; j++) { if (p[j] === '%') dp[j + 1] = dp[j]; }
44
+ for (let i = 1; i <= sLen; i++)
45
+ {
46
+ const next = new Array(pLen + 1).fill(false);
47
+ for (let j = 1; j <= pLen; j++)
48
+ {
49
+ if (p[j - 1] === '%') next[j] = dp[j] || next[j - 1];
50
+ else if (p[j - 1] === '_') next[j] = dp[j - 1];
51
+ else next[j] = dp[j - 1] && s[i - 1] === p[j - 1];
52
+ }
53
+ dp = next;
54
+ }
55
+ return dp[pLen];
56
+ }
57
+
58
+ class MemoryAdapter
59
+ {
60
+ /** @constructor */
61
+ constructor()
62
+ {
63
+ /** @private */ this._tables = new Map();
64
+ /** @private */ this._autoIncrements = new Map();
65
+ /** @private */ this._schemas = new Map();
66
+ /** @private */ this._indexes = new Map();
67
+ }
68
+
69
+ /**
70
+ * Create a table (register schema).
71
+ * @param {string} table - Table name.
72
+ * @param {object} schema - Column definitions.
73
+ */
74
+ async createTable(table, schema)
75
+ {
76
+ if (!this._tables.has(table))
77
+ {
78
+ this._tables.set(table, []);
79
+ this._autoIncrements.set(table, 1);
80
+ }
81
+ if (schema) this._schemas.set(table, schema);
82
+ }
83
+
84
+ /**
85
+ * Drop a table.
86
+ * @param {string} table - Table name.
87
+ */
88
+ async dropTable(table)
89
+ {
90
+ this._tables.delete(table);
91
+ this._autoIncrements.delete(table);
92
+ }
93
+
94
+ /**
95
+ * Insert a row.
96
+ * @param {string} table - Table name.
97
+ * @param {object} data - Row data.
98
+ * @returns {Promise<object>} Inserted row (with auto-increment ID if applicable).
99
+ */
100
+ async insert(table, data)
101
+ {
102
+ const rows = this._getTable(table);
103
+ const row = { ...data };
104
+
105
+ // Auto-increment: find any key not provided
106
+ if (row.id === undefined || row.id === null)
107
+ {
108
+ row.id = this._autoIncrements.get(table) || 1;
109
+ this._autoIncrements.set(table, row.id + 1);
110
+ }
111
+
112
+ // Serialize Date objects
113
+ for (const [k, v] of Object.entries(row))
114
+ {
115
+ if (v instanceof Date) row[k] = v.toISOString();
116
+ }
117
+
118
+ // Enforce unique constraints from schema
119
+ this._enforceUnique(table, row);
120
+
121
+ rows.push(row);
122
+ return row;
123
+ }
124
+
125
+ /**
126
+ * Insert multiple rows at once.
127
+ * @param {string} table - Table name.
128
+ * @param {object[]} dataArray - Array of row data.
129
+ * @returns {Promise<object[]>} Array of inserted rows.
130
+ */
131
+ async insertMany(table, dataArray)
132
+ {
133
+ const results = [];
134
+ for (const data of dataArray) results.push(await this.insert(table, data));
135
+ return results;
136
+ }
137
+
138
+ /**
139
+ * Update a row by primary key.
140
+ * @param {string} table - Table name.
141
+ * @param {string} pk - Primary key column name.
142
+ * @param {*} pkVal - Primary key value.
143
+ * @param {object} data - Fields to update.
144
+ */
145
+ async update(table, pk, pkVal, data)
146
+ {
147
+ const rows = this._getTable(table);
148
+ const row = rows.find(r => r[pk] === pkVal);
149
+ if (row)
150
+ {
151
+ for (const [k, v] of Object.entries(data))
152
+ {
153
+ row[k] = v instanceof Date ? v.toISOString() : v;
154
+ }
155
+ }
156
+ }
157
+
158
+ /**
159
+ * Update all rows matching conditions.
160
+ * @param {string} table - Table name.
161
+ * @param {object} conditions - WHERE conditions.
162
+ * @param {object} data - Fields to update.
163
+ * @returns {Promise<number>} Number of updated rows.
164
+ */
165
+ async updateWhere(table, conditions, data)
166
+ {
167
+ const rows = this._getTable(table);
168
+ let count = 0;
169
+ for (const row of rows)
170
+ {
171
+ if (this._matchConditions(row, conditions))
172
+ {
173
+ for (const [k, v] of Object.entries(data))
174
+ {
175
+ row[k] = v instanceof Date ? v.toISOString() : v;
176
+ }
177
+ count++;
178
+ }
179
+ }
180
+ return count;
181
+ }
182
+
183
+ /**
184
+ * Remove a row by primary key.
185
+ * @param {string} table - Table name.
186
+ * @param {string} pk - Primary key column name.
187
+ * @param {*} pkVal - Primary key value.
188
+ */
189
+ async remove(table, pk, pkVal)
190
+ {
191
+ const rows = this._getTable(table);
192
+ const idx = rows.findIndex(r => r[pk] === pkVal);
193
+ if (idx !== -1) rows.splice(idx, 1);
194
+ }
195
+
196
+ /**
197
+ * Delete all rows matching conditions.
198
+ * @param {string} table - Table name.
199
+ * @param {object} conditions - Filter conditions.
200
+ * @returns {Promise<number>} Number of deleted rows.
201
+ */
202
+ async deleteWhere(table, conditions)
203
+ {
204
+ const rows = this._getTable(table);
205
+ let count = 0;
206
+ for (let i = rows.length - 1; i >= 0; i--)
207
+ {
208
+ if (this._matchConditions(rows[i], conditions))
209
+ {
210
+ rows.splice(i, 1);
211
+ count++;
212
+ }
213
+ }
214
+ return count;
215
+ }
216
+
217
+ /**
218
+ * Execute a query descriptor (from the Query builder).
219
+ * @param {object} descriptor - Abstract query descriptor.
220
+ * @returns {Promise<Array|number>} Matching rows, or count if action is `'count'`.
221
+ */
222
+ async execute(descriptor)
223
+ {
224
+ const { action, table, fields, where, orderBy, limit, offset, distinct, includeDeleted, groupBy, having } = descriptor;
225
+ let rows = [...this._getTable(table)];
226
+
227
+ // Apply WHERE filters
228
+ if (where && where.length > 0)
229
+ {
230
+ rows = rows.filter(row => this._applyWhereChain(row, where));
231
+ }
232
+
233
+ // Count action
234
+ if (action === 'count') return rows.length;
235
+
236
+ // GROUP BY
237
+ if (groupBy && groupBy.length > 0)
238
+ {
239
+ const groups = new Map();
240
+ for (const row of rows)
241
+ {
242
+ const key = groupBy.map(f => row[f]).join('\0');
243
+ if (!groups.has(key)) groups.set(key, { _key: {}, _rows: [] });
244
+ const g = groups.get(key);
245
+ for (const f of groupBy) g._key[f] = row[f];
246
+ g._rows.push(row);
247
+ }
248
+ // Produce one row per group with GROUP BY fields + any selected fields
249
+ rows = [];
250
+ for (const g of groups.values())
251
+ {
252
+ const row = { ...g._key };
253
+ // Support aggregate expressions in select fields (COUNT(*), etc.) later
254
+ row._groupRows = g._rows;
255
+ rows.push(row);
256
+ }
257
+
258
+ // HAVING filter
259
+ if (having && having.length > 0)
260
+ {
261
+ rows = rows.filter(row =>
262
+ {
263
+ for (const h of having)
264
+ {
265
+ const field = h.field;
266
+ let actual;
267
+ // Handle COUNT(*) etc.
268
+ if (field === 'COUNT(*)' || field.startsWith('COUNT'))
269
+ {
270
+ actual = row._groupRows.length;
271
+ }
272
+ else
273
+ {
274
+ actual = row[field];
275
+ }
276
+ const comp = this._compareOp(actual, h.op, h.value);
277
+ if (!comp) return false;
278
+ }
279
+ return true;
280
+ });
281
+ }
282
+
283
+ // Clean up internal _groupRows
284
+ for (const row of rows) delete row._groupRows;
285
+ }
286
+
287
+ // ORDER BY
288
+ if (orderBy && orderBy.length > 0)
289
+ {
290
+ rows.sort((a, b) =>
291
+ {
292
+ for (const { field, dir } of orderBy)
293
+ {
294
+ const av = a[field], bv = b[field];
295
+ if (av < bv) return dir === 'ASC' ? -1 : 1;
296
+ if (av > bv) return dir === 'ASC' ? 1 : -1;
297
+ }
298
+ return 0;
299
+ });
300
+ }
301
+
302
+ // OFFSET
303
+ if (offset) rows = rows.slice(offset);
304
+
305
+ // LIMIT
306
+ if (limit) rows = rows.slice(0, limit);
307
+
308
+ // SELECT specific fields
309
+ if (fields && fields.length > 0)
310
+ {
311
+ rows = rows.map(row =>
312
+ {
313
+ const filtered = {};
314
+ for (const f of fields) filtered[f] = row[f];
315
+ return filtered;
316
+ });
317
+ }
318
+
319
+ // DISTINCT
320
+ if (distinct)
321
+ {
322
+ const seen = new Set();
323
+ rows = rows.filter(row =>
324
+ {
325
+ const key = JSON.stringify(row);
326
+ if (seen.has(key)) return false;
327
+ seen.add(key);
328
+ return true;
329
+ });
330
+ }
331
+
332
+ return rows;
333
+ }
334
+
335
+ /**
336
+ * Compute an aggregate value in memory.
337
+ * @param {object} descriptor - Query descriptor object.
338
+ * @returns {Promise<number|null>} Computed aggregate value.
339
+ */
340
+ async aggregate(descriptor)
341
+ {
342
+ const { table, where, aggregateFn, aggregateField } = descriptor;
343
+ let rows = [...this._getTable(table)];
344
+ if (where && where.length > 0) rows = rows.filter(row => this._applyWhereChain(row, where));
345
+ const fn = aggregateFn.toLowerCase();
346
+ if (!rows.length) return (fn === 'count' || fn === 'avg' || fn === 'sum') ? 0 : null;
347
+ switch (fn)
348
+ {
349
+ case 'sum': return rows.reduce((acc, r) => acc + (Number(r[aggregateField]) || 0), 0);
350
+ case 'avg': return rows.reduce((acc, r) => acc + (Number(r[aggregateField]) || 0), 0) / rows.length;
351
+ case 'min': return rows.reduce((m, r) => (r[aggregateField] < m ? r[aggregateField] : m), rows[0][aggregateField]);
352
+ case 'max': return rows.reduce((m, r) => (r[aggregateField] > m ? r[aggregateField] : m), rows[0][aggregateField]);
353
+ case 'count': return rows.length;
354
+ default: return null;
355
+ }
356
+ }
357
+
358
+ /**
359
+ * Get the query execution plan (memory adapter).
360
+ * Returns a description object since there is no real query plan.
361
+ * @param {object} descriptor - Query descriptor.
362
+ * @returns {{ adapter: string, plan: string, table: string, action: string, estimatedRows: number, filters: number }}
363
+ */
364
+ explain(descriptor)
365
+ {
366
+ return {
367
+ adapter: 'memory',
368
+ plan: 'Full table scan (in-memory)',
369
+ table: descriptor.table || '',
370
+ action: descriptor.action || 'select',
371
+ estimatedRows: this._getTable(descriptor.table || '').length,
372
+ filters: descriptor.where ? descriptor.where.length : 0,
373
+ };
374
+ }
375
+
376
+ /**
377
+ * Clear all data (for testing).
378
+ * @returns {Promise<void>}
379
+ */
380
+ async clear()
381
+ {
382
+ for (const key of this._tables.keys())
383
+ {
384
+ this._tables.set(key, []);
385
+ this._autoIncrements.set(key, 1);
386
+ }
387
+ }
388
+
389
+ // -- Internal Helpers -------------------------------
390
+
391
+ /** @private Get or create table array. */
392
+ _getTable(table)
393
+ {
394
+ if (!this._tables.has(table)) this._tables.set(table, []);
395
+ return this._tables.get(table);
396
+ }
397
+
398
+ /** @private Match simple object conditions { key: value }. */
399
+ _matchConditions(row, conditions)
400
+ {
401
+ if (!conditions || typeof conditions !== 'object') return true;
402
+ for (const [k, v] of Object.entries(conditions))
403
+ {
404
+ if (row[k] !== v) return false;
405
+ }
406
+ return true;
407
+ }
408
+
409
+ /** @private Apply the where chain from query builder. */
410
+ _applyWhereChain(row, where)
411
+ {
412
+ let result = true;
413
+ for (let i = 0; i < where.length; i++)
414
+ {
415
+ const clause = where[i];
416
+ // Skip raw SQL clauses — not supported in memory adapter
417
+ if (clause.raw) continue;
418
+ const matches = this._matchClause(row, clause);
419
+
420
+ if (i === 0 || clause.logic === 'AND')
421
+ {
422
+ result = i === 0 ? matches : (result && matches);
423
+ }
424
+ else if (clause.logic === 'OR')
425
+ {
426
+ result = result || matches;
427
+ }
428
+ }
429
+ return result;
430
+ }
431
+
432
+ /** @private Match a single WHERE clause. */
433
+ _matchClause(row, clause)
434
+ {
435
+ const val = row[clause.field];
436
+ const { op, value } = clause;
437
+
438
+ switch (op)
439
+ {
440
+ case '=': return val === value;
441
+ case '!=':
442
+ case '<>': return val !== value;
443
+ case '>': return val > value;
444
+ case '<': return val < value;
445
+ case '>=': return val >= value;
446
+ case '<=': return val <= value;
447
+ case 'LIKE': return _likeSafe(String(val), String(value));
448
+ case 'IN': return Array.isArray(value) && value.includes(val);
449
+ case 'NOT IN': return Array.isArray(value) && !value.includes(val);
450
+ case 'BETWEEN': return Array.isArray(value) && val >= value[0] && val <= value[1];
451
+ case 'NOT BETWEEN': return Array.isArray(value) && (val < value[0] || val > value[1]);
452
+ case 'IS NULL': return val === null || val === undefined;
453
+ case 'IS NOT NULL': return val !== null && val !== undefined;
454
+ default: return val === value;
455
+ }
456
+ }
457
+
458
+ /** @private Compare a value using an operator. */
459
+ _compareOp(actual, op, value)
460
+ {
461
+ switch (op.toUpperCase())
462
+ {
463
+ case '=': return actual === value;
464
+ case '!=':
465
+ case '<>': return actual !== value;
466
+ case '>': return actual > value;
467
+ case '<': return actual < value;
468
+ case '>=': return actual >= value;
469
+ case '<=': return actual <= value;
470
+ default: return actual === value;
471
+ }
472
+ }
473
+
474
+ // -- Memory Adapter Utilities ------------------------
475
+
476
+ /**
477
+ * List all registered table names.
478
+ * @returns {string[]} Array of table names.
479
+ */
480
+ tables()
481
+ {
482
+ return [...this._tables.keys()];
483
+ }
484
+
485
+ /**
486
+ * Get the total number of rows across all tables.
487
+ * @returns {number} Total row count across all tables.
488
+ */
489
+ totalRows()
490
+ {
491
+ let total = 0;
492
+ for (const rows of this._tables.values()) total += rows.length;
493
+ return total;
494
+ }
495
+
496
+ /**
497
+ * Get memory usage stats.
498
+ * @returns {{ tables: number, totalRows: number, estimatedBytes: number }}
499
+ */
500
+ stats()
501
+ {
502
+ const tables = this._tables.size;
503
+ let totalRows = 0;
504
+ let estimatedBytes = 0;
505
+ for (const rows of this._tables.values())
506
+ {
507
+ totalRows += rows.length;
508
+ estimatedBytes += JSON.stringify(rows).length * 2; // rough UTF-16 estimate
509
+ }
510
+ return { tables, totalRows, estimatedBytes };
511
+ }
512
+
513
+ /**
514
+ * Export all data as a plain object.
515
+ * @returns {object} { tableName: rows[], ... }
516
+ */
517
+ toJSON()
518
+ {
519
+ const out = {};
520
+ for (const [table, rows] of this._tables) out[table] = [...rows];
521
+ return out;
522
+ }
523
+
524
+ /**
525
+ * Import data from a plain object, merging with existing data.
526
+ * @param {object} data - { tableName: rows[], ... }
527
+ */
528
+ fromJSON(data)
529
+ {
530
+ for (const [table, rows] of Object.entries(data))
531
+ {
532
+ if (!this._tables.has(table)) this._tables.set(table, []);
533
+ const existing = this._tables.get(table);
534
+ for (const row of rows) existing.push({ ...row });
535
+ // Update auto-increment
536
+ const maxId = rows.reduce((max, r) => Math.max(max, r.id || 0), 0);
537
+ const currentAi = this._autoIncrements.get(table) || 1;
538
+ if (maxId >= currentAi) this._autoIncrements.set(table, maxId + 1);
539
+ }
540
+ }
541
+
542
+ /**
543
+ * Clone the entire database state (deep copy).
544
+ * @returns {MemoryAdapter} Deep copy of this adapter.
545
+ */
546
+ clone()
547
+ {
548
+ const copy = new MemoryAdapter();
549
+ copy.fromJSON(this.toJSON());
550
+ for (const [t, s] of this._schemas) copy._schemas.set(t, { ...s });
551
+ return copy;
552
+ }
553
+
554
+ // -- Unique constraint enforcement -------------------
555
+
556
+ /** @private Enforce unique constraints defined in schema. */
557
+ _enforceUnique(table, row, excludeRow)
558
+ {
559
+ const schema = this._schemas.get(table);
560
+ if (!schema) return;
561
+ const rows = this._getTable(table);
562
+
563
+ for (const [col, def] of Object.entries(schema))
564
+ {
565
+ if (def.unique && row[col] !== undefined && row[col] !== null)
566
+ {
567
+ const duplicate = rows.find(r => r !== excludeRow && r[col] === row[col]);
568
+ if (duplicate)
569
+ {
570
+ throw new Error(`UNIQUE constraint failed: ${table}.${col}`);
571
+ }
572
+ }
573
+ }
574
+
575
+ // Composite unique constraints
576
+ const groups = {};
577
+ for (const [col, def] of Object.entries(schema))
578
+ {
579
+ if (def.compositeUnique)
580
+ {
581
+ const g = typeof def.compositeUnique === 'string' ? def.compositeUnique : 'default';
582
+ if (!groups[g]) groups[g] = [];
583
+ groups[g].push(col);
584
+ }
585
+ }
586
+ for (const cols of Object.values(groups))
587
+ {
588
+ const duplicate = rows.find(r =>
589
+ r !== excludeRow && cols.every(c => r[c] === row[c])
590
+ );
591
+ if (duplicate)
592
+ {
593
+ throw new Error(`UNIQUE constraint failed: ${table}.(${cols.join(', ')})`);
594
+ }
595
+ }
596
+ }
597
+
598
+ // -- Migration / DDL Methods -------------------------
599
+
600
+ /**
601
+ * Add a column to an existing table (sets default for existing rows).
602
+ * @param {string} table - Table name.
603
+ * @param {string} column - Column name.
604
+ * @param {object} def - Column definition.
605
+ * @returns {Promise<void>}
606
+ */
607
+ async addColumn(table, column, def)
608
+ {
609
+ const schema = this._schemas.get(table);
610
+ if (schema) schema[column] = def;
611
+ const defaultVal = def.default !== undefined ? (typeof def.default === 'function' ? def.default() : def.default) : null;
612
+ const rows = this._getTable(table);
613
+ for (const row of rows)
614
+ {
615
+ if (row[column] === undefined) row[column] = defaultVal;
616
+ }
617
+ }
618
+
619
+ /**
620
+ * Drop a column from a table.
621
+ * @param {string} table - Table name.
622
+ * @param {string} column - Column name.
623
+ * @returns {Promise<void>}
624
+ */
625
+ async dropColumn(table, column)
626
+ {
627
+ const schema = this._schemas.get(table);
628
+ if (schema) delete schema[column];
629
+ const rows = this._getTable(table);
630
+ for (const row of rows) delete row[column];
631
+ }
632
+
633
+ /**
634
+ * Rename a column.
635
+ * @param {string} table - Table name.
636
+ * @param {string} oldName - Current name.
637
+ * @param {string} newName - New name.
638
+ * @returns {Promise<void>}
639
+ */
640
+ async renameColumn(table, oldName, newName)
641
+ {
642
+ const schema = this._schemas.get(table);
643
+ if (schema && schema[oldName])
644
+ {
645
+ schema[newName] = schema[oldName];
646
+ delete schema[oldName];
647
+ }
648
+ const rows = this._getTable(table);
649
+ for (const row of rows)
650
+ {
651
+ if (oldName in row)
652
+ {
653
+ row[newName] = row[oldName];
654
+ delete row[oldName];
655
+ }
656
+ }
657
+ }
658
+
659
+ /**
660
+ * Rename a table.
661
+ * @param {string} oldName - Current name.
662
+ * @param {string} newName - New name.
663
+ * @returns {Promise<void>}
664
+ */
665
+ async renameTable(oldName, newName)
666
+ {
667
+ if (this._tables.has(oldName))
668
+ {
669
+ this._tables.set(newName, this._tables.get(oldName));
670
+ this._tables.delete(oldName);
671
+ this._autoIncrements.set(newName, this._autoIncrements.get(oldName) || 1);
672
+ this._autoIncrements.delete(oldName);
673
+ if (this._schemas.has(oldName))
674
+ {
675
+ this._schemas.set(newName, this._schemas.get(oldName));
676
+ this._schemas.delete(oldName);
677
+ }
678
+ }
679
+ }
680
+
681
+ /**
682
+ * Create an index (tracked in metadata, no-op for queries).
683
+ * @param {string} table - Table name.
684
+ * @param {string|string[]} columns - Column name(s).
685
+ * @param {{ name?: string, unique?: boolean }} [options={}]
686
+ * @returns {Promise<void>}
687
+ */
688
+ async createIndex(table, columns, options = {})
689
+ {
690
+ const cols = Array.isArray(columns) ? columns : [columns];
691
+ const name = options.name || `idx_${table}_${cols.join('_')}`;
692
+ if (!this._indexes.has(table)) this._indexes.set(table, []);
693
+ this._indexes.get(table).push({ name, columns: cols, unique: !!options.unique });
694
+ }
695
+
696
+ /**
697
+ * Drop an index.
698
+ * @param {string} _table - Table name (unused — searches all tables).
699
+ * @param {string} name - Index name.
700
+ * @returns {Promise<void>}
701
+ */
702
+ async dropIndex(_table, name)
703
+ {
704
+ for (const [table, indexes] of this._indexes)
705
+ {
706
+ const idx = indexes.findIndex(i => i.name === name);
707
+ if (idx !== -1) { indexes.splice(idx, 1); return; }
708
+ }
709
+ }
710
+
711
+ /**
712
+ * Check if a table exists.
713
+ * @param {string} table - Table name.
714
+ * @returns {Promise<boolean>} `true` if the table exists.
715
+ */
716
+ async hasTable(table)
717
+ {
718
+ return this._tables.has(table);
719
+ }
720
+
721
+ /**
722
+ * Check if a column exists on a table.
723
+ * @param {string} table - Table name.
724
+ * @param {string} column - Column name.
725
+ * @returns {Promise<boolean>} `true` if the column exists.
726
+ */
727
+ async hasColumn(table, column)
728
+ {
729
+ const schema = this._schemas.get(table);
730
+ if (schema) return column in schema;
731
+ const rows = this._getTable(table);
732
+ return rows.length > 0 && column in rows[0];
733
+ }
734
+
735
+ /**
736
+ * Get column info for a table.
737
+ * @param {string} table - Table name.
738
+ * @returns {Promise<Array<{ name: string, type: string, nullable: boolean, defaultValue: *, primaryKey: boolean }>>}
739
+ */
740
+ async describeTable(table)
741
+ {
742
+ const schema = this._schemas.get(table);
743
+ if (!schema) return [];
744
+ return Object.entries(schema).map(([name, def]) => ({
745
+ name,
746
+ type: def.type || 'TEXT',
747
+ nullable: !def.required,
748
+ defaultValue: def.default !== undefined ? def.default : null,
749
+ primaryKey: !!def.primaryKey,
750
+ }));
751
+ }
752
+
753
+ /**
754
+ * Get indexes for a table.
755
+ * @param {string} table - Table name.
756
+ * @returns {Promise<Array<{ name: string, columns: string[], unique: boolean }>>}
757
+ */
758
+ async indexes(table)
759
+ {
760
+ return this._indexes.get(table) || [];
761
+ }
762
+ }
763
+
764
+ module.exports = MemoryAdapter;