jsql-neo 5.5.0 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/LICENSE +202 -202
  2. package/README.md +8155 -8097
  3. package/bin/jsql +320 -320
  4. package/bin/jsql-server +90 -90
  5. package/bin/jsql-server-control.js +177 -177
  6. package/index.d.ts +412 -385
  7. package/index.js +128 -124
  8. package/lib/ast.js +214 -214
  9. package/lib/btree.js +478 -413
  10. package/lib/cache.js +328 -328
  11. package/lib/client.js +125 -125
  12. package/lib/database.js +1741 -1744
  13. package/lib/date-types.js +182 -182
  14. package/lib/errors.js +89 -89
  15. package/lib/jsql_format.js +497 -497
  16. package/lib/migrate.js +254 -254
  17. package/lib/mod.js +292 -292
  18. package/lib/mongo_server.js +607 -607
  19. package/lib/multiserver.js +140 -140
  20. package/lib/mysql_compat.js +413 -413
  21. package/lib/mysql_server.js +1237 -1237
  22. package/lib/native_client.js +722 -732
  23. package/lib/nedb_compat.js +506 -506
  24. package/lib/pg_server.js +864 -864
  25. package/lib/plugin.js +259 -35
  26. package/lib/plugins/audit.js +37 -0
  27. package/lib/plugins/index.js +72 -0
  28. package/lib/plugins/logger.js +35 -0
  29. package/lib/plugins/metrics.js +38 -0
  30. package/lib/plugins/timestamps.js +57 -0
  31. package/lib/plugins/validation.js +128 -0
  32. package/lib/prepared.js +37 -0
  33. package/lib/query.js +834 -815
  34. package/lib/redis_server.js +571 -571
  35. package/lib/sql.js +4053 -3460
  36. package/lib/sqlite_compat.js +323 -323
  37. package/lib/sqlite_worker.js +264 -264
  38. package/lib/table.js +1351 -1304
  39. package/lib/tui.js +502 -502
  40. package/lib/wasm.js +1 -1
  41. package/lib/wasm_client.js +715 -718
  42. package/lib/web_ui.js +257 -257
  43. package/native/jsql-neo-native.node +0 -0
  44. package/nativesrc/jsql-neo-core/Cargo.lock +462 -455
  45. package/nativesrc/jsql-neo-core/Cargo.toml +26 -24
  46. package/nativesrc/jsql-neo-core/src/engine/hybrid.rs +492 -455
  47. package/nativesrc/jsql-neo-core/src/engine/memory.rs +191 -168
  48. package/nativesrc/jsql-neo-core/src/engine/mod.rs +74 -62
  49. package/nativesrc/jsql-neo-core/src/engine/table.rs +996 -700
  50. package/nativesrc/jsql-neo-core/src/lib.rs +2 -2
  51. package/nativesrc/jsql-neo-core/src/storage/mod.rs +2 -2
  52. package/nativesrc/jsql-neo-core/src/storage/persistent.rs +1 -1
  53. package/nativesrc/jsql-neo-core/src/storage/wal.rs +298 -85
  54. package/nativesrc/jsql-neo-core/src/types.rs +93 -93
  55. package/nativesrc/jsql-neo-native/Cargo.lock +613 -606
  56. package/nativesrc/jsql-neo-native/Cargo.toml +24 -16
  57. package/nativesrc/jsql-neo-native/build.rs +3 -3
  58. package/nativesrc/jsql-neo-native/package.json +7 -7
  59. package/nativesrc/jsql-neo-native/src/lib.rs +281 -269
  60. package/nativesrc/jsql-neo-wasm/Cargo.lock +472 -465
  61. package/nativesrc/jsql-neo-wasm/Cargo.toml +22 -15
  62. package/nativesrc/jsql-neo-wasm/src/lib.rs +463 -447
  63. package/package.json +87 -87
  64. package/postinstall.js +158 -158
  65. package/test/btree.test.js +144 -128
  66. package/test/coverage.js +187 -187
  67. package/test/join.test.js +110 -110
  68. package/test/native.test.js +158 -158
  69. package/test/query-opt.test.js +109 -0
  70. package/test/regress-5.1.0.js +271 -271
  71. package/test/smoke.js +58 -58
  72. package/test/sql-parser.test.js +450 -273
  73. package/test/wasm.test.js +110 -110
  74. package/wasm/browser.d.ts +89 -89
  75. package/wasm/browser.mjs +591 -569
  76. package/wasm/browser_bg.mjs +618 -597
  77. package/wasm/jsql_neo_wasm.d.ts +44 -38
  78. package/wasm/jsql_neo_wasm.js +641 -520
  79. package/wasm/jsql_neo_wasm_bg.wasm +0 -0
  80. package/wasm/jsql_neo_wasm_bg.wasm.d.ts +26 -26
  81. package/wasm/package.json +11 -11
