@zero-server/sdk 0.9.0 → 0.9.2

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 (126) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +460 -437
  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 +460 -460
  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 +136 -136
  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 +254 -254
  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/cluster.d.ts +75 -75
  113. package/types/env.d.ts +80 -80
  114. package/types/errors.d.ts +316 -316
  115. package/types/fetch.d.ts +43 -43
  116. package/types/grpc.d.ts +432 -432
  117. package/types/index.d.ts +384 -384
  118. package/types/lifecycle.d.ts +60 -60
  119. package/types/middleware.d.ts +320 -320
  120. package/types/observe.d.ts +304 -304
  121. package/types/orm.d.ts +1887 -1887
  122. package/types/request.d.ts +109 -109
  123. package/types/response.d.ts +157 -157
  124. package/types/router.d.ts +78 -78
  125. package/types/sse.d.ts +78 -78
  126. package/types/websocket.d.ts +126 -126
@@ -1,1534 +1,1534 @@
1
- /**
2
- * @module orm/adapters/redis
3
- * @description Redis database adapter for the zero-server ORM.
4
- * Uses `ioredis` as the driver. Stores table data as Redis hashes
5
- * with sorted-set indexes for ordering and filtering.
6
- *
7
- * Bring-your-own-driver: `npm install ioredis`
8
- *
9
- * Supports full ORM CRUD, key-value operations, pub/sub,
10
- * pipelines, TTL, and all DDL/migration methods.
11
- *
12
- * @example
13
- * // Connect by host/port
14
- * const db = Database.connect('redis', { host: '127.0.0.1', port: 6379 });
15
- *
16
- * // Connect by URL with authentication
17
- * const db2 = Database.connect('redis', { url: 'redis://user:pass@host:6379/0' });
18
- *
19
- * // Connect with key prefix
20
- * const db3 = Database.connect('redis', { url: 'redis://host:6379', prefix: 'myapp:' });
21
- */
22
-
23
- let Redis;
24
- try { Redis = require('ioredis'); } catch (_) { /* loaded lazily */ }
25
-
26
- /**
27
- * ReDoS-safe SQL LIKE matcher using iterative DP.
28
- * % = any sequence of chars, _ = any single char. Case-insensitive.
29
- * @private
30
- */
31
- function _likeSafe(str, pattern)
32
- {
33
- const s = str.toLowerCase();
34
- const p = pattern.toLowerCase();
35
- const sLen = s.length, pLen = p.length;
36
- let dp = new Array(pLen + 1).fill(false);
37
- dp[0] = true;
38
- for (let j = 0; j < pLen; j++) { if (p[j] === '%') dp[j + 1] = dp[j]; }
39
- for (let i = 1; i <= sLen; i++)
40
- {
41
- const next = new Array(pLen + 1).fill(false);
42
- for (let j = 1; j <= pLen; j++)
43
- {
44
- if (p[j - 1] === '%') next[j] = dp[j] || next[j - 1];
45
- else if (p[j - 1] === '_') next[j] = dp[j - 1];
46
- else next[j] = dp[j - 1] && s[i - 1] === p[j - 1];
47
- }
48
- dp = next;
49
- }
50
- return dp[pLen];
51
- }
52
-
53
- class RedisAdapter
54
- {
55
- /**
56
- * @constructor
57
- * @param {object} [options] - Configuration options.
58
- * @param {string} [options.url] - Redis connection URL.
59
- * @param {string} [options.host='127.0.0.1'] - Redis host.
60
- * @param {number} [options.port=6379] - Redis port.
61
- * @param {string} [options.password] - Redis password.
62
- * @param {number} [options.db=0] - Redis database index.
63
- * @param {string} [options.prefix='zh:'] - Key prefix for namespacing.
64
- * @param {number} [options.maxRetries=3] - Max connection retries.
65
- * @param {boolean} [options.lazyConnect=false] - If true, defer connection until first operation.
66
- * @param {object} [options.tls] - TLS options for secure connections.
67
- * @param {string} [options.keyPrefix] - Alias for prefix (ioredis compat).
68
- * @param {number} [options.connectTimeout=10000] - Connection timeout in ms.
69
- */
70
- constructor(options = {})
71
- {
72
- if (!Redis)
73
- {
74
- throw new Error(
75
- 'Redis adapter requires the "ioredis" package.\n' +
76
- 'Install it with: npm install ioredis'
77
- );
78
- }
79
-
80
- // Validate options at the boundary
81
- if (options.host !== undefined && (typeof options.host !== 'string' || !options.host.length))
82
- throw new Error('Redis: host must be a non-empty string');
83
- if (options.port !== undefined)
84
- {
85
- const p = Number(options.port);
86
- if (!Number.isInteger(p) || p < 1 || p > 65535)
87
- throw new Error('Redis: port must be an integer between 1 and 65535');
88
- }
89
- if (options.db !== undefined)
90
- {
91
- const d = Number(options.db);
92
- if (!Number.isInteger(d) || d < 0 || d > 15)
93
- throw new Error('Redis: db must be an integer between 0 and 15');
94
- }
95
- if (options.password !== undefined && typeof options.password !== 'string')
96
- throw new Error('Redis: password must be a string');
97
- if (options.url !== undefined && typeof options.url !== 'string')
98
- throw new Error('Redis: url must be a string');
99
- if (options.prefix !== undefined && typeof options.prefix !== 'string')
100
- throw new Error('Redis: prefix must be a string');
101
- if (options.connectTimeout !== undefined)
102
- {
103
- const ct = Number(options.connectTimeout);
104
- if (!Number.isFinite(ct) || ct < 0)
105
- throw new Error('Redis: connectTimeout must be a non-negative number');
106
- }
107
-
108
- this._prefix = options.prefix || options.keyPrefix || 'zh:';
109
- this._schemas = new Map();
110
- this._indexes = new Map();
111
- this._subscribers = new Map();
112
-
113
- // Build ioredis config
114
- const config = {};
115
- if (options.url)
116
- {
117
- this._client = new Redis(options.url, {
118
- maxRetriesPerRequest: options.maxRetries || 3,
119
- lazyConnect: options.lazyConnect || false,
120
- connectTimeout: options.connectTimeout || 10000,
121
- tls: options.tls,
122
- keyPrefix: undefined, // we manage prefix ourselves
123
- });
124
- }
125
- else
126
- {
127
- config.host = options.host || '127.0.0.1';
128
- config.port = options.port || 6379;
129
- if (options.password) config.password = options.password;
130
- if (options.db !== undefined) config.db = options.db;
131
- config.maxRetriesPerRequest = options.maxRetries || 3;
132
- config.lazyConnect = options.lazyConnect || false;
133
- config.connectTimeout = options.connectTimeout || 10000;
134
- if (options.tls) config.tls = options.tls;
135
-
136
- this._client = new Redis(config);
137
- }
138
-
139
- // Separate client for pub/sub (subscribers block the connection)
140
- this._subClient = null;
141
- }
142
-
143
- // -- Key Helpers --------------------------------------
144
-
145
- /** @private Validate a table name or key to prevent internal key collision. */
146
- _validateKey(key, label = 'key')
147
- {
148
- if (typeof key !== 'string' || key.length === 0)
149
- throw new Error(`Redis: ${label} must be a non-empty string`);
150
- if (/[\x00-\x1f]/.test(key))
151
- throw new Error(`Redis: ${label} must not contain control characters`);
152
- }
153
-
154
- /** @private Build a prefixed key for a table's metadata. */
155
- _key(table, ...parts)
156
- {
157
- return this._prefix + table + (parts.length ? ':' + parts.join(':') : '');
158
- }
159
-
160
- /** @private Key for a table's row hash: zh:users:row:42 */
161
- _rowKey(table, id)
162
- {
163
- return this._key(table, 'row', String(id));
164
- }
165
-
166
- /** @private Key for a table's ID index sorted set: zh:users:_ids */
167
- _idsKey(table)
168
- {
169
- return this._key(table, '_ids');
170
- }
171
-
172
- /** @private Key for a table's auto-increment counter: zh:users:_seq */
173
- _seqKey(table)
174
- {
175
- return this._key(table, '_seq');
176
- }
177
-
178
- /** @private Key for a table's schema definition: zh:users:_schema */
179
- _schemaKey(table)
180
- {
181
- return this._key(table, '_schema');
182
- }
183
-
184
- /** @private Serialize a row for storage. */
185
- _serialize(row)
186
- {
187
- return JSON.stringify(row);
188
- }
189
-
190
- /** @private Deserialize a stored row. */
191
- _deserialize(data)
192
- {
193
- if (data === null || data === undefined) return null;
194
- try { return JSON.parse(data); }
195
- catch (_) { return null; }
196
- }
197
-
198
- // -- Table Management ---------------------------------
199
-
200
- /**
201
- * Create a table (register schema + initialize index).
202
- * @param {string} table - Table name.
203
- * @param {object} [schema] - Schema definition.
204
- */
205
- async createTable(table, schema)
206
- {
207
- this._validateKey(table, 'table name');
208
- if (schema)
209
- {
210
- this._schemas.set(table, schema);
211
- await this._client.set(this._schemaKey(table), JSON.stringify(schema));
212
- }
213
- // Ensure the sequence key exists
214
- const exists = await this._client.exists(this._seqKey(table));
215
- if (!exists) await this._client.set(this._seqKey(table), '0');
216
- }
217
-
218
- /**
219
- * Drop a table (delete all keys).
220
- * @param {string} table - Table name.
221
- */
222
- async dropTable(table)
223
- {
224
- // Get all row IDs
225
- const ids = await this._client.zrange(this._idsKey(table), 0, -1);
226
- const pipeline = this._client.pipeline();
227
-
228
- for (const id of ids)
229
- {
230
- pipeline.del(this._rowKey(table, id));
231
- }
232
- pipeline.del(this._idsKey(table));
233
- pipeline.del(this._seqKey(table));
234
- pipeline.del(this._schemaKey(table));
235
-
236
- // Delete any field index keys
237
- const schema = this._schemas.get(table);
238
- if (schema)
239
- {
240
- for (const col of Object.keys(schema))
241
- {
242
- pipeline.del(this._key(table, 'idx', col));
243
- }
244
- }
245
-
246
- await pipeline.exec();
247
- this._schemas.delete(table);
248
- this._indexes.delete(table);
249
- }
250
-
251
- // -- CRUD Operations ----------------------------------
252
-
253
- /**
254
- * Insert a row.
255
- * @param {string} table - Table name.
256
- * @param {object} data - Record data object.
257
- * @returns {Promise<object>} Inserted row with ID.
258
- */
259
- async insert(table, data)
260
- {
261
- const row = { ...data };
262
-
263
- // Auto-increment if no ID provided
264
- if (row.id === undefined || row.id === null)
265
- {
266
- row.id = await this._client.incr(this._seqKey(table));
267
- }
268
- else
269
- {
270
- // Ensure sequence is ahead of manual IDs
271
- const current = parseInt(await this._client.get(this._seqKey(table)) || '0', 10);
272
- if (typeof row.id === 'number' && row.id >= current)
273
- {
274
- await this._client.set(this._seqKey(table), String(row.id + 1));
275
- }
276
- }
277
-
278
- // Serialize dates
279
- for (const [k, v] of Object.entries(row))
280
- {
281
- if (v instanceof Date) row[k] = v.toISOString();
282
- }
283
-
284
- // Enforce unique constraints
285
- await this._enforceUnique(table, row);
286
-
287
- // Store the row as a JSON string
288
- const pipeline = this._client.pipeline();
289
- pipeline.set(this._rowKey(table, row.id), this._serialize(row));
290
- // Add to sorted set index (score = numeric id for ordering)
291
- pipeline.zadd(this._idsKey(table), Number(row.id) || 0, String(row.id));
292
-
293
- await pipeline.exec();
294
-
295
- return row;
296
- }
297
-
298
- /**
299
- * Insert multiple rows.
300
- * @param {string} table - Table name.
301
- * @param {object[]} dataArray - Array of record objects.
302
- * @returns {Promise<object[]>} Array of inserted rows.
303
- */
304
- async insertMany(table, dataArray)
305
- {
306
- const results = [];
307
- for (const data of dataArray) results.push(await this.insert(table, data));
308
- return results;
309
- }
310
-
311
- /**
312
- * Update a row by primary key.
313
- * @param {string} table - Table name.
314
- * @param {string} pk - Primary key column name.
315
- * @param {*} pkVal - Primary key value.
316
- * @param {object} data - Record data object.
317
- */
318
- async update(table, pk, pkVal, data)
319
- {
320
- const key = this._rowKey(table, pkVal);
321
- const existing = this._deserialize(await this._client.get(key));
322
- if (!existing) return;
323
-
324
- for (const [k, v] of Object.entries(data))
325
- {
326
- existing[k] = v instanceof Date ? v.toISOString() : v;
327
- }
328
-
329
- await this._client.set(key, this._serialize(existing));
330
- }
331
-
332
- /**
333
- * Update all rows matching conditions.
334
- * @param {string} table - Table name.
335
- * @param {object} conditions - Filter conditions.
336
- * @param {object} data - Record data object.
337
- * @returns {Promise<number>} Number of updated rows.
338
- */
339
- async updateWhere(table, conditions, data)
340
- {
341
- const rows = await this._getAllRows(table);
342
- let count = 0;
343
-
344
- const pipeline = this._client.pipeline();
345
- for (const row of rows)
346
- {
347
- if (this._matchConditions(row, conditions))
348
- {
349
- for (const [k, v] of Object.entries(data))
350
- {
351
- row[k] = v instanceof Date ? v.toISOString() : v;
352
- }
353
- pipeline.set(this._rowKey(table, row.id), this._serialize(row));
354
- count++;
355
- }
356
- }
357
- if (count > 0) await pipeline.exec();
358
- return count;
359
- }
360
-
361
- /**
362
- * Remove a row by primary key.
363
- * @param {string} table - Table name.
364
- * @param {string} pk - Primary key column name.
365
- * @param {*} pkVal - Primary key value.
366
- */
367
- async remove(table, pk, pkVal)
368
- {
369
- const pipeline = this._client.pipeline();
370
- pipeline.del(this._rowKey(table, pkVal));
371
- pipeline.zrem(this._idsKey(table), String(pkVal));
372
- await pipeline.exec();
373
- }
374
-
375
- /**
376
- * Delete all rows matching conditions.
377
- * @param {string} table - Table name.
378
- * @param {object} conditions - Filter conditions.
379
- * @returns {Promise<number>} Number of deleted rows.
380
- */
381
- async deleteWhere(table, conditions)
382
- {
383
- const rows = await this._getAllRows(table);
384
- let count = 0;
385
-
386
- const pipeline = this._client.pipeline();
387
- for (const row of rows)
388
- {
389
- if (this._matchConditions(row, conditions))
390
- {
391
- pipeline.del(this._rowKey(table, row.id));
392
- pipeline.zrem(this._idsKey(table), String(row.id));
393
- count++;
394
- }
395
- }
396
- if (count > 0) await pipeline.exec();
397
- return count;
398
- }
399
-
400
- // -- Query Execution ----------------------------------
401
-
402
- /**
403
- * Execute a query descriptor (from the Query builder).
404
- * @param {object} descriptor - Query descriptor object.
405
- * @returns {Promise<Array|number>} Matching rows, or count if action is `'count'`.
406
- */
407
- async execute(descriptor)
408
- {
409
- const { action, table, fields, where, orderBy, limit, offset, distinct, groupBy, having } = descriptor;
410
- let rows = await this._getAllRows(table);
411
-
412
- // Apply WHERE filters
413
- if (where && where.length > 0)
414
- {
415
- rows = rows.filter(row => this._applyWhereChain(row, where));
416
- }
417
-
418
- // Count action
419
- if (action === 'count') return rows.length;
420
-
421
- // GROUP BY
422
- if (groupBy && groupBy.length > 0)
423
- {
424
- const groups = new Map();
425
- for (const row of rows)
426
- {
427
- const key = groupBy.map(f => row[f]).join('\0');
428
- if (!groups.has(key)) groups.set(key, { _key: {}, _rows: [] });
429
- const g = groups.get(key);
430
- for (const f of groupBy) g._key[f] = row[f];
431
- g._rows.push(row);
432
- }
433
- rows = [];
434
- for (const g of groups.values())
435
- {
436
- const row = { ...g._key };
437
- row._groupRows = g._rows;
438
- rows.push(row);
439
- }
440
-
441
- // HAVING
442
- if (having && having.length > 0)
443
- {
444
- rows = rows.filter(row =>
445
- {
446
- for (const h of having)
447
- {
448
- let actual;
449
- if (h.field === 'COUNT(*)' || h.field.startsWith('COUNT'))
450
- {
451
- actual = row._groupRows.length;
452
- }
453
- else
454
- {
455
- actual = row[h.field];
456
- }
457
- if (!this._compareOp(actual, h.op, h.value)) return false;
458
- }
459
- return true;
460
- });
461
- }
462
-
463
- for (const row of rows) delete row._groupRows;
464
- }
465
-
466
- // ORDER BY
467
- if (orderBy && orderBy.length > 0)
468
- {
469
- rows.sort((a, b) =>
470
- {
471
- for (const { field, dir } of orderBy)
472
- {
473
- const av = a[field], bv = b[field];
474
- if (av < bv) return dir === 'ASC' ? -1 : 1;
475
- if (av > bv) return dir === 'ASC' ? 1 : -1;
476
- }
477
- return 0;
478
- });
479
- }
480
-
481
- // OFFSET
482
- if (offset) rows = rows.slice(offset);
483
-
484
- // LIMIT
485
- if (limit) rows = rows.slice(0, limit);
486
-
487
- // SELECT specific fields
488
- if (fields && fields.length > 0)
489
- {
490
- rows = rows.map(row =>
491
- {
492
- const filtered = {};
493
- for (const f of fields) filtered[f] = row[f];
494
- return filtered;
495
- });
496
- }
497
-
498
- // DISTINCT
499
- if (distinct)
500
- {
501
- const seen = new Set();
502
- rows = rows.filter(row =>
503
- {
504
- const key = JSON.stringify(row);
505
- if (seen.has(key)) return false;
506
- seen.add(key);
507
- return true;
508
- });
509
- }
510
-
511
- return rows;
512
- }
513
-
514
- /**
515
- * Compute an aggregate value.
516
- * @param {object} descriptor - Query descriptor object.
517
- * @returns {Promise<number|null>} Computed aggregate value.
518
- */
519
- async aggregate(descriptor)
520
- {
521
- const { table, where, aggregateFn, aggregateField } = descriptor;
522
- let rows = await this._getAllRows(table);
523
- if (where && where.length > 0)
524
- {
525
- rows = rows.filter(row => this._applyWhereChain(row, where));
526
- }
527
- const fn = aggregateFn.toLowerCase();
528
- if (!rows.length) return (fn === 'count' || fn === 'avg' || fn === 'sum') ? 0 : null;
529
- switch (fn)
530
- {
531
- case 'sum': return rows.reduce((acc, r) => acc + (Number(r[aggregateField]) || 0), 0);
532
- case 'avg': return rows.reduce((acc, r) => acc + (Number(r[aggregateField]) || 0), 0) / rows.length;
533
- case 'min': return rows.reduce((m, r) => (r[aggregateField] < m ? r[aggregateField] : m), rows[0][aggregateField]);
534
- case 'max': return rows.reduce((m, r) => (r[aggregateField] > m ? r[aggregateField] : m), rows[0][aggregateField]);
535
- case 'count': return rows.length;
536
- default: return null;
537
- }
538
- }
539
-
540
- // -- Redis-Specific Operations ------------------------
541
-
542
- /**
543
- * Get a value by key (raw Redis GET).
544
- * @param {string} key - Cache or storage key.
545
- * @returns {Promise<string|null>} Stored value, or `null` if not found.
546
- */
547
- async get(key)
548
- {
549
- this._validateKey(key);
550
- return this._client.get(this._prefix + key);
551
- }
552
-
553
- /**
554
- * Set a key-value pair (raw Redis SET).
555
- * @param {string} key - Cache or storage key.
556
- * @param {*} value - Value to set.
557
- * @param {number} [ttl] - Optional TTL in seconds.
558
- * @returns {Promise<string>} Redis `"OK"` response.
559
- */
560
- async set(key, value, ttl)
561
- {
562
- this._validateKey(key);
563
- if (ttl !== undefined && (!Number.isFinite(ttl) || ttl < 0))
564
- throw new Error('Redis: TTL must be a non-negative number');
565
- const k = this._prefix + key;
566
- const v = typeof value === 'object' ? JSON.stringify(value) : String(value);
567
- if (ttl) return this._client.setex(k, ttl, v);
568
- return this._client.set(k, v);
569
- }
570
-
571
- /**
572
- * Delete a key.
573
- * @param {string} key - Cache or storage key.
574
- * @returns {Promise<number>} Number of keys deleted (0 or 1).
575
- */
576
- async del(key)
577
- {
578
- this._validateKey(key);
579
- return this._client.del(this._prefix + key);
580
- }
581
-
582
- /**
583
- * Check if a key exists.
584
- * @param {string} key - Cache or storage key.
585
- * @returns {Promise<boolean>} `true` if the key exists.
586
- */
587
- async exists(key)
588
- {
589
- this._validateKey(key);
590
- return (await this._client.exists(this._prefix + key)) === 1;
591
- }
592
-
593
- /**
594
- * Set expiration on a key.
595
- * @param {string} key - Cache or storage key.
596
- * @param {number} seconds - Time in seconds.
597
- * @returns {Promise<number>} `1` if timeout was set, `0` if key does not exist.
598
- */
599
- async expire(key, seconds)
600
- {
601
- this._validateKey(key);
602
- if (!Number.isFinite(seconds) || seconds < 0)
603
- throw new Error('Redis: TTL must be a non-negative number');
604
- return this._client.expire(this._prefix + key, seconds);
605
- }
606
-
607
- /**
608
- * Get TTL of a key in seconds.
609
- * @param {string} key - Cache or storage key.
610
- * @returns {Promise<number>} -1 if no expiry, -2 if key doesn't exist.
611
- */
612
- async ttl(key)
613
- {
614
- this._validateKey(key);
615
- return this._client.ttl(this._prefix + key);
616
- }
617
-
618
- /**
619
- * Increment a numeric key.
620
- * @param {string} key - Cache or storage key.
621
- * @param {number} [by=1] - Increment step.
622
- * @returns {Promise<number>} Value after increment.
623
- */
624
- async incr(key, by = 1)
625
- {
626
- this._validateKey(key);
627
- if (by === 1) return this._client.incr(this._prefix + key);
628
- return this._client.incrby(this._prefix + key, by);
629
- }
630
-
631
- /**
632
- * Decrement a numeric key.
633
- * @param {string} key - Cache or storage key.
634
- * @param {number} [by=1] - Increment step.
635
- * @returns {Promise<number>} Value after decrement.
636
- */
637
- async decr(key, by = 1)
638
- {
639
- this._validateKey(key);
640
- if (by === 1) return this._client.decr(this._prefix + key);
641
- return this._client.decrby(this._prefix + key, by);
642
- }
643
-
644
- // -- Hash Operations ----------------------------------
645
-
646
- /**
647
- * Set a hash field.
648
- * @param {string} key - Cache or storage key.
649
- * @param {string} field - Field name.
650
- * @param {*} value - Value to set.
651
- * @returns {Promise<number>} `1` if field is new, `0` if updated.
652
- */
653
- async hset(key, field, value)
654
- {
655
- this._validateKey(key);
656
- return this._client.hset(this._prefix + key, field, typeof value === 'object' ? JSON.stringify(value) : String(value));
657
- }
658
-
659
- /**
660
- * Get a hash field.
661
- * @param {string} key - Cache or storage key.
662
- * @param {string} field - Field name.
663
- * @returns {Promise<string|null>} Field value, or `null` if not found.
664
- */
665
- async hget(key, field)
666
- {
667
- this._validateKey(key);
668
- return this._client.hget(this._prefix + key, field);
669
- }
670
-
671
- /**
672
- * Get all fields in a hash.
673
- * @param {string} key - Cache or storage key.
674
- * @returns {Promise<object>} Object of field-value pairs.
675
- */
676
- async hgetall(key)
677
- {
678
- this._validateKey(key);
679
- return this._client.hgetall(this._prefix + key);
680
- }
681
-
682
- /**
683
- * Delete a hash field.
684
- * @param {string} key - Cache or storage key.
685
- * @param {string} field - Field name.
686
- * @returns {Promise<number>} `1` if the field was removed, `0` if it did not exist.
687
- */
688
- async hdel(key, field)
689
- {
690
- this._validateKey(key);
691
- return this._client.hdel(this._prefix + key, field);
692
- }
693
-
694
- // -- List Operations ----------------------------------
695
-
696
- /**
697
- * Push values to the end of a list.
698
- * @param {string} key - Cache or storage key.
699
- * @param {...*} values - Array of values.
700
- * @returns {Promise<number>} Length of list after push.
701
- */
702
- async rpush(key, ...values)
703
- {
704
- this._validateKey(key);
705
- return this._client.rpush(this._prefix + key, ...values.map(v => typeof v === 'object' ? JSON.stringify(v) : String(v)));
706
- }
707
-
708
- /**
709
- * Push values to the beginning of a list.
710
- * @param {string} key - Cache or storage key.
711
- * @param {...*} values - Array of values.
712
- * @returns {Promise<number>} Length of list after push.
713
- */
714
- async lpush(key, ...values)
715
- {
716
- this._validateKey(key);
717
- return this._client.lpush(this._prefix + key, ...values.map(v => typeof v === 'object' ? JSON.stringify(v) : String(v)));
718
- }
719
-
720
- /**
721
- * Get a range of list elements.
722
- * @param {string} key - Cache or storage key.
723
- * @param {number} [start=0] - Start offset.
724
- * @param {number} [stop=-1] - Stop offset.
725
- * @returns {Promise<string[]>} Array of list elements.
726
- */
727
- async lrange(key, start = 0, stop = -1)
728
- {
729
- this._validateKey(key);
730
- return this._client.lrange(this._prefix + key, start, stop);
731
- }
732
-
733
- /**
734
- * Pop from the end of a list.
735
- * @param {string} key - Cache or storage key.
736
- * @returns {Promise<string|null>} Removed element, or `null` if empty.
737
- */
738
- async rpop(key)
739
- {
740
- this._validateKey(key);
741
- return this._client.rpop(this._prefix + key);
742
- }
743
-
744
- /**
745
- * Pop from the beginning of a list.
746
- * @param {string} key - Cache or storage key.
747
- * @returns {Promise<string|null>} Removed element, or `null` if empty.
748
- */
749
- async lpop(key)
750
- {
751
- this._validateKey(key);
752
- return this._client.lpop(this._prefix + key);
753
- }
754
-
755
- /**
756
- * Get list length.
757
- * @param {string} key - Cache or storage key.
758
- * @returns {Promise<number>} Number of elements in the list.
759
- */
760
- async llen(key)
761
- {
762
- this._validateKey(key);
763
- return this._client.llen(this._prefix + key);
764
- }
765
-
766
- // -- Set Operations -----------------------------------
767
-
768
- /**
769
- * Add members to a set.
770
- * @param {string} key - Cache or storage key.
771
- * @param {...*} members - Array of set members.
772
- * @returns {Promise<number>} Number of members actually added.
773
- */
774
- async sadd(key, ...members)
775
- {
776
- this._validateKey(key);
777
- return this._client.sadd(this._prefix + key, ...members.map(String));
778
- }
779
-
780
- /**
781
- * Get all members of a set.
782
- * @param {string} key - Cache or storage key.
783
- * @returns {Promise<string[]>} Array of set members.
784
- */
785
- async smembers(key)
786
- {
787
- this._validateKey(key);
788
- return this._client.smembers(this._prefix + key);
789
- }
790
-
791
- /**
792
- * Check if a value is a member of a set.
793
- * @param {string} key - Cache or storage key.
794
- * @param {*} member - Set member.
795
- * @returns {Promise<boolean>} `true` if the value is a member.
796
- */
797
- async sismember(key, member)
798
- {
799
- this._validateKey(key);
800
- return (await this._client.sismember(this._prefix + key, String(member))) === 1;
801
- }
802
-
803
- /**
804
- * Remove a member from a set.
805
- * @param {string} key - Cache or storage key.
806
- * @param {*} member - Set member.
807
- * @returns {Promise<number>} `1` if the member was removed, `0` otherwise.
808
- */
809
- async srem(key, member)
810
- {
811
- this._validateKey(key);
812
- return this._client.srem(this._prefix + key, String(member));
813
- }
814
-
815
- /**
816
- * Get the number of members in a set.
817
- * @param {string} key - Cache or storage key.
818
- * @returns {Promise<number>} Number of members in the set.
819
- */
820
- async scard(key)
821
- {
822
- this._validateKey(key);
823
- return this._client.scard(this._prefix + key);
824
- }
825
-
826
- // -- Sorted Set Operations ----------------------------
827
-
828
- /**
829
- * Add a member to a sorted set.
830
- * @param {string} key - Cache or storage key.
831
- * @param {number} score - Sort score.
832
- * @param {*} member - Set member.
833
- * @returns {Promise<number>} Number of members actually added.
834
- */
835
- async zadd(key, score, member)
836
- {
837
- this._validateKey(key);
838
- return this._client.zadd(this._prefix + key, score, String(member));
839
- }
840
-
841
- /**
842
- * Get members from a sorted set by score range.
843
- * @param {string} key - Cache or storage key.
844
- * @param {number|string} min - Minimum value.
845
- * @param {number|string} max - Maximum value.
846
- * @returns {Promise<string[]>} Array of matching members.
847
- */
848
- async zrangebyscore(key, min, max)
849
- {
850
- this._validateKey(key);
851
- return this._client.zrangebyscore(this._prefix + key, min, max);
852
- }
853
-
854
- /**
855
- * Get members from a sorted set by rank range.
856
- * @param {string} key - Cache or storage key.
857
- * @param {number} start - Start offset.
858
- * @param {number} stop - Stop offset.
859
- * @returns {Promise<string[]>} Array of members in rank order.
860
- */
861
- async zrange(key, start, stop)
862
- {
863
- this._validateKey(key);
864
- return this._client.zrange(this._prefix + key, start, stop);
865
- }
866
-
867
- /**
868
- * Remove a member from a sorted set.
869
- * @param {string} key - Cache or storage key.
870
- * @param {*} member - Set member.
871
- * @returns {Promise<number>} Number of members removed.
872
- */
873
- async zrem(key, member)
874
- {
875
- this._validateKey(key);
876
- return this._client.zrem(this._prefix + key, String(member));
877
- }
878
-
879
- /**
880
- * Get sorted set cardinality.
881
- * @param {string} key - Cache or storage key.
882
- * @returns {Promise<number>} Number of members in the sorted set.
883
- */
884
- async zcard(key)
885
- {
886
- this._validateKey(key);
887
- return this._client.zcard(this._prefix + key);
888
- }
889
-
890
- // -- Pub/Sub ------------------------------------------
891
-
892
- /**
893
- * Subscribe to a channel.
894
- * @param {string} channel - Channel name.
895
- * @param {Function} callback - Called with (message, channel).
896
- * @returns {Promise<Function>} Unsubscribe function.
897
- */
898
- async subscribe(channel, callback)
899
- {
900
- this._validateKey(channel, 'channel');
901
- if (typeof callback !== 'function')
902
- throw new Error('Redis: subscribe callback must be a function');
903
- if (!this._subClient)
904
- {
905
- this._subClient = this._client.duplicate();
906
- }
907
-
908
- const prefixedChannel = this._prefix + channel;
909
- await this._subClient.subscribe(prefixedChannel);
910
-
911
- const handler = (ch, message) =>
912
- {
913
- if (ch === prefixedChannel) callback(message, channel);
914
- };
915
- this._subClient.on('message', handler);
916
-
917
- if (!this._subscribers.has(prefixedChannel))
918
- {
919
- this._subscribers.set(prefixedChannel, []);
920
- }
921
- this._subscribers.get(prefixedChannel).push({ callback, handler });
922
-
923
- // Return unsubscribe function
924
- return async () =>
925
- {
926
- this._subClient.removeListener('message', handler);
927
- const subs = this._subscribers.get(prefixedChannel) || [];
928
- const idx = subs.findIndex(s => s.callback === callback);
929
- if (idx !== -1) subs.splice(idx, 1);
930
- if (subs.length === 0)
931
- {
932
- await this._subClient.unsubscribe(prefixedChannel);
933
- this._subscribers.delete(prefixedChannel);
934
- }
935
- };
936
- }
937
-
938
- /**
939
- * Publish a message to a channel.
940
- * @param {string} channel - Channel name.
941
- * @param {*} message - Message payload.
942
- * @returns {Promise<number>} Number of subscribers that received the message.
943
- */
944
- async publish(channel, message)
945
- {
946
- this._validateKey(channel, 'channel');
947
- const msg = typeof message === 'object' ? JSON.stringify(message) : String(message);
948
- return this._client.publish(this._prefix + channel, msg);
949
- }
950
-
951
- // -- Pipeline / Batch ---------------------------------
952
-
953
- /**
954
- * Create a pipeline for batching commands.
955
- * @returns {Pipeline} Prefixed pipeline wrapper.
956
- *
957
- * @example
958
- * const pipe = adapter.pipeline();
959
- * pipe.set('key1', 'val1');
960
- * pipe.set('key2', 'val2');
961
- * const results = await pipe.exec();
962
- */
963
- pipeline()
964
- {
965
- const pipe = this._client.pipeline();
966
- const adapter = this;
967
-
968
- // Wrap to add prefix
969
- return {
970
- set(key, value, ...args)
971
- {
972
- pipe.set(adapter._prefix + key, typeof value === 'object' ? JSON.stringify(value) : String(value), ...args);
973
- return this;
974
- },
975
- get(key) { pipe.get(adapter._prefix + key); return this; },
976
- del(key) { pipe.del(adapter._prefix + key); return this; },
977
- hset(key, field, value)
978
- {
979
- pipe.hset(adapter._prefix + key, field, typeof value === 'object' ? JSON.stringify(value) : String(value));
980
- return this;
981
- },
982
- hget(key, field) { pipe.hget(adapter._prefix + key, field); return this; },
983
- incr(key) { pipe.incr(adapter._prefix + key); return this; },
984
- decr(key) { pipe.decr(adapter._prefix + key); return this; },
985
- expire(key, seconds) { pipe.expire(adapter._prefix + key, seconds); return this; },
986
- sadd(key, ...members) { pipe.sadd(adapter._prefix + key, ...members.map(String)); return this; },
987
- rpush(key, ...values) { pipe.rpush(adapter._prefix + key, ...values.map(v => typeof v === 'object' ? JSON.stringify(v) : String(v))); return this; },
988
- async exec() { return pipe.exec(); },
989
- };
990
- }
991
-
992
- // -- Transaction Support ------------------------------
993
-
994
- /**
995
- * Begin a Redis MULTI transaction.
996
- */
997
- async beginTransaction()
998
- {
999
- this._multi = this._client.multi();
1000
- }
1001
-
1002
- /**
1003
- * Commit a MULTI transaction.
1004
- */
1005
- async commit()
1006
- {
1007
- if (this._multi)
1008
- {
1009
- await this._multi.exec();
1010
- this._multi = null;
1011
- }
1012
- }
1013
-
1014
- /**
1015
- * Discard a MULTI transaction.
1016
- */
1017
- async rollback()
1018
- {
1019
- if (this._multi)
1020
- {
1021
- this._multi.discard();
1022
- this._multi = null;
1023
- }
1024
- }
1025
-
1026
- // -- Utility & Admin ----------------------------------
1027
-
1028
- /**
1029
- * Clear all data (flush matched prefix keys).
1030
- * Uses SCAN for safety in production (no KEYS *).
1031
- */
1032
- async clear()
1033
- {
1034
- let cursor = '0';
1035
- do
1036
- {
1037
- const [nextCursor, keys] = await this._client.scan(cursor, 'MATCH', this._prefix + '*', 'COUNT', 100);
1038
- cursor = nextCursor;
1039
- if (keys.length > 0)
1040
- {
1041
- await this._client.del(...keys);
1042
- }
1043
- } while (cursor !== '0');
1044
- }
1045
-
1046
- /**
1047
- * Ping the Redis server.
1048
- * @returns {Promise<boolean>} `true` if the server responds.
1049
- */
1050
- async ping()
1051
- {
1052
- try
1053
- {
1054
- const result = await this._client.ping();
1055
- return result === 'PONG';
1056
- }
1057
- catch (_)
1058
- {
1059
- return false;
1060
- }
1061
- }
1062
-
1063
- /**
1064
- * Get Redis server info.
1065
- * @param {string} [section] - Optional section (e.g., 'memory', 'clients', 'stats').
1066
- * @returns {Promise<string>} Raw Redis INFO output.
1067
- */
1068
- async info(section)
1069
- {
1070
- return section ? this._client.info(section) : this._client.info();
1071
- }
1072
-
1073
- /**
1074
- * Get database size (number of keys).
1075
- * @returns {Promise<number>} Total number of keys in the database.
1076
- */
1077
- async dbsize()
1078
- {
1079
- return this._client.dbsize();
1080
- }
1081
-
1082
- /**
1083
- * List all table names (by scanning for schema keys).
1084
- * @returns {Promise<string[]>} Array of table names.
1085
- */
1086
- async tables()
1087
- {
1088
- const tables = [];
1089
- let cursor = '0';
1090
- const pattern = this._prefix + '*:_schema';
1091
- do
1092
- {
1093
- const [nextCursor, keys] = await this._client.scan(cursor, 'MATCH', pattern, 'COUNT', 100);
1094
- cursor = nextCursor;
1095
- for (const key of keys)
1096
- {
1097
- // Extract table name: zh:users:_schema → users
1098
- const stripped = key.slice(this._prefix.length);
1099
- const table = stripped.replace(/:_schema$/, '');
1100
- tables.push(table);
1101
- }
1102
- } while (cursor !== '0');
1103
- return tables;
1104
- }
1105
-
1106
- /**
1107
- * Get stats for the adapter.
1108
- * @returns {Promise<object>} Adapter statistics.
1109
- */
1110
- async stats()
1111
- {
1112
- const tableNames = await this.tables();
1113
- let totalRows = 0;
1114
- for (const t of tableNames)
1115
- {
1116
- totalRows += await this._client.zcard(this._idsKey(t));
1117
- }
1118
- return {
1119
- tables: tableNames.length,
1120
- totalRows,
1121
- dbsize: await this._client.dbsize(),
1122
- prefix: this._prefix,
1123
- };
1124
- }
1125
-
1126
- /**
1127
- * Get pool/connection status.
1128
- * @returns {{ status: string, prefix: string }}
1129
- */
1130
- poolStatus()
1131
- {
1132
- return {
1133
- status: this._client.status,
1134
- prefix: this._prefix,
1135
- };
1136
- }
1137
-
1138
- /**
1139
- * Get the underlying ioredis client.
1140
- * @returns {object} The ioredis client instance.
1141
- */
1142
- get client()
1143
- {
1144
- return this._client;
1145
- }
1146
-
1147
- /**
1148
- * Execute a raw Redis command.
1149
- * @param {string} command - Command name.
1150
- * @param {...*} args - Command arguments.
1151
- * @returns {Promise<*>} Command result.
1152
- */
1153
- async raw(command, ...args)
1154
- {
1155
- if (typeof command !== 'string' || command.length === 0)
1156
- throw new Error('Redis: command must be a non-empty string');
1157
- return this._client.call(command, ...args);
1158
- }
1159
-
1160
- /**
1161
- * Close the connection.
1162
- */
1163
- async close()
1164
- {
1165
- if (this._subClient)
1166
- {
1167
- await this._subClient.quit();
1168
- this._subClient = null;
1169
- }
1170
- await this._client.quit();
1171
- }
1172
-
1173
- // -- Migration / DDL Methods --------------------------
1174
-
1175
- /**
1176
- * Add a column to an existing table.
1177
- * @param {string} table - Table name.
1178
- * @param {string} column - Column name.
1179
- * @param {object} def - Column definition.
1180
- */
1181
- async addColumn(table, column, def)
1182
- {
1183
- const schema = this._schemas.get(table);
1184
- if (schema) schema[column] = def;
1185
-
1186
- const defaultVal = def.default !== undefined
1187
- ? (typeof def.default === 'function' ? def.default() : def.default)
1188
- : null;
1189
-
1190
- // Update all existing rows
1191
- const rows = await this._getAllRows(table);
1192
- const pipeline = this._client.pipeline();
1193
- for (const row of rows)
1194
- {
1195
- if (row[column] === undefined)
1196
- {
1197
- row[column] = defaultVal;
1198
- pipeline.set(this._rowKey(table, row.id), this._serialize(row));
1199
- }
1200
- }
1201
- if (rows.length > 0) await pipeline.exec();
1202
-
1203
- // Update stored schema
1204
- await this._client.set(this._schemaKey(table), JSON.stringify(this._schemas.get(table) || {}));
1205
- }
1206
-
1207
- /**
1208
- * Drop a column from a table.
1209
- * @param {string} table - Table name.
1210
- * @param {string} column - Column name.
1211
- */
1212
- async dropColumn(table, column)
1213
- {
1214
- const schema = this._schemas.get(table);
1215
- if (schema) delete schema[column];
1216
-
1217
- const rows = await this._getAllRows(table);
1218
- const pipeline = this._client.pipeline();
1219
- for (const row of rows)
1220
- {
1221
- delete row[column];
1222
- pipeline.set(this._rowKey(table, row.id), this._serialize(row));
1223
- }
1224
- if (rows.length > 0) await pipeline.exec();
1225
- }
1226
-
1227
- /**
1228
- * Rename a column.
1229
- * @param {string} table - Table name.
1230
- * @param {string} oldName - Current name.
1231
- * @param {string} newName - New name.
1232
- */
1233
- async renameColumn(table, oldName, newName)
1234
- {
1235
- const schema = this._schemas.get(table);
1236
- if (schema && schema[oldName])
1237
- {
1238
- schema[newName] = schema[oldName];
1239
- delete schema[oldName];
1240
- }
1241
-
1242
- const rows = await this._getAllRows(table);
1243
- const pipeline = this._client.pipeline();
1244
- for (const row of rows)
1245
- {
1246
- if (oldName in row)
1247
- {
1248
- row[newName] = row[oldName];
1249
- delete row[oldName];
1250
- pipeline.set(this._rowKey(table, row.id), this._serialize(row));
1251
- }
1252
- }
1253
- if (rows.length > 0) await pipeline.exec();
1254
- }
1255
-
1256
- /**
1257
- * Rename a table.
1258
- * @param {string} oldName - Current name.
1259
- * @param {string} newName - New name.
1260
- */
1261
- async renameTable(oldName, newName)
1262
- {
1263
- const rows = await this._getAllRows(oldName);
1264
-
1265
- // Create new table with all rows
1266
- const schema = this._schemas.get(oldName);
1267
- if (schema)
1268
- {
1269
- this._schemas.set(newName, schema);
1270
- this._schemas.delete(oldName);
1271
- }
1272
-
1273
- const pipeline = this._client.pipeline();
1274
-
1275
- // Copy sequence
1276
- const seq = await this._client.get(this._seqKey(oldName));
1277
- pipeline.set(this._seqKey(newName), seq || '0');
1278
-
1279
- // Copy rows to new keys
1280
- for (const row of rows)
1281
- {
1282
- pipeline.set(this._rowKey(newName, row.id), this._serialize(row));
1283
- pipeline.zadd(this._idsKey(newName), Number(row.id) || 0, String(row.id));
1284
- }
1285
-
1286
- // Store new schema
1287
- if (schema)
1288
- {
1289
- pipeline.set(this._schemaKey(newName), JSON.stringify(schema));
1290
- }
1291
-
1292
- await pipeline.exec();
1293
-
1294
- // Drop old table
1295
- await this.dropTable(oldName);
1296
- }
1297
-
1298
- /**
1299
- * Create an index (tracked in metadata).
1300
- * @param {string} table - Table name.
1301
- * @param {string|string[]} columns - Column name(s).
1302
- * @param {{ name?: string, unique?: boolean }} [options={}]
1303
- */
1304
- async createIndex(table, columns, options = {})
1305
- {
1306
- const cols = Array.isArray(columns) ? columns : [columns];
1307
- const name = options.name || `idx_${table}_${cols.join('_')}`;
1308
- if (!this._indexes.has(table)) this._indexes.set(table, []);
1309
- this._indexes.get(table).push({ name, columns: cols, unique: !!options.unique });
1310
- }
1311
-
1312
- /**
1313
- * Drop an index.
1314
- * @param {string} _table - Table name (unused).
1315
- * @param {string} name - Name identifier.
1316
- */
1317
- async dropIndex(_table, name)
1318
- {
1319
- for (const [, indexes] of this._indexes)
1320
- {
1321
- const idx = indexes.findIndex(i => i.name === name);
1322
- if (idx !== -1) { indexes.splice(idx, 1); return; }
1323
- }
1324
- }
1325
-
1326
- /**
1327
- * Check if a table exists.
1328
- * @param {string} table - Table name.
1329
- * @returns {Promise<boolean>} `true` if the table exists.
1330
- */
1331
- async hasTable(table)
1332
- {
1333
- return (await this._client.exists(this._seqKey(table))) === 1 ||
1334
- (await this._client.exists(this._schemaKey(table))) === 1;
1335
- }
1336
-
1337
- /**
1338
- * Check if a column exists on a table.
1339
- * @param {string} table - Table name.
1340
- * @param {string} column - Column name.
1341
- * @returns {Promise<boolean>} `true` if the column exists.
1342
- */
1343
- async hasColumn(table, column)
1344
- {
1345
- const schema = this._schemas.get(table);
1346
- if (schema) return column in schema;
1347
- // Check first row
1348
- const ids = await this._client.zrange(this._idsKey(table), 0, 0);
1349
- if (ids.length === 0) return false;
1350
- const row = this._deserialize(await this._client.get(this._rowKey(table, ids[0])));
1351
- return row ? column in row : false;
1352
- }
1353
-
1354
- /**
1355
- * Describe a table's columns.
1356
- * @param {string} table - Table name.
1357
- * @returns {Promise<Array>} Array of column definitions.
1358
- */
1359
- async describeTable(table)
1360
- {
1361
- const schema = this._schemas.get(table);
1362
- if (!schema) return [];
1363
- return Object.entries(schema).map(([name, def]) => ({
1364
- name,
1365
- type: def.type || 'TEXT',
1366
- nullable: !def.required,
1367
- defaultValue: def.default !== undefined ? def.default : null,
1368
- primaryKey: !!def.primaryKey,
1369
- }));
1370
- }
1371
-
1372
- /**
1373
- * Get indexes for a table.
1374
- * @param {string} table - Table name.
1375
- * @returns {Promise<Array>} Array of index definitions.
1376
- */
1377
- async indexes(table)
1378
- {
1379
- return this._indexes.get(table) || [];
1380
- }
1381
-
1382
- // -- Internal Helpers ---------------------------------
1383
-
1384
- /**
1385
- * Get all rows for a table.
1386
- * @private
1387
- * @param {string} table - Table name.
1388
- * @returns {Promise<object[]>} All rows in the table.
1389
- */
1390
- async _getAllRows(table)
1391
- {
1392
- const ids = await this._client.zrange(this._idsKey(table), 0, -1);
1393
- if (ids.length === 0) return [];
1394
-
1395
- const pipeline = this._client.pipeline();
1396
- for (const id of ids)
1397
- {
1398
- pipeline.get(this._rowKey(table, id));
1399
- }
1400
- const results = await pipeline.exec();
1401
- const rows = [];
1402
- for (const [err, val] of results)
1403
- {
1404
- if (!err && val)
1405
- {
1406
- const row = this._deserialize(val);
1407
- if (row) rows.push(row);
1408
- }
1409
- }
1410
- return rows;
1411
- }
1412
-
1413
- /** @private Match simple conditions. */
1414
- _matchConditions(row, conditions)
1415
- {
1416
- if (!conditions || typeof conditions !== 'object') return true;
1417
- for (const [k, v] of Object.entries(conditions))
1418
- {
1419
- if (row[k] !== v) return false;
1420
- }
1421
- return true;
1422
- }
1423
-
1424
- /** @private Apply the where chain from query builder. */
1425
- _applyWhereChain(row, where)
1426
- {
1427
- let result = true;
1428
- for (let i = 0; i < where.length; i++)
1429
- {
1430
- const clause = where[i];
1431
- if (clause.raw) continue;
1432
- const matches = this._matchClause(row, clause);
1433
-
1434
- if (i === 0 || clause.logic === 'AND')
1435
- {
1436
- result = i === 0 ? matches : (result && matches);
1437
- }
1438
- else if (clause.logic === 'OR')
1439
- {
1440
- result = result || matches;
1441
- }
1442
- }
1443
- return result;
1444
- }
1445
-
1446
- /** @private Match a single WHERE clause. */
1447
- _matchClause(row, clause)
1448
- {
1449
- const val = row[clause.field];
1450
- const { op, value } = clause;
1451
-
1452
- switch (op)
1453
- {
1454
- case '=': return val === value;
1455
- case '!=':
1456
- case '<>': return val !== value;
1457
- case '>': return val > value;
1458
- case '<': return val < value;
1459
- case '>=': return val >= value;
1460
- case '<=': return val <= value;
1461
- case 'LIKE': return _likeSafe(String(val), String(value));
1462
- case 'IN': return Array.isArray(value) && value.includes(val);
1463
- case 'NOT IN': return Array.isArray(value) && !value.includes(val);
1464
- case 'BETWEEN': return Array.isArray(value) && val >= value[0] && val <= value[1];
1465
- case 'NOT BETWEEN': return Array.isArray(value) && (val < value[0] || val > value[1]);
1466
- case 'IS NULL': return val === null || val === undefined;
1467
- case 'IS NOT NULL': return val !== null && val !== undefined;
1468
- default: return val === value;
1469
- }
1470
- }
1471
-
1472
- /** @private Compare for HAVING. */
1473
- _compareOp(actual, op, value)
1474
- {
1475
- switch (op.toUpperCase())
1476
- {
1477
- case '=': return actual === value;
1478
- case '!=':
1479
- case '<>': return actual !== value;
1480
- case '>': return actual > value;
1481
- case '<': return actual < value;
1482
- case '>=': return actual >= value;
1483
- case '<=': return actual <= value;
1484
- default: return actual === value;
1485
- }
1486
- }
1487
-
1488
- /** @private Enforce unique constraints. */
1489
- async _enforceUnique(table, row, excludeRow)
1490
- {
1491
- const schema = this._schemas.get(table);
1492
- if (!schema) return;
1493
-
1494
- const rows = await this._getAllRows(table);
1495
-
1496
- for (const [col, def] of Object.entries(schema))
1497
- {
1498
- if (def.unique && row[col] !== undefined && row[col] !== null)
1499
- {
1500
- const duplicate = rows.find(r =>
1501
- r !== excludeRow && r.id !== (excludeRow && excludeRow.id) && r[col] === row[col]
1502
- );
1503
- if (duplicate)
1504
- {
1505
- throw new Error(`UNIQUE constraint failed: ${table}.${col}`);
1506
- }
1507
- }
1508
- }
1509
-
1510
- // Composite unique
1511
- const groups = {};
1512
- for (const [col, def] of Object.entries(schema))
1513
- {
1514
- if (def.compositeUnique)
1515
- {
1516
- const g = typeof def.compositeUnique === 'string' ? def.compositeUnique : 'default';
1517
- if (!groups[g]) groups[g] = [];
1518
- groups[g].push(col);
1519
- }
1520
- }
1521
- for (const cols of Object.values(groups))
1522
- {
1523
- const duplicate = rows.find(r =>
1524
- r !== excludeRow && r.id !== (excludeRow && excludeRow.id) && cols.every(c => r[c] === row[c])
1525
- );
1526
- if (duplicate)
1527
- {
1528
- throw new Error(`UNIQUE constraint failed: ${table}.(${cols.join(', ')})`);
1529
- }
1530
- }
1531
- }
1532
- }
1533
-
1534
- module.exports = RedisAdapter;
1
+ /**
2
+ * @module orm/adapters/redis
3
+ * @description Redis database adapter for the zero-server ORM.
4
+ * Uses `ioredis` as the driver. Stores table data as Redis hashes
5
+ * with sorted-set indexes for ordering and filtering.
6
+ *
7
+ * Bring-your-own-driver: `npm install ioredis`
8
+ *
9
+ * Supports full ORM CRUD, key-value operations, pub/sub,
10
+ * pipelines, TTL, and all DDL/migration methods.
11
+ *
12
+ * @example
13
+ * // Connect by host/port
14
+ * const db = Database.connect('redis', { host: '127.0.0.1', port: 6379 });
15
+ *
16
+ * // Connect by URL with authentication
17
+ * const db2 = Database.connect('redis', { url: 'redis://user:pass@host:6379/0' });
18
+ *
19
+ * // Connect with key prefix
20
+ * const db3 = Database.connect('redis', { url: 'redis://host:6379', prefix: 'myapp:' });
21
+ */
22
+
23
+ let Redis;
24
+ try { Redis = require('ioredis'); } catch (_) { /* loaded lazily */ }
25
+
26
+ /**
27
+ * ReDoS-safe SQL LIKE matcher using iterative DP.
28
+ * % = any sequence of chars, _ = any single char. Case-insensitive.
29
+ * @private
30
+ */
31
+ function _likeSafe(str, pattern)
32
+ {
33
+ const s = str.toLowerCase();
34
+ const p = pattern.toLowerCase();
35
+ const sLen = s.length, pLen = p.length;
36
+ let dp = new Array(pLen + 1).fill(false);
37
+ dp[0] = true;
38
+ for (let j = 0; j < pLen; j++) { if (p[j] === '%') dp[j + 1] = dp[j]; }
39
+ for (let i = 1; i <= sLen; i++)
40
+ {
41
+ const next = new Array(pLen + 1).fill(false);
42
+ for (let j = 1; j <= pLen; j++)
43
+ {
44
+ if (p[j - 1] === '%') next[j] = dp[j] || next[j - 1];
45
+ else if (p[j - 1] === '_') next[j] = dp[j - 1];
46
+ else next[j] = dp[j - 1] && s[i - 1] === p[j - 1];
47
+ }
48
+ dp = next;
49
+ }
50
+ return dp[pLen];
51
+ }
52
+
53
+ class RedisAdapter
54
+ {
55
+ /**
56
+ * @constructor
57
+ * @param {object} [options] - Configuration options.
58
+ * @param {string} [options.url] - Redis connection URL.
59
+ * @param {string} [options.host='127.0.0.1'] - Redis host.
60
+ * @param {number} [options.port=6379] - Redis port.
61
+ * @param {string} [options.password] - Redis password.
62
+ * @param {number} [options.db=0] - Redis database index.
63
+ * @param {string} [options.prefix='zh:'] - Key prefix for namespacing.
64
+ * @param {number} [options.maxRetries=3] - Max connection retries.
65
+ * @param {boolean} [options.lazyConnect=false] - If true, defer connection until first operation.
66
+ * @param {object} [options.tls] - TLS options for secure connections.
67
+ * @param {string} [options.keyPrefix] - Alias for prefix (ioredis compat).
68
+ * @param {number} [options.connectTimeout=10000] - Connection timeout in ms.
69
+ */
70
+ constructor(options = {})
71
+ {
72
+ if (!Redis)
73
+ {
74
+ throw new Error(
75
+ 'Redis adapter requires the "ioredis" package.\n' +
76
+ 'Install it with: npm install ioredis'
77
+ );
78
+ }
79
+
80
+ // Validate options at the boundary
81
+ if (options.host !== undefined && (typeof options.host !== 'string' || !options.host.length))
82
+ throw new Error('Redis: host must be a non-empty string');
83
+ if (options.port !== undefined)
84
+ {
85
+ const p = Number(options.port);
86
+ if (!Number.isInteger(p) || p < 1 || p > 65535)
87
+ throw new Error('Redis: port must be an integer between 1 and 65535');
88
+ }
89
+ if (options.db !== undefined)
90
+ {
91
+ const d = Number(options.db);
92
+ if (!Number.isInteger(d) || d < 0 || d > 15)
93
+ throw new Error('Redis: db must be an integer between 0 and 15');
94
+ }
95
+ if (options.password !== undefined && typeof options.password !== 'string')
96
+ throw new Error('Redis: password must be a string');
97
+ if (options.url !== undefined && typeof options.url !== 'string')
98
+ throw new Error('Redis: url must be a string');
99
+ if (options.prefix !== undefined && typeof options.prefix !== 'string')
100
+ throw new Error('Redis: prefix must be a string');
101
+ if (options.connectTimeout !== undefined)
102
+ {
103
+ const ct = Number(options.connectTimeout);
104
+ if (!Number.isFinite(ct) || ct < 0)
105
+ throw new Error('Redis: connectTimeout must be a non-negative number');
106
+ }
107
+
108
+ this._prefix = options.prefix || options.keyPrefix || 'zh:';
109
+ this._schemas = new Map();
110
+ this._indexes = new Map();
111
+ this._subscribers = new Map();
112
+
113
+ // Build ioredis config
114
+ const config = {};
115
+ if (options.url)
116
+ {
117
+ this._client = new Redis(options.url, {
118
+ maxRetriesPerRequest: options.maxRetries || 3,
119
+ lazyConnect: options.lazyConnect || false,
120
+ connectTimeout: options.connectTimeout || 10000,
121
+ tls: options.tls,
122
+ keyPrefix: undefined, // we manage prefix ourselves
123
+ });
124
+ }
125
+ else
126
+ {
127
+ config.host = options.host || '127.0.0.1';
128
+ config.port = options.port || 6379;
129
+ if (options.password) config.password = options.password;
130
+ if (options.db !== undefined) config.db = options.db;
131
+ config.maxRetriesPerRequest = options.maxRetries || 3;
132
+ config.lazyConnect = options.lazyConnect || false;
133
+ config.connectTimeout = options.connectTimeout || 10000;
134
+ if (options.tls) config.tls = options.tls;
135
+
136
+ this._client = new Redis(config);
137
+ }
138
+
139
+ // Separate client for pub/sub (subscribers block the connection)
140
+ this._subClient = null;
141
+ }
142
+
143
+ // -- Key Helpers --------------------------------------
144
+
145
+ /** @private Validate a table name or key to prevent internal key collision. */
146
+ _validateKey(key, label = 'key')
147
+ {
148
+ if (typeof key !== 'string' || key.length === 0)
149
+ throw new Error(`Redis: ${label} must be a non-empty string`);
150
+ if (/[\x00-\x1f]/.test(key))
151
+ throw new Error(`Redis: ${label} must not contain control characters`);
152
+ }
153
+
154
+ /** @private Build a prefixed key for a table's metadata. */
155
+ _key(table, ...parts)
156
+ {
157
+ return this._prefix + table + (parts.length ? ':' + parts.join(':') : '');
158
+ }
159
+
160
+ /** @private Key for a table's row hash: zh:users:row:42 */
161
+ _rowKey(table, id)
162
+ {
163
+ return this._key(table, 'row', String(id));
164
+ }
165
+
166
+ /** @private Key for a table's ID index sorted set: zh:users:_ids */
167
+ _idsKey(table)
168
+ {
169
+ return this._key(table, '_ids');
170
+ }
171
+
172
+ /** @private Key for a table's auto-increment counter: zh:users:_seq */
173
+ _seqKey(table)
174
+ {
175
+ return this._key(table, '_seq');
176
+ }
177
+
178
+ /** @private Key for a table's schema definition: zh:users:_schema */
179
+ _schemaKey(table)
180
+ {
181
+ return this._key(table, '_schema');
182
+ }
183
+
184
+ /** @private Serialize a row for storage. */
185
+ _serialize(row)
186
+ {
187
+ return JSON.stringify(row);
188
+ }
189
+
190
+ /** @private Deserialize a stored row. */
191
+ _deserialize(data)
192
+ {
193
+ if (data === null || data === undefined) return null;
194
+ try { return JSON.parse(data); }
195
+ catch (_) { return null; }
196
+ }
197
+
198
+ // -- Table Management ---------------------------------
199
+
200
+ /**
201
+ * Create a table (register schema + initialize index).
202
+ * @param {string} table - Table name.
203
+ * @param {object} [schema] - Schema definition.
204
+ */
205
+ async createTable(table, schema)
206
+ {
207
+ this._validateKey(table, 'table name');
208
+ if (schema)
209
+ {
210
+ this._schemas.set(table, schema);
211
+ await this._client.set(this._schemaKey(table), JSON.stringify(schema));
212
+ }
213
+ // Ensure the sequence key exists
214
+ const exists = await this._client.exists(this._seqKey(table));
215
+ if (!exists) await this._client.set(this._seqKey(table), '0');
216
+ }
217
+
218
+ /**
219
+ * Drop a table (delete all keys).
220
+ * @param {string} table - Table name.
221
+ */
222
+ async dropTable(table)
223
+ {
224
+ // Get all row IDs
225
+ const ids = await this._client.zrange(this._idsKey(table), 0, -1);
226
+ const pipeline = this._client.pipeline();
227
+
228
+ for (const id of ids)
229
+ {
230
+ pipeline.del(this._rowKey(table, id));
231
+ }
232
+ pipeline.del(this._idsKey(table));
233
+ pipeline.del(this._seqKey(table));
234
+ pipeline.del(this._schemaKey(table));
235
+
236
+ // Delete any field index keys
237
+ const schema = this._schemas.get(table);
238
+ if (schema)
239
+ {
240
+ for (const col of Object.keys(schema))
241
+ {
242
+ pipeline.del(this._key(table, 'idx', col));
243
+ }
244
+ }
245
+
246
+ await pipeline.exec();
247
+ this._schemas.delete(table);
248
+ this._indexes.delete(table);
249
+ }
250
+
251
+ // -- CRUD Operations ----------------------------------
252
+
253
+ /**
254
+ * Insert a row.
255
+ * @param {string} table - Table name.
256
+ * @param {object} data - Record data object.
257
+ * @returns {Promise<object>} Inserted row with ID.
258
+ */
259
+ async insert(table, data)
260
+ {
261
+ const row = { ...data };
262
+
263
+ // Auto-increment if no ID provided
264
+ if (row.id === undefined || row.id === null)
265
+ {
266
+ row.id = await this._client.incr(this._seqKey(table));
267
+ }
268
+ else
269
+ {
270
+ // Ensure sequence is ahead of manual IDs
271
+ const current = parseInt(await this._client.get(this._seqKey(table)) || '0', 10);
272
+ if (typeof row.id === 'number' && row.id >= current)
273
+ {
274
+ await this._client.set(this._seqKey(table), String(row.id + 1));
275
+ }
276
+ }
277
+
278
+ // Serialize dates
279
+ for (const [k, v] of Object.entries(row))
280
+ {
281
+ if (v instanceof Date) row[k] = v.toISOString();
282
+ }
283
+
284
+ // Enforce unique constraints
285
+ await this._enforceUnique(table, row);
286
+
287
+ // Store the row as a JSON string
288
+ const pipeline = this._client.pipeline();
289
+ pipeline.set(this._rowKey(table, row.id), this._serialize(row));
290
+ // Add to sorted set index (score = numeric id for ordering)
291
+ pipeline.zadd(this._idsKey(table), Number(row.id) || 0, String(row.id));
292
+
293
+ await pipeline.exec();
294
+
295
+ return row;
296
+ }
297
+
298
+ /**
299
+ * Insert multiple rows.
300
+ * @param {string} table - Table name.
301
+ * @param {object[]} dataArray - Array of record objects.
302
+ * @returns {Promise<object[]>} Array of inserted rows.
303
+ */
304
+ async insertMany(table, dataArray)
305
+ {
306
+ const results = [];
307
+ for (const data of dataArray) results.push(await this.insert(table, data));
308
+ return results;
309
+ }
310
+
311
+ /**
312
+ * Update a row by primary key.
313
+ * @param {string} table - Table name.
314
+ * @param {string} pk - Primary key column name.
315
+ * @param {*} pkVal - Primary key value.
316
+ * @param {object} data - Record data object.
317
+ */
318
+ async update(table, pk, pkVal, data)
319
+ {
320
+ const key = this._rowKey(table, pkVal);
321
+ const existing = this._deserialize(await this._client.get(key));
322
+ if (!existing) return;
323
+
324
+ for (const [k, v] of Object.entries(data))
325
+ {
326
+ existing[k] = v instanceof Date ? v.toISOString() : v;
327
+ }
328
+
329
+ await this._client.set(key, this._serialize(existing));
330
+ }
331
+
332
+ /**
333
+ * Update all rows matching conditions.
334
+ * @param {string} table - Table name.
335
+ * @param {object} conditions - Filter conditions.
336
+ * @param {object} data - Record data object.
337
+ * @returns {Promise<number>} Number of updated rows.
338
+ */
339
+ async updateWhere(table, conditions, data)
340
+ {
341
+ const rows = await this._getAllRows(table);
342
+ let count = 0;
343
+
344
+ const pipeline = this._client.pipeline();
345
+ for (const row of rows)
346
+ {
347
+ if (this._matchConditions(row, conditions))
348
+ {
349
+ for (const [k, v] of Object.entries(data))
350
+ {
351
+ row[k] = v instanceof Date ? v.toISOString() : v;
352
+ }
353
+ pipeline.set(this._rowKey(table, row.id), this._serialize(row));
354
+ count++;
355
+ }
356
+ }
357
+ if (count > 0) await pipeline.exec();
358
+ return count;
359
+ }
360
+
361
+ /**
362
+ * Remove a row by primary key.
363
+ * @param {string} table - Table name.
364
+ * @param {string} pk - Primary key column name.
365
+ * @param {*} pkVal - Primary key value.
366
+ */
367
+ async remove(table, pk, pkVal)
368
+ {
369
+ const pipeline = this._client.pipeline();
370
+ pipeline.del(this._rowKey(table, pkVal));
371
+ pipeline.zrem(this._idsKey(table), String(pkVal));
372
+ await pipeline.exec();
373
+ }
374
+
375
+ /**
376
+ * Delete all rows matching conditions.
377
+ * @param {string} table - Table name.
378
+ * @param {object} conditions - Filter conditions.
379
+ * @returns {Promise<number>} Number of deleted rows.
380
+ */
381
+ async deleteWhere(table, conditions)
382
+ {
383
+ const rows = await this._getAllRows(table);
384
+ let count = 0;
385
+
386
+ const pipeline = this._client.pipeline();
387
+ for (const row of rows)
388
+ {
389
+ if (this._matchConditions(row, conditions))
390
+ {
391
+ pipeline.del(this._rowKey(table, row.id));
392
+ pipeline.zrem(this._idsKey(table), String(row.id));
393
+ count++;
394
+ }
395
+ }
396
+ if (count > 0) await pipeline.exec();
397
+ return count;
398
+ }
399
+
400
+ // -- Query Execution ----------------------------------
401
+
402
+ /**
403
+ * Execute a query descriptor (from the Query builder).
404
+ * @param {object} descriptor - Query descriptor object.
405
+ * @returns {Promise<Array|number>} Matching rows, or count if action is `'count'`.
406
+ */
407
+ async execute(descriptor)
408
+ {
409
+ const { action, table, fields, where, orderBy, limit, offset, distinct, groupBy, having } = descriptor;
410
+ let rows = await this._getAllRows(table);
411
+
412
+ // Apply WHERE filters
413
+ if (where && where.length > 0)
414
+ {
415
+ rows = rows.filter(row => this._applyWhereChain(row, where));
416
+ }
417
+
418
+ // Count action
419
+ if (action === 'count') return rows.length;
420
+
421
+ // GROUP BY
422
+ if (groupBy && groupBy.length > 0)
423
+ {
424
+ const groups = new Map();
425
+ for (const row of rows)
426
+ {
427
+ const key = groupBy.map(f => row[f]).join('\0');
428
+ if (!groups.has(key)) groups.set(key, { _key: {}, _rows: [] });
429
+ const g = groups.get(key);
430
+ for (const f of groupBy) g._key[f] = row[f];
431
+ g._rows.push(row);
432
+ }
433
+ rows = [];
434
+ for (const g of groups.values())
435
+ {
436
+ const row = { ...g._key };
437
+ row._groupRows = g._rows;
438
+ rows.push(row);
439
+ }
440
+
441
+ // HAVING
442
+ if (having && having.length > 0)
443
+ {
444
+ rows = rows.filter(row =>
445
+ {
446
+ for (const h of having)
447
+ {
448
+ let actual;
449
+ if (h.field === 'COUNT(*)' || h.field.startsWith('COUNT'))
450
+ {
451
+ actual = row._groupRows.length;
452
+ }
453
+ else
454
+ {
455
+ actual = row[h.field];
456
+ }
457
+ if (!this._compareOp(actual, h.op, h.value)) return false;
458
+ }
459
+ return true;
460
+ });
461
+ }
462
+
463
+ for (const row of rows) delete row._groupRows;
464
+ }
465
+
466
+ // ORDER BY
467
+ if (orderBy && orderBy.length > 0)
468
+ {
469
+ rows.sort((a, b) =>
470
+ {
471
+ for (const { field, dir } of orderBy)
472
+ {
473
+ const av = a[field], bv = b[field];
474
+ if (av < bv) return dir === 'ASC' ? -1 : 1;
475
+ if (av > bv) return dir === 'ASC' ? 1 : -1;
476
+ }
477
+ return 0;
478
+ });
479
+ }
480
+
481
+ // OFFSET
482
+ if (offset) rows = rows.slice(offset);
483
+
484
+ // LIMIT
485
+ if (limit) rows = rows.slice(0, limit);
486
+
487
+ // SELECT specific fields
488
+ if (fields && fields.length > 0)
489
+ {
490
+ rows = rows.map(row =>
491
+ {
492
+ const filtered = {};
493
+ for (const f of fields) filtered[f] = row[f];
494
+ return filtered;
495
+ });
496
+ }
497
+
498
+ // DISTINCT
499
+ if (distinct)
500
+ {
501
+ const seen = new Set();
502
+ rows = rows.filter(row =>
503
+ {
504
+ const key = JSON.stringify(row);
505
+ if (seen.has(key)) return false;
506
+ seen.add(key);
507
+ return true;
508
+ });
509
+ }
510
+
511
+ return rows;
512
+ }
513
+
514
+ /**
515
+ * Compute an aggregate value.
516
+ * @param {object} descriptor - Query descriptor object.
517
+ * @returns {Promise<number|null>} Computed aggregate value.
518
+ */
519
+ async aggregate(descriptor)
520
+ {
521
+ const { table, where, aggregateFn, aggregateField } = descriptor;
522
+ let rows = await this._getAllRows(table);
523
+ if (where && where.length > 0)
524
+ {
525
+ rows = rows.filter(row => this._applyWhereChain(row, where));
526
+ }
527
+ const fn = aggregateFn.toLowerCase();
528
+ if (!rows.length) return (fn === 'count' || fn === 'avg' || fn === 'sum') ? 0 : null;
529
+ switch (fn)
530
+ {
531
+ case 'sum': return rows.reduce((acc, r) => acc + (Number(r[aggregateField]) || 0), 0);
532
+ case 'avg': return rows.reduce((acc, r) => acc + (Number(r[aggregateField]) || 0), 0) / rows.length;
533
+ case 'min': return rows.reduce((m, r) => (r[aggregateField] < m ? r[aggregateField] : m), rows[0][aggregateField]);
534
+ case 'max': return rows.reduce((m, r) => (r[aggregateField] > m ? r[aggregateField] : m), rows[0][aggregateField]);
535
+ case 'count': return rows.length;
536
+ default: return null;
537
+ }
538
+ }
539
+
540
+ // -- Redis-Specific Operations ------------------------
541
+
542
+ /**
543
+ * Get a value by key (raw Redis GET).
544
+ * @param {string} key - Cache or storage key.
545
+ * @returns {Promise<string|null>} Stored value, or `null` if not found.
546
+ */
547
+ async get(key)
548
+ {
549
+ this._validateKey(key);
550
+ return this._client.get(this._prefix + key);
551
+ }
552
+
553
+ /**
554
+ * Set a key-value pair (raw Redis SET).
555
+ * @param {string} key - Cache or storage key.
556
+ * @param {*} value - Value to set.
557
+ * @param {number} [ttl] - Optional TTL in seconds.
558
+ * @returns {Promise<string>} Redis `"OK"` response.
559
+ */
560
+ async set(key, value, ttl)
561
+ {
562
+ this._validateKey(key);
563
+ if (ttl !== undefined && (!Number.isFinite(ttl) || ttl < 0))
564
+ throw new Error('Redis: TTL must be a non-negative number');
565
+ const k = this._prefix + key;
566
+ const v = typeof value === 'object' ? JSON.stringify(value) : String(value);
567
+ if (ttl) return this._client.setex(k, ttl, v);
568
+ return this._client.set(k, v);
569
+ }
570
+
571
+ /**
572
+ * Delete a key.
573
+ * @param {string} key - Cache or storage key.
574
+ * @returns {Promise<number>} Number of keys deleted (0 or 1).
575
+ */
576
+ async del(key)
577
+ {
578
+ this._validateKey(key);
579
+ return this._client.del(this._prefix + key);
580
+ }
581
+
582
+ /**
583
+ * Check if a key exists.
584
+ * @param {string} key - Cache or storage key.
585
+ * @returns {Promise<boolean>} `true` if the key exists.
586
+ */
587
+ async exists(key)
588
+ {
589
+ this._validateKey(key);
590
+ return (await this._client.exists(this._prefix + key)) === 1;
591
+ }
592
+
593
+ /**
594
+ * Set expiration on a key.
595
+ * @param {string} key - Cache or storage key.
596
+ * @param {number} seconds - Time in seconds.
597
+ * @returns {Promise<number>} `1` if timeout was set, `0` if key does not exist.
598
+ */
599
+ async expire(key, seconds)
600
+ {
601
+ this._validateKey(key);
602
+ if (!Number.isFinite(seconds) || seconds < 0)
603
+ throw new Error('Redis: TTL must be a non-negative number');
604
+ return this._client.expire(this._prefix + key, seconds);
605
+ }
606
+
607
+ /**
608
+ * Get TTL of a key in seconds.
609
+ * @param {string} key - Cache or storage key.
610
+ * @returns {Promise<number>} -1 if no expiry, -2 if key doesn't exist.
611
+ */
612
+ async ttl(key)
613
+ {
614
+ this._validateKey(key);
615
+ return this._client.ttl(this._prefix + key);
616
+ }
617
+
618
+ /**
619
+ * Increment a numeric key.
620
+ * @param {string} key - Cache or storage key.
621
+ * @param {number} [by=1] - Increment step.
622
+ * @returns {Promise<number>} Value after increment.
623
+ */
624
+ async incr(key, by = 1)
625
+ {
626
+ this._validateKey(key);
627
+ if (by === 1) return this._client.incr(this._prefix + key);
628
+ return this._client.incrby(this._prefix + key, by);
629
+ }
630
+
631
+ /**
632
+ * Decrement a numeric key.
633
+ * @param {string} key - Cache or storage key.
634
+ * @param {number} [by=1] - Increment step.
635
+ * @returns {Promise<number>} Value after decrement.
636
+ */
637
+ async decr(key, by = 1)
638
+ {
639
+ this._validateKey(key);
640
+ if (by === 1) return this._client.decr(this._prefix + key);
641
+ return this._client.decrby(this._prefix + key, by);
642
+ }
643
+
644
+ // -- Hash Operations ----------------------------------
645
+
646
+ /**
647
+ * Set a hash field.
648
+ * @param {string} key - Cache or storage key.
649
+ * @param {string} field - Field name.
650
+ * @param {*} value - Value to set.
651
+ * @returns {Promise<number>} `1` if field is new, `0` if updated.
652
+ */
653
+ async hset(key, field, value)
654
+ {
655
+ this._validateKey(key);
656
+ return this._client.hset(this._prefix + key, field, typeof value === 'object' ? JSON.stringify(value) : String(value));
657
+ }
658
+
659
+ /**
660
+ * Get a hash field.
661
+ * @param {string} key - Cache or storage key.
662
+ * @param {string} field - Field name.
663
+ * @returns {Promise<string|null>} Field value, or `null` if not found.
664
+ */
665
+ async hget(key, field)
666
+ {
667
+ this._validateKey(key);
668
+ return this._client.hget(this._prefix + key, field);
669
+ }
670
+
671
+ /**
672
+ * Get all fields in a hash.
673
+ * @param {string} key - Cache or storage key.
674
+ * @returns {Promise<object>} Object of field-value pairs.
675
+ */
676
+ async hgetall(key)
677
+ {
678
+ this._validateKey(key);
679
+ return this._client.hgetall(this._prefix + key);
680
+ }
681
+
682
+ /**
683
+ * Delete a hash field.
684
+ * @param {string} key - Cache or storage key.
685
+ * @param {string} field - Field name.
686
+ * @returns {Promise<number>} `1` if the field was removed, `0` if it did not exist.
687
+ */
688
+ async hdel(key, field)
689
+ {
690
+ this._validateKey(key);
691
+ return this._client.hdel(this._prefix + key, field);
692
+ }
693
+
694
+ // -- List Operations ----------------------------------
695
+
696
+ /**
697
+ * Push values to the end of a list.
698
+ * @param {string} key - Cache or storage key.
699
+ * @param {...*} values - Array of values.
700
+ * @returns {Promise<number>} Length of list after push.
701
+ */
702
+ async rpush(key, ...values)
703
+ {
704
+ this._validateKey(key);
705
+ return this._client.rpush(this._prefix + key, ...values.map(v => typeof v === 'object' ? JSON.stringify(v) : String(v)));
706
+ }
707
+
708
+ /**
709
+ * Push values to the beginning of a list.
710
+ * @param {string} key - Cache or storage key.
711
+ * @param {...*} values - Array of values.
712
+ * @returns {Promise<number>} Length of list after push.
713
+ */
714
+ async lpush(key, ...values)
715
+ {
716
+ this._validateKey(key);
717
+ return this._client.lpush(this._prefix + key, ...values.map(v => typeof v === 'object' ? JSON.stringify(v) : String(v)));
718
+ }
719
+
720
+ /**
721
+ * Get a range of list elements.
722
+ * @param {string} key - Cache or storage key.
723
+ * @param {number} [start=0] - Start offset.
724
+ * @param {number} [stop=-1] - Stop offset.
725
+ * @returns {Promise<string[]>} Array of list elements.
726
+ */
727
+ async lrange(key, start = 0, stop = -1)
728
+ {
729
+ this._validateKey(key);
730
+ return this._client.lrange(this._prefix + key, start, stop);
731
+ }
732
+
733
+ /**
734
+ * Pop from the end of a list.
735
+ * @param {string} key - Cache or storage key.
736
+ * @returns {Promise<string|null>} Removed element, or `null` if empty.
737
+ */
738
+ async rpop(key)
739
+ {
740
+ this._validateKey(key);
741
+ return this._client.rpop(this._prefix + key);
742
+ }
743
+
744
+ /**
745
+ * Pop from the beginning of a list.
746
+ * @param {string} key - Cache or storage key.
747
+ * @returns {Promise<string|null>} Removed element, or `null` if empty.
748
+ */
749
+ async lpop(key)
750
+ {
751
+ this._validateKey(key);
752
+ return this._client.lpop(this._prefix + key);
753
+ }
754
+
755
+ /**
756
+ * Get list length.
757
+ * @param {string} key - Cache or storage key.
758
+ * @returns {Promise<number>} Number of elements in the list.
759
+ */
760
+ async llen(key)
761
+ {
762
+ this._validateKey(key);
763
+ return this._client.llen(this._prefix + key);
764
+ }
765
+
766
+ // -- Set Operations -----------------------------------
767
+
768
+ /**
769
+ * Add members to a set.
770
+ * @param {string} key - Cache or storage key.
771
+ * @param {...*} members - Array of set members.
772
+ * @returns {Promise<number>} Number of members actually added.
773
+ */
774
+ async sadd(key, ...members)
775
+ {
776
+ this._validateKey(key);
777
+ return this._client.sadd(this._prefix + key, ...members.map(String));
778
+ }
779
+
780
+ /**
781
+ * Get all members of a set.
782
+ * @param {string} key - Cache or storage key.
783
+ * @returns {Promise<string[]>} Array of set members.
784
+ */
785
+ async smembers(key)
786
+ {
787
+ this._validateKey(key);
788
+ return this._client.smembers(this._prefix + key);
789
+ }
790
+
791
+ /**
792
+ * Check if a value is a member of a set.
793
+ * @param {string} key - Cache or storage key.
794
+ * @param {*} member - Set member.
795
+ * @returns {Promise<boolean>} `true` if the value is a member.
796
+ */
797
+ async sismember(key, member)
798
+ {
799
+ this._validateKey(key);
800
+ return (await this._client.sismember(this._prefix + key, String(member))) === 1;
801
+ }
802
+
803
+ /**
804
+ * Remove a member from a set.
805
+ * @param {string} key - Cache or storage key.
806
+ * @param {*} member - Set member.
807
+ * @returns {Promise<number>} `1` if the member was removed, `0` otherwise.
808
+ */
809
+ async srem(key, member)
810
+ {
811
+ this._validateKey(key);
812
+ return this._client.srem(this._prefix + key, String(member));
813
+ }
814
+
815
+ /**
816
+ * Get the number of members in a set.
817
+ * @param {string} key - Cache or storage key.
818
+ * @returns {Promise<number>} Number of members in the set.
819
+ */
820
+ async scard(key)
821
+ {
822
+ this._validateKey(key);
823
+ return this._client.scard(this._prefix + key);
824
+ }
825
+
826
+ // -- Sorted Set Operations ----------------------------
827
+
828
+ /**
829
+ * Add a member to a sorted set.
830
+ * @param {string} key - Cache or storage key.
831
+ * @param {number} score - Sort score.
832
+ * @param {*} member - Set member.
833
+ * @returns {Promise<number>} Number of members actually added.
834
+ */
835
+ async zadd(key, score, member)
836
+ {
837
+ this._validateKey(key);
838
+ return this._client.zadd(this._prefix + key, score, String(member));
839
+ }
840
+
841
+ /**
842
+ * Get members from a sorted set by score range.
843
+ * @param {string} key - Cache or storage key.
844
+ * @param {number|string} min - Minimum value.
845
+ * @param {number|string} max - Maximum value.
846
+ * @returns {Promise<string[]>} Array of matching members.
847
+ */
848
+ async zrangebyscore(key, min, max)
849
+ {
850
+ this._validateKey(key);
851
+ return this._client.zrangebyscore(this._prefix + key, min, max);
852
+ }
853
+
854
+ /**
855
+ * Get members from a sorted set by rank range.
856
+ * @param {string} key - Cache or storage key.
857
+ * @param {number} start - Start offset.
858
+ * @param {number} stop - Stop offset.
859
+ * @returns {Promise<string[]>} Array of members in rank order.
860
+ */
861
+ async zrange(key, start, stop)
862
+ {
863
+ this._validateKey(key);
864
+ return this._client.zrange(this._prefix + key, start, stop);
865
+ }
866
+
867
+ /**
868
+ * Remove a member from a sorted set.
869
+ * @param {string} key - Cache or storage key.
870
+ * @param {*} member - Set member.
871
+ * @returns {Promise<number>} Number of members removed.
872
+ */
873
+ async zrem(key, member)
874
+ {
875
+ this._validateKey(key);
876
+ return this._client.zrem(this._prefix + key, String(member));
877
+ }
878
+
879
+ /**
880
+ * Get sorted set cardinality.
881
+ * @param {string} key - Cache or storage key.
882
+ * @returns {Promise<number>} Number of members in the sorted set.
883
+ */
884
+ async zcard(key)
885
+ {
886
+ this._validateKey(key);
887
+ return this._client.zcard(this._prefix + key);
888
+ }
889
+
890
+ // -- Pub/Sub ------------------------------------------
891
+
892
+ /**
893
+ * Subscribe to a channel.
894
+ * @param {string} channel - Channel name.
895
+ * @param {Function} callback - Called with (message, channel).
896
+ * @returns {Promise<Function>} Unsubscribe function.
897
+ */
898
+ async subscribe(channel, callback)
899
+ {
900
+ this._validateKey(channel, 'channel');
901
+ if (typeof callback !== 'function')
902
+ throw new Error('Redis: subscribe callback must be a function');
903
+ if (!this._subClient)
904
+ {
905
+ this._subClient = this._client.duplicate();
906
+ }
907
+
908
+ const prefixedChannel = this._prefix + channel;
909
+ await this._subClient.subscribe(prefixedChannel);
910
+
911
+ const handler = (ch, message) =>
912
+ {
913
+ if (ch === prefixedChannel) callback(message, channel);
914
+ };
915
+ this._subClient.on('message', handler);
916
+
917
+ if (!this._subscribers.has(prefixedChannel))
918
+ {
919
+ this._subscribers.set(prefixedChannel, []);
920
+ }
921
+ this._subscribers.get(prefixedChannel).push({ callback, handler });
922
+
923
+ // Return unsubscribe function
924
+ return async () =>
925
+ {
926
+ this._subClient.removeListener('message', handler);
927
+ const subs = this._subscribers.get(prefixedChannel) || [];
928
+ const idx = subs.findIndex(s => s.callback === callback);
929
+ if (idx !== -1) subs.splice(idx, 1);
930
+ if (subs.length === 0)
931
+ {
932
+ await this._subClient.unsubscribe(prefixedChannel);
933
+ this._subscribers.delete(prefixedChannel);
934
+ }
935
+ };
936
+ }
937
+
938
+ /**
939
+ * Publish a message to a channel.
940
+ * @param {string} channel - Channel name.
941
+ * @param {*} message - Message payload.
942
+ * @returns {Promise<number>} Number of subscribers that received the message.
943
+ */
944
+ async publish(channel, message)
945
+ {
946
+ this._validateKey(channel, 'channel');
947
+ const msg = typeof message === 'object' ? JSON.stringify(message) : String(message);
948
+ return this._client.publish(this._prefix + channel, msg);
949
+ }
950
+
951
+ // -- Pipeline / Batch ---------------------------------
952
+
953
+ /**
954
+ * Create a pipeline for batching commands.
955
+ * @returns {Pipeline} Prefixed pipeline wrapper.
956
+ *
957
+ * @example
958
+ * const pipe = adapter.pipeline();
959
+ * pipe.set('key1', 'val1');
960
+ * pipe.set('key2', 'val2');
961
+ * const results = await pipe.exec();
962
+ */
963
+ pipeline()
964
+ {
965
+ const pipe = this._client.pipeline();
966
+ const adapter = this;
967
+
968
+ // Wrap to add prefix
969
+ return {
970
+ set(key, value, ...args)
971
+ {
972
+ pipe.set(adapter._prefix + key, typeof value === 'object' ? JSON.stringify(value) : String(value), ...args);
973
+ return this;
974
+ },
975
+ get(key) { pipe.get(adapter._prefix + key); return this; },
976
+ del(key) { pipe.del(adapter._prefix + key); return this; },
977
+ hset(key, field, value)
978
+ {
979
+ pipe.hset(adapter._prefix + key, field, typeof value === 'object' ? JSON.stringify(value) : String(value));
980
+ return this;
981
+ },
982
+ hget(key, field) { pipe.hget(adapter._prefix + key, field); return this; },
983
+ incr(key) { pipe.incr(adapter._prefix + key); return this; },
984
+ decr(key) { pipe.decr(adapter._prefix + key); return this; },
985
+ expire(key, seconds) { pipe.expire(adapter._prefix + key, seconds); return this; },
986
+ sadd(key, ...members) { pipe.sadd(adapter._prefix + key, ...members.map(String)); return this; },
987
+ rpush(key, ...values) { pipe.rpush(adapter._prefix + key, ...values.map(v => typeof v === 'object' ? JSON.stringify(v) : String(v))); return this; },
988
+ async exec() { return pipe.exec(); },
989
+ };
990
+ }
991
+
992
+ // -- Transaction Support ------------------------------
993
+
994
+ /**
995
+ * Begin a Redis MULTI transaction.
996
+ */
997
+ async beginTransaction()
998
+ {
999
+ this._multi = this._client.multi();
1000
+ }
1001
+
1002
+ /**
1003
+ * Commit a MULTI transaction.
1004
+ */
1005
+ async commit()
1006
+ {
1007
+ if (this._multi)
1008
+ {
1009
+ await this._multi.exec();
1010
+ this._multi = null;
1011
+ }
1012
+ }
1013
+
1014
+ /**
1015
+ * Discard a MULTI transaction.
1016
+ */
1017
+ async rollback()
1018
+ {
1019
+ if (this._multi)
1020
+ {
1021
+ this._multi.discard();
1022
+ this._multi = null;
1023
+ }
1024
+ }
1025
+
1026
+ // -- Utility & Admin ----------------------------------
1027
+
1028
+ /**
1029
+ * Clear all data (flush matched prefix keys).
1030
+ * Uses SCAN for safety in production (no KEYS *).
1031
+ */
1032
+ async clear()
1033
+ {
1034
+ let cursor = '0';
1035
+ do
1036
+ {
1037
+ const [nextCursor, keys] = await this._client.scan(cursor, 'MATCH', this._prefix + '*', 'COUNT', 100);
1038
+ cursor = nextCursor;
1039
+ if (keys.length > 0)
1040
+ {
1041
+ await this._client.del(...keys);
1042
+ }
1043
+ } while (cursor !== '0');
1044
+ }
1045
+
1046
+ /**
1047
+ * Ping the Redis server.
1048
+ * @returns {Promise<boolean>} `true` if the server responds.
1049
+ */
1050
+ async ping()
1051
+ {
1052
+ try
1053
+ {
1054
+ const result = await this._client.ping();
1055
+ return result === 'PONG';
1056
+ }
1057
+ catch (_)
1058
+ {
1059
+ return false;
1060
+ }
1061
+ }
1062
+
1063
+ /**
1064
+ * Get Redis server info.
1065
+ * @param {string} [section] - Optional section (e.g., 'memory', 'clients', 'stats').
1066
+ * @returns {Promise<string>} Raw Redis INFO output.
1067
+ */
1068
+ async info(section)
1069
+ {
1070
+ return section ? this._client.info(section) : this._client.info();
1071
+ }
1072
+
1073
+ /**
1074
+ * Get database size (number of keys).
1075
+ * @returns {Promise<number>} Total number of keys in the database.
1076
+ */
1077
+ async dbsize()
1078
+ {
1079
+ return this._client.dbsize();
1080
+ }
1081
+
1082
+ /**
1083
+ * List all table names (by scanning for schema keys).
1084
+ * @returns {Promise<string[]>} Array of table names.
1085
+ */
1086
+ async tables()
1087
+ {
1088
+ const tables = [];
1089
+ let cursor = '0';
1090
+ const pattern = this._prefix + '*:_schema';
1091
+ do
1092
+ {
1093
+ const [nextCursor, keys] = await this._client.scan(cursor, 'MATCH', pattern, 'COUNT', 100);
1094
+ cursor = nextCursor;
1095
+ for (const key of keys)
1096
+ {
1097
+ // Extract table name: zh:users:_schema → users
1098
+ const stripped = key.slice(this._prefix.length);
1099
+ const table = stripped.replace(/:_schema$/, '');
1100
+ tables.push(table);
1101
+ }
1102
+ } while (cursor !== '0');
1103
+ return tables;
1104
+ }
1105
+
1106
+ /**
1107
+ * Get stats for the adapter.
1108
+ * @returns {Promise<object>} Adapter statistics.
1109
+ */
1110
+ async stats()
1111
+ {
1112
+ const tableNames = await this.tables();
1113
+ let totalRows = 0;
1114
+ for (const t of tableNames)
1115
+ {
1116
+ totalRows += await this._client.zcard(this._idsKey(t));
1117
+ }
1118
+ return {
1119
+ tables: tableNames.length,
1120
+ totalRows,
1121
+ dbsize: await this._client.dbsize(),
1122
+ prefix: this._prefix,
1123
+ };
1124
+ }
1125
+
1126
+ /**
1127
+ * Get pool/connection status.
1128
+ * @returns {{ status: string, prefix: string }}
1129
+ */
1130
+ poolStatus()
1131
+ {
1132
+ return {
1133
+ status: this._client.status,
1134
+ prefix: this._prefix,
1135
+ };
1136
+ }
1137
+
1138
+ /**
1139
+ * Get the underlying ioredis client.
1140
+ * @returns {object} The ioredis client instance.
1141
+ */
1142
+ get client()
1143
+ {
1144
+ return this._client;
1145
+ }
1146
+
1147
+ /**
1148
+ * Execute a raw Redis command.
1149
+ * @param {string} command - Command name.
1150
+ * @param {...*} args - Command arguments.
1151
+ * @returns {Promise<*>} Command result.
1152
+ */
1153
+ async raw(command, ...args)
1154
+ {
1155
+ if (typeof command !== 'string' || command.length === 0)
1156
+ throw new Error('Redis: command must be a non-empty string');
1157
+ return this._client.call(command, ...args);
1158
+ }
1159
+
1160
+ /**
1161
+ * Close the connection.
1162
+ */
1163
+ async close()
1164
+ {
1165
+ if (this._subClient)
1166
+ {
1167
+ await this._subClient.quit();
1168
+ this._subClient = null;
1169
+ }
1170
+ await this._client.quit();
1171
+ }
1172
+
1173
+ // -- Migration / DDL Methods --------------------------
1174
+
1175
+ /**
1176
+ * Add a column to an existing table.
1177
+ * @param {string} table - Table name.
1178
+ * @param {string} column - Column name.
1179
+ * @param {object} def - Column definition.
1180
+ */
1181
+ async addColumn(table, column, def)
1182
+ {
1183
+ const schema = this._schemas.get(table);
1184
+ if (schema) schema[column] = def;
1185
+
1186
+ const defaultVal = def.default !== undefined
1187
+ ? (typeof def.default === 'function' ? def.default() : def.default)
1188
+ : null;
1189
+
1190
+ // Update all existing rows
1191
+ const rows = await this._getAllRows(table);
1192
+ const pipeline = this._client.pipeline();
1193
+ for (const row of rows)
1194
+ {
1195
+ if (row[column] === undefined)
1196
+ {
1197
+ row[column] = defaultVal;
1198
+ pipeline.set(this._rowKey(table, row.id), this._serialize(row));
1199
+ }
1200
+ }
1201
+ if (rows.length > 0) await pipeline.exec();
1202
+
1203
+ // Update stored schema
1204
+ await this._client.set(this._schemaKey(table), JSON.stringify(this._schemas.get(table) || {}));
1205
+ }
1206
+
1207
+ /**
1208
+ * Drop a column from a table.
1209
+ * @param {string} table - Table name.
1210
+ * @param {string} column - Column name.
1211
+ */
1212
+ async dropColumn(table, column)
1213
+ {
1214
+ const schema = this._schemas.get(table);
1215
+ if (schema) delete schema[column];
1216
+
1217
+ const rows = await this._getAllRows(table);
1218
+ const pipeline = this._client.pipeline();
1219
+ for (const row of rows)
1220
+ {
1221
+ delete row[column];
1222
+ pipeline.set(this._rowKey(table, row.id), this._serialize(row));
1223
+ }
1224
+ if (rows.length > 0) await pipeline.exec();
1225
+ }
1226
+
1227
+ /**
1228
+ * Rename a column.
1229
+ * @param {string} table - Table name.
1230
+ * @param {string} oldName - Current name.
1231
+ * @param {string} newName - New name.
1232
+ */
1233
+ async renameColumn(table, oldName, newName)
1234
+ {
1235
+ const schema = this._schemas.get(table);
1236
+ if (schema && schema[oldName])
1237
+ {
1238
+ schema[newName] = schema[oldName];
1239
+ delete schema[oldName];
1240
+ }
1241
+
1242
+ const rows = await this._getAllRows(table);
1243
+ const pipeline = this._client.pipeline();
1244
+ for (const row of rows)
1245
+ {
1246
+ if (oldName in row)
1247
+ {
1248
+ row[newName] = row[oldName];
1249
+ delete row[oldName];
1250
+ pipeline.set(this._rowKey(table, row.id), this._serialize(row));
1251
+ }
1252
+ }
1253
+ if (rows.length > 0) await pipeline.exec();
1254
+ }
1255
+
1256
+ /**
1257
+ * Rename a table.
1258
+ * @param {string} oldName - Current name.
1259
+ * @param {string} newName - New name.
1260
+ */
1261
+ async renameTable(oldName, newName)
1262
+ {
1263
+ const rows = await this._getAllRows(oldName);
1264
+
1265
+ // Create new table with all rows
1266
+ const schema = this._schemas.get(oldName);
1267
+ if (schema)
1268
+ {
1269
+ this._schemas.set(newName, schema);
1270
+ this._schemas.delete(oldName);
1271
+ }
1272
+
1273
+ const pipeline = this._client.pipeline();
1274
+
1275
+ // Copy sequence
1276
+ const seq = await this._client.get(this._seqKey(oldName));
1277
+ pipeline.set(this._seqKey(newName), seq || '0');
1278
+
1279
+ // Copy rows to new keys
1280
+ for (const row of rows)
1281
+ {
1282
+ pipeline.set(this._rowKey(newName, row.id), this._serialize(row));
1283
+ pipeline.zadd(this._idsKey(newName), Number(row.id) || 0, String(row.id));
1284
+ }
1285
+
1286
+ // Store new schema
1287
+ if (schema)
1288
+ {
1289
+ pipeline.set(this._schemaKey(newName), JSON.stringify(schema));
1290
+ }
1291
+
1292
+ await pipeline.exec();
1293
+
1294
+ // Drop old table
1295
+ await this.dropTable(oldName);
1296
+ }
1297
+
1298
+ /**
1299
+ * Create an index (tracked in metadata).
1300
+ * @param {string} table - Table name.
1301
+ * @param {string|string[]} columns - Column name(s).
1302
+ * @param {{ name?: string, unique?: boolean }} [options={}]
1303
+ */
1304
+ async createIndex(table, columns, options = {})
1305
+ {
1306
+ const cols = Array.isArray(columns) ? columns : [columns];
1307
+ const name = options.name || `idx_${table}_${cols.join('_')}`;
1308
+ if (!this._indexes.has(table)) this._indexes.set(table, []);
1309
+ this._indexes.get(table).push({ name, columns: cols, unique: !!options.unique });
1310
+ }
1311
+
1312
+ /**
1313
+ * Drop an index.
1314
+ * @param {string} _table - Table name (unused).
1315
+ * @param {string} name - Name identifier.
1316
+ */
1317
+ async dropIndex(_table, name)
1318
+ {
1319
+ for (const [, indexes] of this._indexes)
1320
+ {
1321
+ const idx = indexes.findIndex(i => i.name === name);
1322
+ if (idx !== -1) { indexes.splice(idx, 1); return; }
1323
+ }
1324
+ }
1325
+
1326
+ /**
1327
+ * Check if a table exists.
1328
+ * @param {string} table - Table name.
1329
+ * @returns {Promise<boolean>} `true` if the table exists.
1330
+ */
1331
+ async hasTable(table)
1332
+ {
1333
+ return (await this._client.exists(this._seqKey(table))) === 1 ||
1334
+ (await this._client.exists(this._schemaKey(table))) === 1;
1335
+ }
1336
+
1337
+ /**
1338
+ * Check if a column exists on a table.
1339
+ * @param {string} table - Table name.
1340
+ * @param {string} column - Column name.
1341
+ * @returns {Promise<boolean>} `true` if the column exists.
1342
+ */
1343
+ async hasColumn(table, column)
1344
+ {
1345
+ const schema = this._schemas.get(table);
1346
+ if (schema) return column in schema;
1347
+ // Check first row
1348
+ const ids = await this._client.zrange(this._idsKey(table), 0, 0);
1349
+ if (ids.length === 0) return false;
1350
+ const row = this._deserialize(await this._client.get(this._rowKey(table, ids[0])));
1351
+ return row ? column in row : false;
1352
+ }
1353
+
1354
+ /**
1355
+ * Describe a table's columns.
1356
+ * @param {string} table - Table name.
1357
+ * @returns {Promise<Array>} Array of column definitions.
1358
+ */
1359
+ async describeTable(table)
1360
+ {
1361
+ const schema = this._schemas.get(table);
1362
+ if (!schema) return [];
1363
+ return Object.entries(schema).map(([name, def]) => ({
1364
+ name,
1365
+ type: def.type || 'TEXT',
1366
+ nullable: !def.required,
1367
+ defaultValue: def.default !== undefined ? def.default : null,
1368
+ primaryKey: !!def.primaryKey,
1369
+ }));
1370
+ }
1371
+
1372
+ /**
1373
+ * Get indexes for a table.
1374
+ * @param {string} table - Table name.
1375
+ * @returns {Promise<Array>} Array of index definitions.
1376
+ */
1377
+ async indexes(table)
1378
+ {
1379
+ return this._indexes.get(table) || [];
1380
+ }
1381
+
1382
+ // -- Internal Helpers ---------------------------------
1383
+
1384
+ /**
1385
+ * Get all rows for a table.
1386
+ * @private
1387
+ * @param {string} table - Table name.
1388
+ * @returns {Promise<object[]>} All rows in the table.
1389
+ */
1390
+ async _getAllRows(table)
1391
+ {
1392
+ const ids = await this._client.zrange(this._idsKey(table), 0, -1);
1393
+ if (ids.length === 0) return [];
1394
+
1395
+ const pipeline = this._client.pipeline();
1396
+ for (const id of ids)
1397
+ {
1398
+ pipeline.get(this._rowKey(table, id));
1399
+ }
1400
+ const results = await pipeline.exec();
1401
+ const rows = [];
1402
+ for (const [err, val] of results)
1403
+ {
1404
+ if (!err && val)
1405
+ {
1406
+ const row = this._deserialize(val);
1407
+ if (row) rows.push(row);
1408
+ }
1409
+ }
1410
+ return rows;
1411
+ }
1412
+
1413
+ /** @private Match simple conditions. */
1414
+ _matchConditions(row, conditions)
1415
+ {
1416
+ if (!conditions || typeof conditions !== 'object') return true;
1417
+ for (const [k, v] of Object.entries(conditions))
1418
+ {
1419
+ if (row[k] !== v) return false;
1420
+ }
1421
+ return true;
1422
+ }
1423
+
1424
+ /** @private Apply the where chain from query builder. */
1425
+ _applyWhereChain(row, where)
1426
+ {
1427
+ let result = true;
1428
+ for (let i = 0; i < where.length; i++)
1429
+ {
1430
+ const clause = where[i];
1431
+ if (clause.raw) continue;
1432
+ const matches = this._matchClause(row, clause);
1433
+
1434
+ if (i === 0 || clause.logic === 'AND')
1435
+ {
1436
+ result = i === 0 ? matches : (result && matches);
1437
+ }
1438
+ else if (clause.logic === 'OR')
1439
+ {
1440
+ result = result || matches;
1441
+ }
1442
+ }
1443
+ return result;
1444
+ }
1445
+
1446
+ /** @private Match a single WHERE clause. */
1447
+ _matchClause(row, clause)
1448
+ {
1449
+ const val = row[clause.field];
1450
+ const { op, value } = clause;
1451
+
1452
+ switch (op)
1453
+ {
1454
+ case '=': return val === value;
1455
+ case '!=':
1456
+ case '<>': return val !== value;
1457
+ case '>': return val > value;
1458
+ case '<': return val < value;
1459
+ case '>=': return val >= value;
1460
+ case '<=': return val <= value;
1461
+ case 'LIKE': return _likeSafe(String(val), String(value));
1462
+ case 'IN': return Array.isArray(value) && value.includes(val);
1463
+ case 'NOT IN': return Array.isArray(value) && !value.includes(val);
1464
+ case 'BETWEEN': return Array.isArray(value) && val >= value[0] && val <= value[1];
1465
+ case 'NOT BETWEEN': return Array.isArray(value) && (val < value[0] || val > value[1]);
1466
+ case 'IS NULL': return val === null || val === undefined;
1467
+ case 'IS NOT NULL': return val !== null && val !== undefined;
1468
+ default: return val === value;
1469
+ }
1470
+ }
1471
+
1472
+ /** @private Compare for HAVING. */
1473
+ _compareOp(actual, op, value)
1474
+ {
1475
+ switch (op.toUpperCase())
1476
+ {
1477
+ case '=': return actual === value;
1478
+ case '!=':
1479
+ case '<>': return actual !== value;
1480
+ case '>': return actual > value;
1481
+ case '<': return actual < value;
1482
+ case '>=': return actual >= value;
1483
+ case '<=': return actual <= value;
1484
+ default: return actual === value;
1485
+ }
1486
+ }
1487
+
1488
+ /** @private Enforce unique constraints. */
1489
+ async _enforceUnique(table, row, excludeRow)
1490
+ {
1491
+ const schema = this._schemas.get(table);
1492
+ if (!schema) return;
1493
+
1494
+ const rows = await this._getAllRows(table);
1495
+
1496
+ for (const [col, def] of Object.entries(schema))
1497
+ {
1498
+ if (def.unique && row[col] !== undefined && row[col] !== null)
1499
+ {
1500
+ const duplicate = rows.find(r =>
1501
+ r !== excludeRow && r.id !== (excludeRow && excludeRow.id) && r[col] === row[col]
1502
+ );
1503
+ if (duplicate)
1504
+ {
1505
+ throw new Error(`UNIQUE constraint failed: ${table}.${col}`);
1506
+ }
1507
+ }
1508
+ }
1509
+
1510
+ // Composite unique
1511
+ const groups = {};
1512
+ for (const [col, def] of Object.entries(schema))
1513
+ {
1514
+ if (def.compositeUnique)
1515
+ {
1516
+ const g = typeof def.compositeUnique === 'string' ? def.compositeUnique : 'default';
1517
+ if (!groups[g]) groups[g] = [];
1518
+ groups[g].push(col);
1519
+ }
1520
+ }
1521
+ for (const cols of Object.values(groups))
1522
+ {
1523
+ const duplicate = rows.find(r =>
1524
+ r !== excludeRow && r.id !== (excludeRow && excludeRow.id) && cols.every(c => r[c] === row[c])
1525
+ );
1526
+ if (duplicate)
1527
+ {
1528
+ throw new Error(`UNIQUE constraint failed: ${table}.(${cols.join(', ')})`);
1529
+ }
1530
+ }
1531
+ }
1532
+ }
1533
+
1534
+ module.exports = RedisAdapter;