@@ -1,733 +1,723 @@
1
- const path = require('path');
2
- const os = require('os');
3
- const { executeSQL } = require('./sql');
4
- const native = require(path.join(__dirname, '..', 'native', 'jsql-neo-native.node'));
5
- const INT64_TAG = 1;
6
- const FLOAT_TAG = 2;
7
- const STR_TAG = 3;
8
- const BOOL_TAG = 4;
9
- const INT32_TAG = 5;
10
-
11
- function safeParse(str, fallback) {
12
- if (typeof str !== 'string') return fallback;
13
- try { return JSON.parse(str); } catch (e) { return fallback; }
14
- }
15
-
16
- const NATIVE_TYPE_MAP = {
17
- text: 'string',
18
- varchar: 'string',
19
- double: 'float',
20
- number: 'float',
21
- numeric: 'float',
22
- decimal: 'float',
23
- date: 'string',
24
- timestamp: 'string',
25
- datetime: 'string',
26
- json: 'string',
27
- array: 'string',
28
- object: 'string',
29
- bool: 'boolean',
30
- bigint: 'string',
31
- int: 'integer',
32
- };
33
-
34
- function parseShorthandSchema(str) {
35
- const def = { type: str };
36
- const strip = (re) => {
37
- const next = def.type.replace(re, '').trim();
38
- def.type = next || def.type;
39
- };
40
- if (/\bprimary\s+key\b/i.test(def.type)) { def.primaryKey = true; strip(/\bprimary\s+key\b/gi); }
41
- if (/\bauto_?increment\b/i.test(def.type)) { def.autoIncrement = true; strip(/\bauto_?increment\b/gi); }
42
- if (/\bnot\s+null\b/i.test(def.type)) { def.required = true; strip(/\bnot\s+null\b/gi); }
43
- if (/\bunique\b/i.test(def.type)) { def.unique = true; strip(/\bunique\b/gi); }
44
- if (/\bdefault\s+(\S+)/i.test(def.type)) {
45
- const m = def.type.match(/\bdefault\s+(\S+)/i);
46
- def.default = m[1].replace(/^['"]|['"]$/g, '');
47
- strip(/\bdefault\s+\S+/gi);
48
- }
49
- return def;
50
- }
51
-
52
- function parseSchemaString(str) {
53
- const out = {};
54
- for (const seg of str.split(',')) {
55
- const trimmed = seg.trim();
56
- if (!trimmed) continue;
57
- const parts = trimmed.split(/\s+/);
58
- const name = parts.shift();
59
- const def = parseShorthandSchema(parts.join(' ').toLowerCase().trim());
60
- if (def.type.length === 0) def.type = 'string';
61
- out[name] = def;
62
- }
63
- return out;
64
- }
65
-
66
- function mapNativeSchema(schema) {
67
- if (typeof schema === 'string') schema = parseSchemaString(schema);
68
- const mapped = {};
69
- for (const [field, def] of Object.entries(schema || {})) {
70
- if (typeof def === 'string') {
71
- const parsed = parseShorthandSchema(def.toLowerCase().trim());
72
- if (parsed.type.length === 0) parsed.type = 'string';
73
- mapped[field] = { ...parsed, type: NATIVE_TYPE_MAP[parsed.type] || parsed.type };
74
- } else if (def && typeof def === 'object') {
75
- const t = (def.type || 'string').toLowerCase();
76
- const out = { ...def, type: NATIVE_TYPE_MAP[t] || t };
77
- if (out.primary_key !== undefined && out.primaryKey === undefined) { out.primaryKey = out.primary_key; delete out.primary_key; }
78
- if (out.auto_increment !== undefined && out.autoIncrement === undefined) { out.autoIncrement = out.auto_increment; delete out.auto_increment; }
79
- mapped[field] = out;
80
- } else {
81
- mapped[field] = { type: 'string' };
82
- }
83
- }
84
- return mapped;
85
- }
86
-
87
- function restoreRow(row, schema) {
88
- if (typeof row !== 'object' || row === null) return row;
89
- let src = row;
90
- if (row.fields && typeof row.fields === 'object' && row.fields !== null) {
91
- src = { ...row.fields };
92
- if (row.id !== undefined) {
93
- const pkCols = [];
94
- if (schema) {
95
- for (const [k, def] of Object.entries(schema)) {
96
- if (def && typeof def === 'object' && def.autoIncrement) continue;
97
- const isPk = typeof def === 'string'
98
- ? /\bprimary\s+key\b/i.test(def)
99
- : !!(def && (def.primaryKey || def.primary_key));
100
- if (isPk) pkCols.push(k);
101
- }
102
- } else if (src.id === undefined) {
103
- pkCols.push('id');
104
- }
105
- for (const c of pkCols) {
106
- const v = src[c];
107
- if (v === undefined || v === null || v === 0 || v === '' || v === false) src[c] = row.id;
108
- }
109
- }
110
- if (row.created_at !== undefined) src.created_at = row.created_at;
111
- if (row.updated_at !== undefined) src.updated_at = row.updated_at;
112
- }
113
- if (!schema) return src;
114
- const out = {};
115
- for (const [field, value] of Object.entries(src)) {
116
- const colDef = schema[field];
117
- let t = null;
118
- if (typeof colDef === 'string') t = colDef.toLowerCase();
119
- else if (colDef && typeof colDef === 'object' && colDef.type) t = String(colDef.type).toLowerCase();
120
- if (['json', 'array', 'object'].includes(t) && typeof value === 'string') {
121
- try { out[field] = JSON.parse(value); } catch (e) { out[field] = value; }
122
- } else if ((t === 'integer' || t === 'int' || t === 'bigint') && typeof value === 'string' && /^-?\d+$/.test(value)) {
123
- out[field] = Number(value);
124
- } else if ((t === 'float' || t === 'double' || t === 'number') && typeof value === 'string' && !Number.isNaN(Number(value))) {
125
- out[field] = Number(value);
126
- } else {
127
- out[field] = value;
128
- }
129
- }
130
- return out;
131
- }
132
-
133
- function _encodedFieldSize(v) {
134
- if (v === null || v === undefined) return 1;
135
- if (typeof v === 'number') {
136
- if (Number.isInteger(v)) return (v >= -2147483648 && v <= 2147483647) ? 1 + 4 : 1 + 8;
137
- return 1 + 8;
138
- }
139
- if (typeof v === 'boolean') return 1 + 1;
140
- const s = typeof v === 'object' ? JSON.stringify(v) : String(v);
141
- return 1 + 4 + Buffer.byteLength(s, 'utf8');
142
- }
143
-
144
- function encodeField(buf, off, v) {
145
- if (v === null || v === undefined) {
146
- buf.writeUInt8(0, off); return off + 1;
147
- }
148
- if (typeof v === 'number') {
149
- if (Number.isInteger(v)) {
150
- if (v >= -2147483648 && v <= 2147483647) {
151
- buf.writeUInt8(INT32_TAG, off); buf.writeInt32LE(v, off + 1); return off + 5;
152
- }
153
- buf.writeUInt8(INT64_TAG, off); buf.writeBigInt64LE(BigInt(v), off + 1); return off + 9;
154
- }
155
- buf.writeUInt8(FLOAT_TAG, off); buf.writeDoubleLE(v, off + 1); return off + 9;
156
- }
157
- if (typeof v === 'string') {
158
- const sl = Buffer.byteLength(v, 'utf8');
159
- buf.writeUInt8(STR_TAG, off);
160
- buf.writeUInt32LE(sl, off + 1);
161
- buf.write(v, off + 5, sl, 'utf8');
162
- return off + 5 + sl;
163
- }
164
- if (typeof v === 'boolean') {
165
- buf.writeUInt8(BOOL_TAG, off); buf.writeUInt8(v ? 1 : 0, off + 1); return off + 2;
166
- }
167
- const s = typeof v === 'object' ? JSON.stringify(v) : String(v);
168
- const sl = Buffer.byteLength(s, 'utf8');
169
- buf.writeUInt8(STR_TAG, off);
170
- buf.writeUInt32LE(sl, off + 1);
171
- buf.write(s, off + 5, sl, 'utf8');
172
- return off + 5 + sl;
173
- }
174
-
175
- function encodeBatch(rows) {
176
- if (rows.length === 0) return new Uint8Array(0);
177
- const fieldNames = Object.keys(rows[0]);
178
- const nFields = fieldNames.length;
179
- let size = 1;
180
- for (const s of fieldNames) size += 1 + Buffer.byteLength(s, 'utf8');
181
- size += 4;
182
- for (const row of rows) {
183
- for (let fi = 0; fi < nFields; fi++) size += _encodedFieldSize(row[fieldNames[fi]]);
184
- }
185
- const buf = Buffer.allocUnsafe(size);
186
- let off = 0;
187
-
188
- off = buf.writeUInt8(nFields, off);
189
- for (let fi = 0; fi < nFields; fi++) {
190
- const s = fieldNames[fi];
191
- const nlen = Buffer.byteLength(s, 'utf8');
192
- off = buf.writeUInt8(nlen, off);
193
- off += buf.write(s, off, nlen, 'utf8');
194
- }
195
- off = buf.writeUInt32LE(rows.length, off);
196
-
197
- for (let ri = 0; ri < rows.length; ri++) {
198
- const row = rows[ri];
199
- for (let fi = 0; fi < nFields; fi++) {
200
- off = encodeField(buf, off, row[fieldNames[fi]]);
201
- }
202
- }
203
-
204
- return buf.slice(0, off);
205
- }
206
-
207
- class JSQL {
208
- constructor(opts = {}) {
209
- this._flushThreshold = opts.flushThreshold || 5000;
210
- this._buffer = {};
211
- this._bufferSize = 0;
212
- this._opBuffer = { remove: {}, update: {} };
213
- this._opTimer = null;
214
- this._opFlushInterval = opts.opFlushInterval || 50;
215
- this._tableNames = new Set();
216
- this._schemas = {};
217
- this._txId = undefined;
218
- this._autoPlugins = opts.modules !== false;
219
-
220
- // 持久化模式: 'memory' | 'hybrid' | 'disk'
221
- this._path = opts.path || null;
222
- this._mode = opts.mode || (this._path ? 'hybrid' : 'memory');
223
- this._memReserveMB = opts.memReserveMB !== undefined ? opts.memReserveMB : 512;
224
- this._flushInterval = opts.flushInterval !== undefined
225
- ? opts.flushInterval
226
- : (this._mode === 'disk' ? 50 : 200);
227
- this._evictInterval = opts.evictInterval !== undefined ? opts.evictInterval : 1000;
228
- this._diskFlushTimer = null;
229
- this._evictTimer = null;
230
-
231
- this._plugins = [];
232
- this._hooks = {
233
- beforeInsert: [], afterInsert: [],
234
- beforeUpdate: [], afterUpdate: [],
235
- beforeDelete: [], afterDelete: [],
236
- beforeFind: [], afterFind: [],
237
- beforeCreateTable: [], afterCreateTable: [],
238
- beforeDropTable: [], afterDropTable: [],
239
- beforeFlush: [], afterFlush: [],
240
- beforeCount: [], afterCount: [],
241
- onStart: [], onStop: []
242
- };
243
- this._eventListeners = [];
244
- if (this._autoPlugins) {
245
- const { ModuleManager } = require('./mod');
246
- new ModuleManager().applyTo(this);
247
- }
248
- }
249
-
250
- use(plugin) {
251
- if (typeof plugin === 'function') {
252
- plugin = { install: plugin };
253
- }
254
- if (plugin.hooks) {
255
- for (const [event, fn] of Object.entries(plugin.hooks)) {
256
- if (this._hooks[event]) {
257
- this._hooks[event].push(fn);
258
- }
259
- }
260
- }
261
- if (typeof plugin.install === 'function') {
262
- plugin.install(this, this._buildCtx(plugin));
263
- }
264
- if (typeof plugin.onEvent === 'function') {
265
- this._eventListeners.push(plugin.onEvent);
266
- }
267
- this._plugins.push(plugin);
268
- return this;
269
- }
270
-
271
- _buildCtx(plugin) {
272
- const self = this;
273
- return {
274
- name: plugin.name || 'anonymous',
275
- engine: this,
276
- plugin,
277
- on(hook, fn) { return self.on(hook, fn); },
278
- onEvent(fn) { return self.onEvent(fn); },
279
- emit(eventName, data) { self._emit(eventName, data); },
280
- tables() { return Array.from(self._tableNames); },
281
- hasTable(name) { return self._tableNames.has(name); },
282
- getTableSchema(name) { return self._schemas[name] || null; }
283
- };
284
- }
285
-
286
- on(event, fn) {
287
- if (this._hooks[event]) {
288
- this._hooks[event].push(fn);
289
- }
290
- return this;
291
- }
292
-
293
- onEvent(fn) {
294
- this._eventListeners.push(fn);
295
- return this;
296
- }
297
-
298
- _emit(eventName, data) {
299
- for (const fn of this._eventListeners) {
300
- try { fn(eventName, data); } catch (e) { /* ignore */ }
301
- }
302
- }
303
-
304
- _runHooks(hookName, args) {
305
- const hooks = this._hooks[hookName];
306
- if (!hooks || hooks.length === 0) return true;
307
- if (this._inHook) {
308
- // 防止插件 hook 内重入 native 调用导致 N-API 崩溃(段错误)
309
- throw new Error('ER_PLUGIN_REENTRY: plugin hook "' + hookName + '" re-entered native call; plugin must not call engine methods inside its own hook');
310
- }
311
- this._inHook = true;
312
- try {
313
- for (const fn of hooks) {
314
- const r = fn(...args);
315
- if (r === false) return false;
316
- if (r !== undefined && args.length > 0) {
317
- args[0] = r;
318
- }
319
- }
320
- return true;
321
- } finally {
322
- this._inHook = false;
323
- }
324
- }
325
-
326
- async start() {
327
- if (this._mode !== 'memory') {
328
- if (!this._path) throw new Error('hybrid/disk mode requires a directory path');
329
- let r;
330
- try {
331
- r = safeParse(native.jsqlOpen(this._path, this._mode));
332
- } catch (e) {
333
- throw new Error('failed to open native storage: ' + e.message);
334
- }
335
- if (r && r.ok === false) throw new Error(r.error || 'open storage failed');
336
- if (r && Array.isArray(r.tables)) {
337
- this._tableNames = new Set(r.tables);
338
- if (r.schemas) this._schemas = r.schemas;
339
- }
340
- } else {
341
- try {
342
- JSON.parse(native.jsqlOpen('', 'memory'));
343
- } catch (e) {
344
- throw new Error('failed to open native memory storage: ' + e.message);
345
- }
346
- }
347
- if (this._mode !== 'memory') {
348
- if (this._flushInterval > 0) {
349
- this._diskFlushTimer = setInterval(() => {
350
- try { native.jsqlFlushDirty(); } catch (e) { /* ignore */ }
351
- }, this._flushInterval);
352
- if (this._diskFlushTimer.unref) this._diskFlushTimer.unref();
353
- }
354
- this._evictTimer = setInterval(() => {
355
- try { this._checkMemory(); } catch (e) { /* ignore */ }
356
- }, this._evictInterval);
357
- if (this._evictTimer.unref) this._evictTimer.unref();
358
- }
359
- this._runHooks('onStart', []);
360
- this._emit('start', {});
361
- }
362
-
363
- _checkMemory() {
364
- const total = os.totalmem();
365
- if (!total) return;
366
- const budget = total - this._memReserveMB * 1024 * 1024;
367
- if (budget <= 0) return;
368
- if (process.memoryUsage().rss <= budget) return;
369
- for (let i = 0; i < 16; i++) {
370
- let r;
371
- try { r = JSON.parse(native.jsqlEvict()); } catch (e) { return; }
372
- if (r.ok === false || !r.evicted || r.remaining === 0) return;
373
- if (process.memoryUsage().rss <= budget) return;
374
- }
375
- }
376
-
377
- _pkOf(table) {
378
- const schema = this._schemas[table];
379
- if (!schema) return null;
380
- for (const [k, def] of Object.entries(schema)) {
381
- const isPk = (typeof def === 'string' && /\bprimary\s+key\b/i.test(def))
382
- || !!(def && typeof def === 'object' && (def.primaryKey || def.primary_key));
383
- if (isPk) return k;
384
- }
385
- return null;
386
- }
387
-
388
- _pkAutoIncrement(table) {
389
- const schema = this._schemas[table];
390
- const pk = this._pkOf(table);
391
- if (!pk || !schema) return false;
392
- const def = schema[pk];
393
- if (typeof def === 'string') return /\bauto_?increment\b/i.test(def);
394
- return !!(def && def.autoIncrement);
395
- }
396
-
397
- _coercePkId(table, id) {
398
- const schema = this._schemas[table];
399
- const pk = this._pkOf(table);
400
- if (!schema || !pk) return id;
401
- const def = schema[pk];
402
- let t = null;
403
- if (typeof def === 'string') t = def.toLowerCase();
404
- else if (def && typeof def === 'object' && def.type) t = String(def.type).toLowerCase();
405
- if (['integer', 'int', 'bigint'].includes(t)) return Number(id);
406
- return id;
407
- }
408
-
409
- _findRawById(table, id) {
410
- const pk = this._pkOf(table);
411
- if (pk) {
412
- const filter = {};
413
- filter[pk] = this._coercePkId(table, id);
414
- const r = safeParse(native.jsqlFind(table, JSON.stringify(filter), 1, 0));
415
- if (r && r.error) return r;
416
- return Array.isArray(r) && r.length > 0 ? r[0] : null;
417
- }
418
- return safeParse(native.jsqlFindById(table, Number(id)));
419
- }
420
-
421
- _seqIdByPk(table, id) {
422
- const pk = this._pkOf(table);
423
- if (pk) {
424
- const filter = {};
425
- filter[pk] = this._coercePkId(table, id);
426
- const r = safeParse(native.jsqlFind(table, JSON.stringify(filter), 1, 0));
427
- if (Array.isArray(r) && r.length > 0) return r[0].id;
428
- return null;
429
- }
430
- return Number(id);
431
- }
432
-
433
- async _insertBatch(table, rows) {
434
- const schema = this._schemas[table];
435
- if (schema) {
436
- rows = rows.map(row => {
437
- const out = {};
438
- for (const [k, v] of Object.entries(row)) {
439
- if (v instanceof Date) out[k] = v.toISOString();
440
- else out[k] = v;
441
- }
442
- return out;
443
- });
444
- }
445
- const bin = encodeBatch(rows);
446
- const r = safeParse(native.jsqlInsertBuf(table, bin));
447
- if (r && r.error) throw new Error(r.error);
448
- if (r && Array.isArray(r) && !this._pkAutoIncrement(table)) {
449
- const pk = this._pkOf(table);
450
- if (pk) {
451
- return r.map((seq, i) => {
452
- const row = rows[i];
453
- return (row && row[pk] !== undefined && row[pk] !== null) ? row[pk] : seq;
454
- });
455
- }
456
- }
457
- return r;
458
- }
459
-
460
- _scheduleOpFlush() {
461
- if (this._opTimer) return;
462
- this._opTimer = setTimeout(() => {
463
- this._opTimer = null;
464
- this._flushOps();
465
- }, this._opFlushInterval);
466
- }
467
-
468
- _flushOps() {
469
- var remove = this._opBuffer.remove;
470
- var update = this._opBuffer.update;
471
- for (var table in remove) {
472
- var ids = remove[table];
473
- if (ids.size === 0) continue;
474
- var idsArr = Array.from(ids);
475
- var r = safeParse(native.jsqlRemoveByIds(table, JSON.stringify(idsArr)));
476
- this._emit('delete', { table, ids: idsArr, result: r });
477
- }
478
- for (var table in update) {
479
- var entries = update[table];
480
- if (entries.length === 0) continue;
481
- var r = safeParse(native.jsqlUpdateByIds(table, JSON.stringify(entries)));
482
- this._emit('update', { table, entries, result: r });
483
- }
484
- this._opBuffer = { remove: {}, update: {} };
485
- }
486
-
487
- async _flush() {
488
- this._flushOpsNow();
489
- if (!this._runHooks('beforeFlush', [])) return null;
490
- const flushed = {};
491
- for (const [table, rows] of Object.entries(this._buffer)) {
492
- if (rows.length === 0) continue;
493
- const r = await this._insertBatch(table, rows);
494
- flushed[table] = r;
495
- }
496
- this._buffer = {};
497
- this._bufferSize = 0;
498
- this._runHooks('afterFlush', []);
499
- return flushed;
500
- }
501
-
502
- _flushOpsNow() {
503
- if (this._opTimer) {
504
- clearTimeout(this._opTimer);
505
- this._opTimer = null;
506
- }
507
- this._flushOps();
508
- }
509
-
510
- async flush() {
511
- await this._flush();
512
- this._flushOpsNow();
513
- if (this._mode !== 'memory') {
514
- try { native.jsqlFlushDirty(); } catch (e) { /* ignore */ }
515
- }
516
- }
517
-
518
- async insert(table, data) {
519
- const arr = Array.isArray(data) ? data : [data];
520
- var filtered = arr;
521
- if (!this._runHooks('beforeInsert', [table, filtered])) return [];
522
- if (arr.length > 1) {
523
- await this._flush();
524
- let result;
525
- for (let i = 0; i < arr.length; i += this._flushThreshold) {
526
- const chunk = arr.slice(i, i + this._flushThreshold);
527
- const r = await this._insertBatch(table, chunk);
528
- if (r && r.error) throw new Error(r.error);
529
- if (!result) result = r;
530
- }
531
- this._emit('insert', { table, count: arr.length, ids: result });
532
- this._runHooks('afterInsert', [table, filtered, result]);
533
- return result;
534
- }
535
- if (!this._buffer[table]) this._buffer[table] = [];
536
- this._buffer[table].push(arr[0]);
537
- this._bufferSize++;
538
- const flushed = await this._flush();
539
- return flushed && flushed[table] ? flushed[table] : null;
540
- }
541
-
542
- async createTable(name, schema) {
543
- await this._flush();
544
- if (!this._runHooks('beforeCreateTable', [name, schema])) return null;
545
- const r = safeParse(native.jsqlCreateTable(name, JSON.stringify(mapNativeSchema(schema))));
546
- if (r && r.ok === false) throw new Error(r.error || 'create table failed');
547
- this._tableNames.add(name);
548
- this._schemas[name] = typeof schema === 'string' ? mapNativeSchema(schema) : schema;
549
- this._emit('createTable', { name, schema });
550
- this._runHooks('afterCreateTable', [name, schema]);
551
- return r;
552
- }
553
-
554
- async dropTable(name) {
555
- await this._flush();
556
- if (!this._runHooks('beforeDropTable', [name])) return null;
557
- const r = safeParse(native.jsqlDropTable(name));
558
- if (r && r.ok === false) throw new Error(r.error || 'drop table failed');
559
- this._tableNames.delete(name);
560
- delete this._schemas[name];
561
- this._emit('dropTable', { name });
562
- this._runHooks('afterDropTable', [name]);
563
- return r;
564
- }
565
-
566
- findById(table, id) {
567
- this._flushOpsNow();
568
- if (!this._runHooks('beforeFind', [table, { id }])) return null;
569
- const raw = this._findRawById(table, id);
570
- if (raw && raw.error) throw new Error(raw.error);
571
- this._runHooks('afterFind', [table, { id }, raw]);
572
- const schema = this._schemas[table];
573
- if (schema && raw && typeof raw === 'object') return restoreRow(raw, schema);
574
- return raw;
575
- }
576
-
577
- findByIds(table, ids) {
578
- this._flushOpsNow();
579
- if (!this._runHooks('beforeFind', [table, { ids }])) return null;
580
- let r;
581
- if (this._pkOf(table)) {
582
- r = ids.map(id => this._findRawById(table, id)).filter(x => x !== null && !(x && x.error));
583
- } else {
584
- r = safeParse(native.jsqlFindByIds(table, JSON.stringify(ids)));
585
- }
586
- if (r && r.error) throw new Error(r.error);
587
- this._runHooks('afterFind', [table, { ids }, r]);
588
- const schema = this._schemas[table];
589
- if (schema && Array.isArray(r)) return r.map(row => restoreRow(row, schema));
590
- return r;
591
- }
592
-
593
- findByIdsRaw(table, ids) {
594
- return this.findByIds(table, ids);
595
- }
596
-
597
- async find(table, filter, opts = {}) {
598
- this._flushOpsNow();
599
- if (!this._runHooks('beforeFind', [table, { filter, opts }])) return [];
600
- const filterStr = filter ? JSON.stringify(filter) : '';
601
- const { limit = 100, offset = 0 } = opts;
602
- const r = safeParse(native.jsqlFind(table, filterStr, limit, offset));
603
- if (r && r.error) throw new Error(r.error);
604
- this._runHooks('afterFind', [table, { filter, opts }, r]);
605
- const schema = this._schemas[table];
606
- if (schema && Array.isArray(r)) return r.map(row => restoreRow(row, schema));
607
- return r;
608
- }
609
-
610
- async count(table) {
611
- this._flushOpsNow();
612
- this._runHooks('beforeCount', [table]);
613
- const r = parseInt(native.jsqlCount(table), 10);
614
- const n = isNaN(r) ? 0 : r;
615
- this._runHooks('afterCount', [table, n]);
616
- return n;
617
- }
618
-
619
- updateByIds(table, entries) {
620
- const pairs = [];
621
- for (const [id, data] of entries) {
622
- const seq = this._seqIdByPk(table, id);
623
- if (seq !== null) pairs.push([seq, data]);
624
- }
625
- if (!this._runHooks('beforeUpdate', [table, pairs])) return;
626
- if (!this._opBuffer.update[table]) this._opBuffer.update[table] = [];
627
- this._opBuffer.update[table].push(...pairs);
628
- this._scheduleOpFlush();
629
- }
630
-
631
- removeByIds(table, ids) {
632
- if (!this._runHooks('beforeDelete', [table, ids])) return;
633
- if (!this._opBuffer.remove[table]) this._opBuffer.remove[table] = new Set();
634
- for (const id of ids) {
635
- const seq = this._seqIdByPk(table, id);
636
- if (seq !== null) this._opBuffer.remove[table].add(seq);
637
- }
638
- this._scheduleOpFlush();
639
- }
640
-
641
- updateById(table, id, data) {
642
- if (!this._runHooks('beforeUpdate', [table, id, data])) return;
643
- const seq = this._seqIdByPk(table, id);
644
- if (seq === null) return;
645
- if (!this._opBuffer.update[table]) this._opBuffer.update[table] = [];
646
- this._opBuffer.update[table].push([seq, data]);
647
- this._scheduleOpFlush();
648
- }
649
-
650
- removeById(table, id) {
651
- if (!this._runHooks('beforeDelete', [table, id])) return;
652
- const seq = this._seqIdByPk(table, id);
653
- if (seq === null) return;
654
- if (!this._opBuffer.remove[table]) this._opBuffer.remove[table] = new Set();
655
- this._opBuffer.remove[table].add(seq);
656
- this._scheduleOpFlush();
657
- }
658
-
659
- hasTable(name) {
660
- return this._tableNames.has(name);
661
- }
662
-
663
- getTables() {
664
- return Array.from(this._tableNames);
665
- }
666
-
667
- getTableSchema(name) {
668
- return this._schemas[name] || null;
669
- }
670
-
671
- /**
672
- * 直接执行原生 SQL 语句。本实例自身即充当 engine,
673
- * 支持 SELECT / INSERT / UPDATE / DELETE / CREATE TABLE 等常用语句。
674
- * @example
675
- * const rows = await db.query("SELECT * FROM users WHERE age > ?", [21]);
676
- * await db.query("UPDATE users SET age = age + 1 WHERE name = 'A'");
677
- */
678
- async query(sql, paramsOrOpts, opts) {
679
- return executeSQL(this, sql, paramsOrOpts, opts);
680
- }
681
-
682
- async stop() {
683
- this._flushOpsNow();
684
- await this._flush();
685
- if (this._diskFlushTimer) { clearInterval(this._diskFlushTimer); this._diskFlushTimer = null; }
686
- if (this._evictTimer) { clearInterval(this._evictTimer); this._evictTimer = null; }
687
- if (this._mode !== 'memory') {
688
- try { JSON.parse(native.jsqlClose()); } catch (e) { /* ignore */ }
689
- }
690
- this._runHooks('onStop', []);
691
- this._emit('stop', {});
692
- }
693
-
694
- async beginTx() {
695
- this._flushOpsNow();
696
- const r = safeParse(native.jsqlBeginTx());
697
- if (r && r.ok === false) throw new Error(r.error || 'begin transaction failed');
698
- this._txId = r.txId;
699
- return r.txId;
700
- }
701
-
702
- async beginTransaction() {
703
- return this.beginTx();
704
- }
705
-
706
- async commit() {
707
- if (this._txId === undefined) return true;
708
- const r = await this.commitTx(this._txId);
709
- this._txId = undefined;
710
- return r;
711
- }
712
-
713
- async rollback() {
714
- if (this._txId === undefined) return true;
715
- const r = await this.rollbackTx(this._txId);
716
- this._txId = undefined;
717
- return r;
718
- }
719
-
720
- async commitTx(txId) {
721
- const r = safeParse(native.jsqlCommitTx(String(txId)));
722
- if (r && r.ok === false) throw new Error(r.error || 'commit transaction failed');
723
- return true;
724
- }
725
-
726
- async rollbackTx(txId) {
727
- const r = safeParse(native.jsqlRollbackTx(String(txId)));
728
- if (r && r.ok === false) throw new Error(r.error || 'rollback transaction failed');
729
- return true;
730
- }
731
- }
732
-
1
+ const path = require('path');
2
+ const os = require('os');
3
+ const { executeSQL } = require('./sql');
4
+ const {
5
+ createHookRegistry, applyPlugin, buildPluginContext, registerHook,
6
+ runHooks, getPluginApis
7
+ } = require('./plugin');
8
+ const native = require(path.join(__dirname, '..', 'native', 'jsql-neo-native.node'));
9
+ const INT64_TAG = 1;
10
+ const FLOAT_TAG = 2;
11
+ const STR_TAG = 3;
12
+ const BOOL_TAG = 4;
13
+ const INT32_TAG = 5;
14
+
15
+ function safeParse(str, fallback) {
16
+ if (typeof str !== 'string') return fallback;
17
+ try { return JSON.parse(str); } catch (e) { return fallback; }
18
+ }
19
+
20
+ const NATIVE_TYPE_MAP = {
21
+ text: 'string',
22
+ varchar: 'string',
23
+ double: 'float',
24
+ number: 'float',
25
+ numeric: 'float',
26
+ decimal: 'float',
27
+ date: 'string',
28
+ timestamp: 'string',
29
+ datetime: 'string',
30
+ json: 'string',
31
+ array: 'string',
32
+ object: 'string',
33
+ bool: 'boolean',
34
+ bigint: 'string',
35
+ int: 'integer',
36
+ };
37
+
38
+ function parseShorthandSchema(str) {
39
+ const def = { type: str };
40
+ const strip = (re) => {
41
+ const next = def.type.replace(re, '').trim();
42
+ def.type = next || def.type;
43
+ };
44
+ if (/\bprimary\s+key\b/i.test(def.type)) { def.primaryKey = true; strip(/\bprimary\s+key\b/gi); }
45
+ if (/\bauto_?increment\b/i.test(def.type)) { def.autoIncrement = true; strip(/\bauto_?increment\b/gi); }
46
+ if (/\bnot\s+null\b/i.test(def.type)) { def.required = true; strip(/\bnot\s+null\b/gi); }
47
+ if (/\bunique\b/i.test(def.type)) { def.unique = true; strip(/\bunique\b/gi); }
48
+ if (/\bdefault\s+(\S+)/i.test(def.type)) {
49
+ const m = def.type.match(/\bdefault\s+(\S+)/i);
50
+ def.default = m[1].replace(/^['"]|['"]$/g, '');
51
+ strip(/\bdefault\s+\S+/gi);
52
+ }
53
+ return def;
54
+ }
55
+
56
+ function parseSchemaString(str) {
57
+ const out = {};
58
+ for (const seg of str.split(',')) {
59
+ const trimmed = seg.trim();
60
+ if (!trimmed) continue;
61
+ const parts = trimmed.split(/\s+/);
62
+ const name = parts.shift();
63
+ const def = parseShorthandSchema(parts.join(' ').toLowerCase().trim());
64
+ if (def.type.length === 0) def.type = 'string';
65
+ out[name] = def;
66
+ }
67
+ return out;
68
+ }
69
+
70
+ function mapNativeSchema(schema) {
71
+ if (typeof schema === 'string') schema = parseSchemaString(schema);
72
+ const mapped = {};
73
+ for (const [field, def] of Object.entries(schema || {})) {
74
+ if (typeof def === 'string') {
75
+ const parsed = parseShorthandSchema(def.toLowerCase().trim());
76
+ if (parsed.type.length === 0) parsed.type = 'string';
77
+ mapped[field] = { ...parsed, type: NATIVE_TYPE_MAP[parsed.type] || parsed.type };
78
+ } else if (def && typeof def === 'object') {
79
+ const t = (def.type || 'string').toLowerCase();
80
+ const out = { ...def, type: NATIVE_TYPE_MAP[t] || t };
81
+ if (out.primary_key !== undefined && out.primaryKey === undefined) { out.primaryKey = out.primary_key; delete out.primary_key; }
82
+ if (out.auto_increment !== undefined && out.autoIncrement === undefined) { out.autoIncrement = out.auto_increment; delete out.auto_increment; }
83
+ mapped[field] = out;
84
+ } else {
85
+ mapped[field] = { type: 'string' };
86
+ }
87
+ }
88
+ return mapped;
89
+ }
90
+
91
+ function restoreRow(row, schema) {
92
+ if (typeof row !== 'object' || row === null) return row;
93
+ let src = row;
94
+ if (row.fields && typeof row.fields === 'object' && row.fields !== null) {
95
+ src = { ...row.fields };
96
+ if (row.id !== undefined) {
97
+ const pkCols = [];
98
+ if (schema) {
99
+ for (const [k, def] of Object.entries(schema)) {
100
+ if (def && typeof def === 'object' && def.autoIncrement) continue;
101
+ const isPk = typeof def === 'string'
102
+ ? /\bprimary\s+key\b/i.test(def)
103
+ : !!(def && (def.primaryKey || def.primary_key));
104
+ if (isPk) pkCols.push(k);
105
+ }
106
+ } else if (src.id === undefined) {
107
+ pkCols.push('id');
108
+ }
109
+ for (const c of pkCols) {
110
+ const v = src[c];
111
+ if (v === undefined || v === null || v === 0 || v === '' || v === false) src[c] = row.id;
112
+ }
113
+ }
114
+ if (row.created_at !== undefined) src.created_at = row.created_at;
115
+ if (row.updated_at !== undefined) src.updated_at = row.updated_at;
116
+ }
117
+ if (!schema) return src;
118
+ const out = {};
119
+ for (const [field, value] of Object.entries(src)) {
120
+ const colDef = schema[field];
121
+ let t = null;
122
+ if (typeof colDef === 'string') t = colDef.toLowerCase();
123
+ else if (colDef && typeof colDef === 'object' && colDef.type) t = String(colDef.type).toLowerCase();
124
+ if (['json', 'array', 'object'].includes(t) && typeof value === 'string') {
125
+ try { out[field] = JSON.parse(value); } catch (e) { out[field] = value; }
126
+ } else if ((t === 'integer' || t === 'int' || t === 'bigint') && typeof value === 'string' && /^-?\d+$/.test(value)) {
127
+ out[field] = Number(value);
128
+ } else if ((t === 'float' || t === 'double' || t === 'number') && typeof value === 'string' && !Number.isNaN(Number(value))) {
129
+ out[field] = Number(value);
130
+ } else {
131
+ out[field] = value;
132
+ }
133
+ }
134
+ return out;
135
+ }
136
+
137
+ function _encodedFieldSize(v) {
138
+ if (v === null || v === undefined) return 1;
139
+ if (typeof v === 'number') {
140
+ if (Number.isInteger(v)) return (v >= -2147483648 && v <= 2147483647) ? 1 + 4 : 1 + 8;
141
+ return 1 + 8;
142
+ }
143
+ if (typeof v === 'boolean') return 1 + 1;
144
+ const s = typeof v === 'object' ? JSON.stringify(v) : String(v);
145
+ return 1 + 4 + Buffer.byteLength(s, 'utf8');
146
+ }
147
+
148
+ function encodeField(buf, off, v) {
149
+ if (v === null || v === undefined) {
150
+ buf.writeUInt8(0, off); return off + 1;
151
+ }
152
+ if (typeof v === 'number') {
153
+ if (Number.isInteger(v)) {
154
+ if (v >= -2147483648 && v <= 2147483647) {
155
+ buf.writeUInt8(INT32_TAG, off); buf.writeInt32LE(v, off + 1); return off + 5;
156
+ }
157
+ buf.writeUInt8(INT64_TAG, off); buf.writeBigInt64LE(BigInt(v), off + 1); return off + 9;
158
+ }
159
+ buf.writeUInt8(FLOAT_TAG, off); buf.writeDoubleLE(v, off + 1); return off + 9;
160
+ }
161
+ if (typeof v === 'string') {
162
+ const sl = Buffer.byteLength(v, 'utf8');
163
+ buf.writeUInt8(STR_TAG, off);
164
+ buf.writeUInt32LE(sl, off + 1);
165
+ buf.write(v, off + 5, sl, 'utf8');
166
+ return off + 5 + sl;
167
+ }
168
+ if (typeof v === 'boolean') {
169
+ buf.writeUInt8(BOOL_TAG, off); buf.writeUInt8(v ? 1 : 0, off + 1); return off + 2;
170
+ }
171
+ const s = typeof v === 'object' ? JSON.stringify(v) : String(v);
172
+ const sl = Buffer.byteLength(s, 'utf8');
173
+ buf.writeUInt8(STR_TAG, off);
174
+ buf.writeUInt32LE(sl, off + 1);
175
+ buf.write(s, off + 5, sl, 'utf8');
176
+ return off + 5 + sl;
177
+ }
178
+
179
+ function encodeBatch(rows) {
180
+ if (rows.length === 0) return new Uint8Array(0);
181
+ const fieldNames = Object.keys(rows[0]);
182
+ const nFields = fieldNames.length;
183
+ let size = 1;
184
+ for (const s of fieldNames) size += 1 + Buffer.byteLength(s, 'utf8');
185
+ size += 4;
186
+ for (const row of rows) {
187
+ for (let fi = 0; fi < nFields; fi++) size += _encodedFieldSize(row[fieldNames[fi]]);
188
+ }
189
+ const buf = Buffer.allocUnsafe(size);
190
+ let off = 0;
191
+
192
+ off = buf.writeUInt8(nFields, off);
193
+ for (let fi = 0; fi < nFields; fi++) {
194
+ const s = fieldNames[fi];
195
+ const nlen = Buffer.byteLength(s, 'utf8');
196
+ off = buf.writeUInt8(nlen, off);
197
+ off += buf.write(s, off, nlen, 'utf8');
198
+ }
199
+ off = buf.writeUInt32LE(rows.length, off);
200
+
201
+ for (let ri = 0; ri < rows.length; ri++) {
202
+ const row = rows[ri];
203
+ for (let fi = 0; fi < nFields; fi++) {
204
+ off = encodeField(buf, off, row[fieldNames[fi]]);
205
+ }
206
+ }
207
+
208
+ return buf.slice(0, off);
209
+ }
210
+
211
+ class JSQL {
212
+ constructor(opts = {}) {
213
+ this._flushThreshold = opts.flushThreshold || 5000;
214
+ this._buffer = {};
215
+ this._bufferSize = 0;
216
+ this._opBuffer = { remove: {}, update: {} };
217
+ this._opTimer = null;
218
+ this._opFlushInterval = opts.opFlushInterval || 50;
219
+ this._tableNames = new Set();
220
+ this._schemas = {};
221
+ this._txId = undefined;
222
+ this._autoPlugins = opts.modules !== false;
223
+
224
+ // 持久化模式: 'memory' | 'hybrid' | 'disk'
225
+ this._path = opts.path || null;
226
+ this._mode = opts.mode || (this._path ? 'hybrid' : 'memory');
227
+ this._memReserveMB = opts.memReserveMB !== undefined ? opts.memReserveMB : 512;
228
+ this._flushInterval = opts.flushInterval !== undefined
229
+ ? opts.flushInterval
230
+ : (this._mode === 'disk' ? 50 : 200);
231
+ this._evictInterval = opts.evictInterval !== undefined ? opts.evictInterval : 1000;
232
+ this._diskFlushTimer = null;
233
+ this._evictTimer = null;
234
+
235
+ this._plugins = [];
236
+ this._hooks = createHookRegistry();
237
+ // native 引擎:钩子内再次调用引擎方法会触发 N-API 重入崩溃,需显式防护
238
+ this._forbidReentry = true;
239
+ this._eventListeners = [];
240
+ if (this._autoPlugins) {
241
+ const { ModuleManager } = require('./mod');
242
+ new ModuleManager().applyTo(this);
243
+ }
244
+ }
245
+
246
+ use(plugin, opts) {
247
+ return applyPlugin(this, plugin, opts);
248
+ }
249
+
250
+ _buildCtx(plugin) {
251
+ return buildPluginContext(this, plugin);
252
+ }
253
+
254
+ on(event, fn) {
255
+ return registerHook(this, event, fn);
256
+ }
257
+
258
+ onEvent(fn) {
259
+ this._eventListeners.push(fn);
260
+ return this;
261
+ }
262
+
263
+ /** 广播事件(插件上下文 / 外部均可调用) */
264
+ emit(eventName, data) {
265
+ this._emit(eventName, data);
266
+ return this;
267
+ }
268
+
269
+ /** 主动触发一个钩子(含插件自定义钩子) */
270
+ runHook(hookName, ...args) {
271
+ return this._runHooks(hookName, args);
272
+ }
273
+
274
+ /** 取插件对外暴露的 API(由 plugin.api 声明) */
275
+ plugin(name) {
276
+ return getPluginApis(this).get(name) || null;
277
+ }
278
+
279
+ _emit(eventName, data) {
280
+ for (const fn of this._eventListeners) {
281
+ try { fn(eventName, data); } catch (e) { /* ignore */ }
282
+ }
283
+ }
284
+
285
+ _runHooks(hookName, args) {
286
+ return runHooks(this, hookName, args);
287
+ }
288
+
289
+ async start() {
290
+ if (this._mode !== 'memory') {
291
+ if (!this._path) throw new Error('hybrid/disk mode requires a directory path');
292
+ let r;
293
+ try {
294
+ r = safeParse(native.jsqlOpen(this._path, this._mode));
295
+ } catch (e) {
296
+ throw new Error('failed to open native storage: ' + e.message);
297
+ }
298
+ if (r && r.ok === false) throw new Error(r.error || 'open storage failed');
299
+ if (r && Array.isArray(r.tables)) {
300
+ this._tableNames = new Set(r.tables);
301
+ if (r.schemas) this._schemas = r.schemas;
302
+ }
303
+ } else {
304
+ try {
305
+ JSON.parse(native.jsqlOpen('', 'memory'));
306
+ } catch (e) {
307
+ throw new Error('failed to open native memory storage: ' + e.message);
308
+ }
309
+ }
310
+ if (this._mode !== 'memory') {
311
+ if (this._flushInterval > 0) {
312
+ this._diskFlushTimer = setInterval(() => {
313
+ try { native.jsqlFlushDirty(); } catch (e) { /* ignore */ }
314
+ }, this._flushInterval);
315
+ if (this._diskFlushTimer.unref) this._diskFlushTimer.unref();
316
+ }
317
+ this._evictTimer = setInterval(() => {
318
+ try { this._checkMemory(); } catch (e) { /* ignore */ }
319
+ }, this._evictInterval);
320
+ if (this._evictTimer.unref) this._evictTimer.unref();
321
+ }
322
+ this._runHooks('onStart', []);
323
+ this._emit('start', {});
324
+ }
325
+
326
+ _checkMemory() {
327
+ const total = os.totalmem();
328
+ if (!total) return;
329
+ const budget = total - this._memReserveMB * 1024 * 1024;
330
+ if (budget <= 0) return;
331
+ if (process.memoryUsage().rss <= budget) return;
332
+ for (let i = 0; i < 16; i++) {
333
+ let r;
334
+ try { r = JSON.parse(native.jsqlEvict()); } catch (e) { return; }
335
+ if (r.ok === false || !r.evicted || r.remaining === 0) return;
336
+ if (process.memoryUsage().rss <= budget) return;
337
+ }
338
+ }
339
+
340
+ _pkOf(table) {
341
+ const schema = this._schemas[table];
342
+ if (!schema) return null;
343
+ for (const [k, def] of Object.entries(schema)) {
344
+ const isPk = (typeof def === 'string' && /\bprimary\s+key\b/i.test(def))
345
+ || !!(def && typeof def === 'object' && (def.primaryKey || def.primary_key));
346
+ if (isPk) return k;
347
+ }
348
+ return null;
349
+ }
350
+
351
+ _pkAutoIncrement(table) {
352
+ const schema = this._schemas[table];
353
+ const pk = this._pkOf(table);
354
+ if (!pk || !schema) return false;
355
+ const def = schema[pk];
356
+ if (typeof def === 'string') return /\bauto_?increment\b/i.test(def);
357
+ return !!(def && def.autoIncrement);
358
+ }
359
+
360
+ _coercePkId(table, id) {
361
+ const schema = this._schemas[table];
362
+ const pk = this._pkOf(table);
363
+ if (!schema || !pk) return id;
364
+ const def = schema[pk];
365
+ let t = null;
366
+ if (typeof def === 'string') t = def.toLowerCase();
367
+ else if (def && typeof def === 'object' && def.type) t = String(def.type).toLowerCase();
368
+ if (['integer', 'int', 'bigint'].includes(t)) return Number(id);
369
+ return id;
370
+ }
371
+
372
+ _findRawById(table, id) {
373
+ const pk = this._pkOf(table);
374
+ if (pk) {
375
+ const filter = {};
376
+ filter[pk] = this._coercePkId(table, id);
377
+ const r = safeParse(native.jsqlFind(table, JSON.stringify(filter), 1, 0));
378
+ if (r && r.error) return r;
379
+ return Array.isArray(r) && r.length > 0 ? r[0] : null;
380
+ }
381
+ return safeParse(native.jsqlFindById(table, Number(id)));
382
+ }
383
+
384
+ _seqIdByPk(table, id) {
385
+ const pk = this._pkOf(table);
386
+ if (pk) {
387
+ const filter = {};
388
+ filter[pk] = this._coercePkId(table, id);
389
+ const r = safeParse(native.jsqlFind(table, JSON.stringify(filter), 1, 0));
390
+ if (Array.isArray(r) && r.length > 0) return r[0].id;
391
+ return null;
392
+ }
393
+ return Number(id);
394
+ }
395
+
396
+ async _insertBatch(table, rows) {
397
+ const schema = this._schemas[table];
398
+ if (schema) {
399
+ rows = rows.map(row => {
400
+ const out = {};
401
+ for (const [k, v] of Object.entries(row)) {
402
+ if (v instanceof Date) out[k] = v.toISOString();
403
+ else out[k] = v;
404
+ }
405
+ return out;
406
+ });
407
+ }
408
+ const bin = encodeBatch(rows);
409
+ const r = safeParse(native.jsqlInsertBuf(table, bin));
410
+ if (r && r.error) throw new Error(r.error);
411
+ if (r && Array.isArray(r) && !this._pkAutoIncrement(table)) {
412
+ const pk = this._pkOf(table);
413
+ if (pk) {
414
+ return r.map((seq, i) => {
415
+ const row = rows[i];
416
+ return (row && row[pk] !== undefined && row[pk] !== null) ? row[pk] : seq;
417
+ });
418
+ }
419
+ }
420
+ return r;
421
+ }
422
+
423
+ _scheduleOpFlush() {
424
+ if (this._opTimer) return;
425
+ this._opTimer = setTimeout(() => {
426
+ this._opTimer = null;
427
+ this._flushOps();
428
+ }, this._opFlushInterval);
429
+ }
430
+
431
+ _flushOps() {
432
+ var remove = this._opBuffer.remove;
433
+ var update = this._opBuffer.update;
434
+ for (var table in remove) {
435
+ var ids = remove[table];
436
+ if (ids.size === 0) continue;
437
+ var idsArr = Array.from(ids);
438
+ var r = safeParse(native.jsqlRemoveByIds(table, JSON.stringify(idsArr)));
439
+ this._emit('delete', { table, ids: idsArr, result: r });
440
+ }
441
+ for (var table in update) {
442
+ var entries = update[table];
443
+ if (entries.length === 0) continue;
444
+ var r = safeParse(native.jsqlUpdateByIds(table, JSON.stringify(entries)));
445
+ this._emit('update', { table, entries, result: r });
446
+ }
447
+ this._opBuffer = { remove: {}, update: {} };
448
+ }
449
+
450
+ async _flush() {
451
+ this._flushOpsNow();
452
+ if (!this._runHooks('beforeFlush', [])) return null;
453
+ const flushed = {};
454
+ for (const [table, rows] of Object.entries(this._buffer)) {
455
+ if (rows.length === 0) continue;
456
+ const r = await this._insertBatch(table, rows);
457
+ flushed[table] = r;
458
+ }
459
+ this._buffer = {};
460
+ this._bufferSize = 0;
461
+ this._runHooks('afterFlush', []);
462
+ return flushed;
463
+ }
464
+
465
+ _flushOpsNow() {
466
+ if (this._opTimer) {
467
+ clearTimeout(this._opTimer);
468
+ this._opTimer = null;
469
+ }
470
+ this._flushOps();
471
+ }
472
+
473
+ async flush() {
474
+ await this._flush();
475
+ this._flushOpsNow();
476
+ if (this._mode !== 'memory') {
477
+ try { native.jsqlFlushDirty(); } catch (e) { /* ignore */ }
478
+ }
479
+ }
480
+
481
+ async insert(table, data) {
482
+ const arr = Array.isArray(data) ? data : [data];
483
+ var filtered = arr;
484
+ if (!this._runHooks('beforeInsert', [table, filtered])) return [];
485
+ if (arr.length > 1) {
486
+ await this._flush();
487
+ let result;
488
+ for (let i = 0; i < arr.length; i += this._flushThreshold) {
489
+ const chunk = arr.slice(i, i + this._flushThreshold);
490
+ const r = await this._insertBatch(table, chunk);
491
+ if (r && r.error) throw new Error(r.error);
492
+ if (!result) result = r;
493
+ }
494
+ this._emit('insert', { table, count: arr.length, ids: result });
495
+ this._runHooks('afterInsert', [table, filtered, result]);
496
+ return result;
497
+ }
498
+ if (!this._buffer[table]) this._buffer[table] = [];
499
+ this._buffer[table].push(arr[0]);
500
+ this._bufferSize++;
501
+ const flushed = await this._flush();
502
+ const result = flushed && flushed[table] ? flushed[table] : null;
503
+ this._emit('insert', { table, count: arr.length, ids: result });
504
+ this._runHooks('afterInsert', [table, filtered, result]);
505
+ return result;
506
+ }
507
+
508
+ async createTable(name, schema) {
509
+ await this._flush();
510
+ if (typeof schema === 'string') schema = parseSchemaString(schema);
511
+ if (!this._runHooks('beforeCreateTable', [name, schema])) return null;
512
+ const r = safeParse(native.jsqlCreateTable(name, JSON.stringify(mapNativeSchema(schema))));
513
+ if (r && r.ok === false) throw new Error(r.error || 'create table failed');
514
+ this._tableNames.add(name);
515
+ this._schemas[name] = typeof schema === 'string' ? mapNativeSchema(schema) : schema;
516
+ this._emit('createTable', { name, schema });
517
+ this._runHooks('afterCreateTable', [name, schema]);
518
+ return r;
519
+ }
520
+
521
+ async addColumn(table, name, def) {
522
+ await this._flush();
523
+ const mapped = mapNativeSchema({ [name]: def })[name];
524
+ const r = safeParse(native.jsqlAddColumn(table, name, JSON.stringify(mapped)));
525
+ if (r && r.ok === false) throw new Error(r.error || 'add column failed');
526
+ if (!this._schemas[table]) this._schemas[table] = {};
527
+ this._schemas[table][name] = mapped;
528
+ this._emit('addColumn', { table, name, def: mapped });
529
+ return r;
530
+ }
531
+
532
+ async dropTable(name) {
533
+ await this._flush();
534
+ if (!this._runHooks('beforeDropTable', [name])) return null;
535
+ const r = safeParse(native.jsqlDropTable(name));
536
+ if (r && r.ok === false) throw new Error(r.error || 'drop table failed');
537
+ this._tableNames.delete(name);
538
+ delete this._schemas[name];
539
+ this._emit('dropTable', { name });
540
+ this._runHooks('afterDropTable', [name]);
541
+ return r;
542
+ }
543
+
544
+ findById(table, id) {
545
+ this._flushOpsNow();
546
+ if (!this._runHooks('beforeFind', [table, { id }])) return null;
547
+ const raw = this._findRawById(table, id);
548
+ if (raw && raw.error) throw new Error(raw.error);
549
+ this._runHooks('afterFind', [table, { id }, raw]);
550
+ const schema = this._schemas[table];
551
+ if (schema && raw && typeof raw === 'object') return restoreRow(raw, schema);
552
+ return raw;
553
+ }
554
+
555
+ findByIds(table, ids) {
556
+ this._flushOpsNow();
557
+ if (!this._runHooks('beforeFind', [table, { ids }])) return null;
558
+ let r;
559
+ if (this._pkOf(table)) {
560
+ r = ids.map(id => this._findRawById(table, id)).filter(x => x !== null && !(x && x.error));
561
+ } else {
562
+ r = safeParse(native.jsqlFindByIds(table, JSON.stringify(ids)));
563
+ }
564
+ if (r && r.error) throw new Error(r.error);
565
+ this._runHooks('afterFind', [table, { ids }, r]);
566
+ const schema = this._schemas[table];
567
+ if (schema && Array.isArray(r)) return r.map(row => restoreRow(row, schema));
568
+ return r;
569
+ }
570
+
571
+ findByIdsRaw(table, ids) {
572
+ return this.findByIds(table, ids);
573
+ }
574
+
575
+ async find(table, filter, opts = {}) {
576
+ this._flushOpsNow();
577
+ if (!this._runHooks('beforeFind', [table, { filter, opts }])) return [];
578
+ const filterStr = filter ? JSON.stringify(filter) : '';
579
+ const { limit = 100, offset = 0 } = opts;
580
+ const r = safeParse(native.jsqlFind(table, filterStr, limit, offset));
581
+ if (r && r.error) throw new Error(r.error);
582
+ this._runHooks('afterFind', [table, { filter, opts }, r]);
583
+ const schema = this._schemas[table];
584
+ if (schema && Array.isArray(r)) return r.map(row => restoreRow(row, schema));
585
+ return r;
586
+ }
587
+
588
+ async count(table) {
589
+ this._flushOpsNow();
590
+ this._runHooks('beforeCount', [table]);
591
+ const r = parseInt(native.jsqlCount(table), 10);
592
+ const n = isNaN(r) ? 0 : r;
593
+ this._runHooks('afterCount', [table, n]);
594
+ return n;
595
+ }
596
+
597
+ updateByIds(table, entries) {
598
+ const pairs = [];
599
+ for (const [id, data] of entries) {
600
+ const seq = this._seqIdByPk(table, id);
601
+ if (seq !== null) pairs.push([seq, data]);
602
+ }
603
+ if (!this._runHooks('beforeUpdate', [table, pairs])) return;
604
+ if (!this._opBuffer.update[table]) this._opBuffer.update[table] = [];
605
+ this._opBuffer.update[table].push(...pairs);
606
+ this._scheduleOpFlush();
607
+ }
608
+
609
+ removeByIds(table, ids) {
610
+ if (!this._runHooks('beforeDelete', [table, ids])) return;
611
+ if (!this._opBuffer.remove[table]) this._opBuffer.remove[table] = new Set();
612
+ for (const id of ids) {
613
+ const seq = this._seqIdByPk(table, id);
614
+ if (seq !== null) this._opBuffer.remove[table].add(seq);
615
+ }
616
+ this._scheduleOpFlush();
617
+ }
618
+
619
+ updateById(table, id, data) {
620
+ if (!this._runHooks('beforeUpdate', [table, id, data])) return;
621
+ const seq = this._seqIdByPk(table, id);
622
+ if (seq === null) return;
623
+ if (!this._opBuffer.update[table]) this._opBuffer.update[table] = [];
624
+ this._opBuffer.update[table].push([seq, data]);
625
+ this._scheduleOpFlush();
626
+ }
627
+
628
+ removeById(table, id) {
629
+ if (!this._runHooks('beforeDelete', [table, id])) return;
630
+ const seq = this._seqIdByPk(table, id);
631
+ if (seq === null) return;
632
+ if (!this._opBuffer.remove[table]) this._opBuffer.remove[table] = new Set();
633
+ this._opBuffer.remove[table].add(seq);
634
+ this._scheduleOpFlush();
635
+ }
636
+
637
+ hasTable(name) {
638
+ return this._tableNames.has(name);
639
+ }
640
+
641
+ getTables() {
642
+ return Array.from(this._tableNames);
643
+ }
644
+
645
+ getTableSchema(name) {
646
+ return this._schemas[name] || null;
647
+ }
648
+
649
+ /**
650
+ * 直接执行原生 SQL 语句。本实例自身即充当 engine,
651
+ * 支持 SELECT / INSERT / UPDATE / DELETE / CREATE TABLE 等常用语句。
652
+ * @example
653
+ * const rows = await db.query("SELECT * FROM users WHERE age > ?", [21]);
654
+ * await db.query("UPDATE users SET age = age + 1 WHERE name = 'A'");
655
+ */
656
+ async query(sql, paramsOrOpts, opts) {
657
+ if (!this._runHooks('beforeQuery', [sql, paramsOrOpts, opts])) return null;
658
+ const result = await executeSQL(this, sql, paramsOrOpts, opts);
659
+ this._runHooks('afterQuery', [sql, paramsOrOpts, opts, result]);
660
+ return result;
661
+ }
662
+
663
+ async exists(table, filter = {}) {
664
+ const rows = await this.find(table, filter, { limit: 1 });
665
+ return Array.isArray(rows) && rows.length > 0;
666
+ }
667
+
668
+ prepare(sql) {
669
+ return require('./prepared').createPrepared(this, sql);
670
+ }
671
+
672
+ async stop() {
673
+ this._flushOpsNow();
674
+ await this._flush();
675
+ if (this._diskFlushTimer) { clearInterval(this._diskFlushTimer); this._diskFlushTimer = null; }
676
+ if (this._evictTimer) { clearInterval(this._evictTimer); this._evictTimer = null; }
677
+ if (this._mode !== 'memory') {
678
+ try { JSON.parse(native.jsqlClose()); } catch (e) { /* ignore */ }
679
+ }
680
+ this._runHooks('onStop', []);
681
+ this._emit('stop', {});
682
+ }
683
+
684
+ async beginTx() {
685
+ this._flushOpsNow();
686
+ const r = safeParse(native.jsqlBeginTx());
687
+ if (r && r.ok === false) throw new Error(r.error || 'begin transaction failed');
688
+ this._txId = r.txId;
689
+ return r.txId;
690
+ }
691
+
692
+ async beginTransaction() {
693
+ return this.beginTx();
694
+ }
695
+
696
+ async commit() {
697
+ if (this._txId === undefined) return true;
698
+ const r = await this.commitTx(this._txId);
699
+ this._txId = undefined;
700
+ return r;
701
+ }
702
+
703
+ async rollback() {
704
+ if (this._txId === undefined) return true;
705
+ const r = await this.rollbackTx(this._txId);
706
+ this._txId = undefined;
707
+ return r;
708
+ }
709
+
710
+ async commitTx(txId) {
711
+ const r = safeParse(native.jsqlCommitTx(String(txId)));
712
+ if (r && r.ok === false) throw new Error(r.error || 'commit transaction failed');
713
+ return true;
714
+ }
715
+
716
+ async rollbackTx(txId) {
717
+ const r = safeParse(native.jsqlRollbackTx(String(txId)));
718
+ if (r && r.ok === false) throw new Error(r.error || 'rollback transaction failed');
719
+ return true;
720
+ }
721
+ }
722
+
733
723
  module.exports = { JSQL };