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
package/wasm/browser.mjs CHANGED
@@ -1,569 +1,591 @@
1
- import {
2
- jsql_reset,
3
- jsql_create_table,
4
- jsql_drop_table,
5
- jsql_insert_json,
6
- jsql_find,
7
- jsql_find_by_id,
8
- jsql_find_by_ids,
9
- jsql_update_by_id,
10
- jsql_update_by_ids,
11
- jsql_remove_by_id,
12
- jsql_remove_by_ids,
13
- jsql_count,
14
- jsql_begin_tx,
15
- jsql_commit_tx,
16
- jsql_rollback_tx,
17
- } from './browser_bg.mjs';
18
- import init from './browser_bg.mjs';
19
-
20
- function safeJsonParse(str) {
21
- try { return JSON.parse(str); } catch { return str; }
22
- }
23
-
24
- const NATIVE_TYPE_MAP = {
25
- text: 'string',
26
- varchar: 'string',
27
- double: 'float',
28
- number: 'float',
29
- numeric: 'float',
30
- decimal: 'float',
31
- date: 'string',
32
- timestamp: 'string',
33
- datetime: 'string',
34
- json: 'string',
35
- array: 'string',
36
- object: 'string',
37
- bool: 'boolean',
38
- bigint: 'string',
39
- int: 'integer',
40
- };
41
-
42
- function parseShorthandSchema(str) {
43
- const def = { type: str };
44
- const strip = (re) => {
45
- const next = def.type.replace(re, '').trim();
46
- def.type = next || def.type;
47
- };
48
- if (/\bprimary\s+key\b/i.test(def.type)) { def.primaryKey = true; strip(/\bprimary\s+key\b/gi); }
49
- if (/\bauto_?increment\b/i.test(def.type)) { def.autoIncrement = true; strip(/\bauto_?increment\b/gi); }
50
- if (/\bnot\s+null\b/i.test(def.type)) { def.required = true; strip(/\bnot\s+null\b/gi); }
51
- if (/\bunique\b/i.test(def.type)) { def.unique = true; strip(/\bunique\b/gi); }
52
- if (/\bdefault\s+(\S+)/i.test(def.type)) {
53
- const m = def.type.match(/\bdefault\s+(\S+)/i);
54
- def.default = m[1].replace(/^['"]|['"]$/g, '');
55
- strip(/\bdefault\s+\S+/gi);
56
- }
57
- return def;
58
- }
59
-
60
- function parseSchemaString(str) {
61
- const out = {};
62
- for (const seg of str.split(',')) {
63
- const trimmed = seg.trim();
64
- if (!trimmed) continue;
65
- const parts = trimmed.split(/\s+/);
66
- const name = parts.shift();
67
- const def = parseShorthandSchema(parts.join(' ').toLowerCase().trim());
68
- if (def.type.length === 0) def.type = 'string';
69
- out[name] = def;
70
- }
71
- return out;
72
- }
73
-
74
- function mapNativeSchema(schema) {
75
- if (typeof schema === 'string') schema = parseSchemaString(schema);
76
- const mapped = {};
77
- for (const [field, def] of Object.entries(schema || {})) {
78
- if (typeof def === 'string') {
79
- const parsed = parseShorthandSchema(def.toLowerCase().trim());
80
- if (parsed.type.length === 0) parsed.type = 'string';
81
- mapped[field] = { ...parsed, type: NATIVE_TYPE_MAP[parsed.type] || parsed.type };
82
- } else if (def && typeof def === 'object') {
83
- const t = (def.type || 'string').toLowerCase();
84
- const out = { ...def, type: NATIVE_TYPE_MAP[t] || t };
85
- if (out.primary_key !== undefined && out.primaryKey === undefined) { out.primaryKey = out.primary_key; delete out.primary_key; }
86
- if (out.auto_increment !== undefined && out.autoIncrement === undefined) { out.autoIncrement = out.auto_increment; delete out.auto_increment; }
87
- mapped[field] = out;
88
- } else {
89
- mapped[field] = { type: 'string' };
90
- }
91
- }
92
- return mapped;
93
- }
94
-
95
- function restoreRow(row, schema) {
96
- if (typeof row !== 'object' || row === null) return row;
97
- let src = row;
98
- if (row.fields && typeof row.fields === 'object' && row.fields !== null) {
99
- src = { ...row.fields };
100
- if (row.id !== undefined) {
101
- const pkCols = [];
102
- if (schema) {
103
- for (const [k, def] of Object.entries(schema)) {
104
- if (def && typeof def === 'object' && def.autoIncrement) continue;
105
- const isPk = typeof def === 'string'
106
- ? /\bprimary\s+key\b/i.test(def)
107
- : !!(def && (def.primaryKey || def.primary_key));
108
- if (isPk) pkCols.push(k);
109
- }
110
- } else if (src.id === undefined) {
111
- pkCols.push('id');
112
- }
113
- for (const c of pkCols) {
114
- const v = src[c];
115
- if (v === undefined || v === null || v === 0 || v === '' || v === false) src[c] = row.id;
116
- }
117
- }
118
- if (row.created_at !== undefined) src.created_at = row.created_at;
119
- if (row.updated_at !== undefined) src.updated_at = row.updated_at;
120
- }
121
- if (!schema) return src;
122
- const out = {};
123
- for (const [field, value] of Object.entries(src)) {
124
- const colDef = schema[field];
125
- let t = null;
126
- if (typeof colDef === 'string') t = colDef.toLowerCase();
127
- else if (colDef && typeof colDef === 'object' && colDef.type) t = String(colDef.type).toLowerCase();
128
- if (['json', 'array', 'object'].includes(t) && typeof value === 'string') {
129
- try { out[field] = JSON.parse(value); } catch (e) { out[field] = value; }
130
- } else if ((t === 'integer' || t === 'int' || t === 'bigint') && typeof value === 'string' && /^-?\d+$/.test(value)) {
131
- out[field] = Number(value);
132
- } else if ((t === 'float' || t === 'double' || t === 'number') && typeof value === 'string' && !Number.isNaN(Number(value))) {
133
- out[field] = Number(value);
134
- } else {
135
- out[field] = value;
136
- }
137
- }
138
- return out;
139
- }
140
-
141
- const INT64_TAG = 1;
142
- const FLOAT_TAG = 2;
143
- const STR_TAG = 3;
144
- const BOOL_TAG = 4;
145
- const INT32_TAG = 5;
146
-
147
-
148
- export class JSQL {
149
- constructor(opts = {}) {
150
- this._flushThreshold = opts.flushThreshold || 5000;
151
- this._buffer = {};
152
- this._bufferSize = 0;
153
- this._tableNames = new Set();
154
- this._schemas = {};
155
- this._txId = undefined;
156
- this._autoPlugins = opts.modules !== false;
157
-
158
- this._plugins = [];
159
- this._hooks = {
160
- beforeInsert: [], afterInsert: [],
161
- beforeUpdate: [], afterUpdate: [],
162
- beforeDelete: [], afterDelete: [],
163
- beforeFind: [], afterFind: [],
164
- beforeCreateTable: [], afterCreateTable: [],
165
- beforeDropTable: [], afterDropTable: [],
166
- beforeFlush: [], afterFlush: [],
167
- beforeCount: [], afterCount: [],
168
- onStart: [], onStop: []
169
- };
170
- this._eventListeners = [];
171
- if (this._autoPlugins && typeof globalThis.__jsqlLoadModules === 'function') {
172
- globalThis.__jsqlLoadModules(this);
173
- }
174
- }
175
-
176
- use(plugin) {
177
- if (typeof plugin === 'function') {
178
- plugin = { install: plugin };
179
- }
180
- if (plugin.hooks) {
181
- for (const [event, fn] of Object.entries(plugin.hooks)) {
182
- if (this._hooks[event]) {
183
- this._hooks[event].push(fn);
184
- }
185
- }
186
- }
187
- if (typeof plugin.install === 'function') {
188
- plugin.install(this, this._buildCtx(plugin));
189
- }
190
- if (typeof plugin.onEvent === 'function') {
191
- this._eventListeners.push(plugin.onEvent);
192
- }
193
- this._plugins.push(plugin);
194
- return this;
195
- }
196
-
197
- _buildCtx(plugin) {
198
- const self = this;
199
- return {
200
- name: plugin.name || 'anonymous',
201
- engine: this,
202
- plugin,
203
- on(hook, fn) { return self.on(hook, fn); },
204
- onEvent(fn) { return self.onEvent(fn); },
205
- emit(eventName, data) { self._emit(eventName, data); },
206
- tables() { return Array.from(self._tableNames); },
207
- hasTable(name) { return self._tableNames.has(name); },
208
- getTableSchema(name) { return self._schemas[name] || null; }
209
- };
210
- }
211
-
212
- on(event, fn) {
213
- if (this._hooks[event]) {
214
- this._hooks[event].push(fn);
215
- }
216
- return this;
217
- }
218
-
219
- onEvent(fn) {
220
- this._eventListeners.push(fn);
221
- return this;
222
- }
223
-
224
- _emit(eventName, data) {
225
- for (const fn of this._eventListeners) {
226
- try { fn(eventName, data); } catch (e) { /* ignore */ }
227
- }
228
- }
229
-
230
- _runHooks(hookName, args) {
231
- const hooks = this._hooks[hookName];
232
- if (!hooks || hooks.length === 0) return true;
233
- for (const fn of hooks) {
234
- const r = fn(...args);
235
- if (r === false) return false;
236
- if (r !== undefined && args.length > 0) {
237
- args[0] = r;
238
- }
239
- }
240
- return true;
241
- }
242
-
243
- async start() {
244
- await init();
245
- jsql_reset();
246
- this._runHooks('onStart', []);
247
- this._emit('start', {});
248
- }
249
-
250
- _pkOf(table) {
251
- const schema = this._schemas[table];
252
- if (!schema) return null;
253
- for (const [k, def] of Object.entries(schema)) {
254
- const isPk = (typeof def === 'string' && /\bprimary\s+key\b/i.test(def))
255
- || !!(def && typeof def === 'object' && (def.primaryKey || def.primary_key));
256
- if (isPk) return k;
257
- }
258
- return null;
259
- }
260
-
261
- _pkAutoIncrement(table) {
262
- const schema = this._schemas[table];
263
- const pk = this._pkOf(table);
264
- if (!pk || !schema) return false;
265
- const def = schema[pk];
266
- if (typeof def === 'string') return /\bauto_?increment\b/i.test(def);
267
- return !!(def && def.autoIncrement);
268
- }
269
-
270
- _coercePkId(table, id) {
271
- const schema = this._schemas[table];
272
- const pk = this._pkOf(table);
273
- if (!schema || !pk) return id;
274
- const def = schema[pk];
275
- let t = null;
276
- if (typeof def === 'string') t = def.toLowerCase();
277
- else if (def && typeof def === 'object' && def.type) t = String(def.type).toLowerCase();
278
- if (['integer', 'int', 'bigint'].includes(t)) return Number(id);
279
- return id;
280
- }
281
-
282
- _findRawById(table, id) {
283
- const pk = this._pkOf(table);
284
- if (pk) {
285
- const filter = {};
286
- filter[pk] = this._coercePkId(table, id);
287
- const r = safeJsonParse(jsql_find(table, JSON.stringify(filter), 1, 0));
288
- if (r && r.error) return r;
289
- return Array.isArray(r) && r.length > 0 ? r[0] : null;
290
- }
291
- return safeJsonParse(jsql_find_by_id(table, BigInt(id)));
292
- }
293
-
294
- _seqIdByPk(table, id) {
295
- const pk = this._pkOf(table);
296
- if (pk) {
297
- const filter = {};
298
- filter[pk] = this._coercePkId(table, id);
299
- const r = safeJsonParse(jsql_find(table, JSON.stringify(filter), 1, 0));
300
- if (Array.isArray(r) && r.length > 0) return r[0].id;
301
- return null;
302
- }
303
- return Number(id);
304
- }
305
-
306
- async _insertBatch(table, rows) {
307
- const schema = this._schemas[table];
308
- if (schema) {
309
- rows = rows.map(row => {
310
- const out = {};
311
- for (const [k, v] of Object.entries(row)) {
312
- const def = schema[k];
313
- let t = null;
314
- if (typeof def === 'string') t = def.toLowerCase();
315
- else if (def && typeof def === 'object' && def.type) t = String(def.type).toLowerCase();
316
- if (v !== null && v !== undefined && ['json', 'array', 'object'].includes(t) && typeof v !== 'string') {
317
- out[k] = JSON.stringify(v);
318
- } else if (v instanceof Date) {
319
- out[k] = v.toISOString();
320
- } else {
321
- out[k] = v;
322
- }
323
- }
324
- return out;
325
- });
326
- }
327
- const r = safeJsonParse(jsql_insert_json(table, JSON.stringify(rows)));
328
- if (r && r.error) throw new Error(r.error);
329
- if (r && Array.isArray(r) && !this._pkAutoIncrement(table)) {
330
- const pk = this._pkOf(table);
331
- if (pk) {
332
- return r.map((seq, i) => {
333
- const row = rows[i];
334
- return (row && row[pk] !== undefined && row[pk] !== null) ? row[pk] : seq;
335
- });
336
- }
337
- }
338
- return r;
339
- }
340
-
341
- async _flush() {
342
- if (!this._runHooks('beforeFlush', [])) return null;
343
- const flushed = {};
344
- for (const [table, rows] of Object.entries(this._buffer)) {
345
- if (rows.length === 0) continue;
346
- const r = await this._insertBatch(table, rows);
347
- flushed[table] = r;
348
- }
349
- this._buffer = {};
350
- this._bufferSize = 0;
351
- this._runHooks('afterFlush', []);
352
- return flushed;
353
- }
354
-
355
- async flush() {
356
- await this._flush();
357
- }
358
-
359
- async insert(table, data) {
360
- const arr = Array.isArray(data) ? data : [data];
361
- if (!this._runHooks('beforeInsert', [table, arr])) return [];
362
- if (arr.length > 1) {
363
- await this._flush();
364
- let result;
365
- for (let i = 0; i < arr.length; i += this._flushThreshold) {
366
- const chunk = arr.slice(i, i + this._flushThreshold);
367
- const r = await this._insertBatch(table, chunk);
368
- if (r && r.error) throw new Error(r.error);
369
- if (!result) result = r;
370
- }
371
- this._emit('insert', { table, count: arr.length, ids: result });
372
- this._runHooks('afterInsert', [table, arr, result]);
373
- return result;
374
- }
375
- if (!this._buffer[table]) this._buffer[table] = [];
376
- this._buffer[table].push(arr[0]);
377
- this._bufferSize++;
378
- const flushed = await this._flush();
379
- return flushed && flushed[table] ? flushed[table] : null;
380
- }
381
-
382
- async insertMany(table, data) {
383
- return this.insert(table, data);
384
- }
385
-
386
- async createTable(name, schema) {
387
- await this._flush();
388
- if (!this._runHooks('beforeCreateTable', [name, schema])) return null;
389
- const r = safeJsonParse(jsql_create_table(name, JSON.stringify(mapNativeSchema(schema))));
390
- if (r && r.ok === false) throw new Error(r.error || 'create table failed');
391
- this._tableNames.add(name);
392
- this._schemas[name] = typeof schema === 'string' ? mapNativeSchema(schema) : schema;
393
- this._emit('createTable', { name, schema });
394
- this._runHooks('afterCreateTable', [name, schema]);
395
- return r;
396
- }
397
-
398
- async dropTable(name) {
399
- await this._flush();
400
- if (!this._runHooks('beforeDropTable', [name])) return null;
401
- const r = safeJsonParse(jsql_drop_table(name));
402
- if (r && r.ok === false) throw new Error(r.error || 'drop table failed');
403
- this._tableNames.delete(name);
404
- delete this._schemas[name];
405
- this._emit('dropTable', { name });
406
- this._runHooks('afterDropTable', [name]);
407
- return r;
408
- }
409
-
410
- async findById(table, id) {
411
- await this._flush();
412
- if (!this._runHooks('beforeFind', [table, { id }])) return null;
413
- const r = this._findRawById(table, id);
414
- if (r && r.error) throw new Error(r.error);
415
- this._runHooks('afterFind', [table, { id }, r]);
416
- const schema = this._schemas[table];
417
- if (schema && r && typeof r === 'object') return restoreRow(r, schema);
418
- return r;
419
- }
420
-
421
- async find(table, filter, opts = {}) {
422
- await this._flush();
423
- if (!this._runHooks('beforeFind', [table, { filter, opts }])) return [];
424
- const filterStr = filter ? JSON.stringify(filter) : '';
425
- const { limit = 100, offset = 0 } = opts;
426
- const r = safeJsonParse(jsql_find(table, filterStr, limit, offset));
427
- if (r && r.error) throw new Error(r.error);
428
- this._runHooks('afterFind', [table, { filter, opts }, r]);
429
- const schema = this._schemas[table];
430
- if (schema && Array.isArray(r)) return r.map(row => restoreRow(row, schema));
431
- return r;
432
- }
433
-
434
- async count(table) {
435
- await this._flush();
436
- this._runHooks('beforeCount', [table]);
437
- const r = parseInt(jsql_count(table), 10);
438
- const n = isNaN(r) ? 0 : r;
439
- this._runHooks('afterCount', [table, n]);
440
- return n;
441
- }
442
-
443
- async updateByIds(table, entries) {
444
- const pairs = [];
445
- for (const [id, data] of entries) {
446
- const seq = this._seqIdByPk(table, id);
447
- if (seq !== null) pairs.push([seq, data]);
448
- }
449
- if (!this._runHooks('beforeUpdate', [table, pairs])) return;
450
- await this._flush();
451
- const r = safeJsonParse(jsql_update_by_ids(table, JSON.stringify(pairs)));
452
- if (r && r.error) throw new Error(r.error);
453
- this._emit('update', { table, entries: pairs, result: r });
454
- this._runHooks('afterUpdate', [table, pairs, r]);
455
- return r;
456
- }
457
-
458
- async removeByIds(table, ids) {
459
- if (!this._runHooks('beforeDelete', [table, ids])) return;
460
- await this._flush();
461
- const seqs = ids.map(id => this._seqIdByPk(table, id)).filter(s => s !== null);
462
- const r = safeJsonParse(jsql_remove_by_ids(table, JSON.stringify(seqs)));
463
- if (r && r.error) throw new Error(r.error);
464
- this._emit('delete', { table, ids: seqs, result: r });
465
- this._runHooks('afterDelete', [table, ids, r]);
466
- return r;
467
- }
468
-
469
- async findByIds(table, ids) {
470
- await this._flush();
471
- if (!this._runHooks('beforeFind', [table, { ids }])) return null;
472
- let r;
473
- if (this._pkOf(table)) {
474
- r = ids.map(id => this._findRawById(table, id)).filter(x => x !== null && !(x && x.error));
475
- } else {
476
- r = safeJsonParse(jsql_find_by_ids(table, JSON.stringify(ids)));
477
- }
478
- if (r && r.error) throw new Error(r.error);
479
- this._runHooks('afterFind', [table, { ids }, r]);
480
- const schema = this._schemas[table];
481
- if (schema && Array.isArray(r)) return r.map(row => restoreRow(row, schema));
482
- return r;
483
- }
484
-
485
- findByIdsRaw(table, ids) {
486
- return this.findByIds(table, ids);
487
- }
488
-
489
- async updateById(table, id, data) {
490
- if (!this._runHooks('beforeUpdate', [table, id, data])) return;
491
- await this._flush();
492
- const seq = this._seqIdByPk(table, id);
493
- if (seq === null) return null;
494
- const r = safeJsonParse(jsql_update_by_id(table, BigInt(seq), JSON.stringify(data)));
495
- if (r && r.ok === false) throw new Error(r.error || 'update failed');
496
- this._emit('update', { table, id, data });
497
- this._runHooks('afterUpdate', [table, id, data, r]);
498
- return r;
499
- }
500
-
501
- async removeById(table, id) {
502
- if (!this._runHooks('beforeDelete', [table, id])) return;
503
- await this._flush();
504
- const seq = this._seqIdByPk(table, id);
505
- if (seq === null) return null;
506
- const r = safeJsonParse(jsql_remove_by_id(table, BigInt(seq)));
507
- if (r && r.ok === false) throw new Error(r.error || 'remove failed');
508
- this._emit('delete', { table, id });
509
- this._runHooks('afterDelete', [table, id, r]);
510
- return r;
511
- }
512
-
513
- async beginTx() {
514
- await this._flush();
515
- const r = safeJsonParse(jsql_begin_tx());
516
- if (r && r.ok === false) throw new Error(r.error || 'begin transaction failed');
517
- this._txId = r.txId;
518
- return r.txId;
519
- }
520
-
521
- async commitTx(txId) {
522
- const r = safeJsonParse(jsql_commit_tx(String(txId)));
523
- if (r && r.ok === false) throw new Error(r.error || 'commit transaction failed');
524
- return true;
525
- }
526
-
527
- async rollbackTx(txId) {
528
- const r = safeJsonParse(jsql_rollback_tx(String(txId)));
529
- if (r && r.ok === false) throw new Error(r.error || 'rollback transaction failed');
530
- return true;
531
- }
532
-
533
- async beginTransaction() {
534
- return this.beginTx();
535
- }
536
-
537
- async commit() {
538
- if (this._txId === undefined) return true;
539
- const r = await this.commitTx(this._txId);
540
- this._txId = undefined;
541
- return r;
542
- }
543
-
544
- async rollback() {
545
- if (this._txId === undefined) return true;
546
- const r = await this.rollbackTx(this._txId);
547
- this._txId = undefined;
548
- return r;
549
- }
550
-
551
- async hasTable(name) {
552
- return this._tableNames.has(name);
553
- }
554
-
555
- async getTables() {
556
- return Array.from(this._tableNames);
557
- }
558
-
559
- async getTableSchema(name) {
560
- return this._schemas[name] || null;
561
- }
562
-
563
- async stop() {
564
- await this._flush();
565
- this._runHooks('onStop', []);
566
- this._emit('stop', {});
567
- }
568
- }
569
-
1
+ import {
2
+ jsql_reset,
3
+ jsql_create_table,
4
+ jsql_add_column,
5
+ jsql_drop_table,
6
+ jsql_insert_json,
7
+ jsql_find,
8
+ jsql_find_by_id,
9
+ jsql_find_by_ids,
10
+ jsql_update_by_id,
11
+ jsql_update_by_ids,
12
+ jsql_remove_by_id,
13
+ jsql_remove_by_ids,
14
+ jsql_count,
15
+ jsql_begin_tx,
16
+ jsql_commit_tx,
17
+ jsql_rollback_tx,
18
+ } from './browser_bg.mjs';
19
+ import init from './browser_bg.mjs';
20
+
21
+ function safeJsonParse(str) {
22
+ try { return JSON.parse(str); } catch { return str; }
23
+ }
24
+
25
+ const NATIVE_TYPE_MAP = {
26
+ text: 'string',
27
+ varchar: 'string',
28
+ double: 'float',
29
+ number: 'float',
30
+ numeric: 'float',
31
+ decimal: 'float',
32
+ date: 'string',
33
+ timestamp: 'string',
34
+ datetime: 'string',
35
+ json: 'string',
36
+ array: 'string',
37
+ object: 'string',
38
+ bool: 'boolean',
39
+ bigint: 'string',
40
+ int: 'integer',
41
+ };
42
+
43
+ function parseShorthandSchema(str) {
44
+ const def = { type: str };
45
+ const strip = (re) => {
46
+ const next = def.type.replace(re, '').trim();
47
+ def.type = next || def.type;
48
+ };
49
+ if (/\bprimary\s+key\b/i.test(def.type)) { def.primaryKey = true; strip(/\bprimary\s+key\b/gi); }
50
+ if (/\bauto_?increment\b/i.test(def.type)) { def.autoIncrement = true; strip(/\bauto_?increment\b/gi); }
51
+ if (/\bnot\s+null\b/i.test(def.type)) { def.required = true; strip(/\bnot\s+null\b/gi); }
52
+ if (/\bunique\b/i.test(def.type)) { def.unique = true; strip(/\bunique\b/gi); }
53
+ if (/\bdefault\s+(\S+)/i.test(def.type)) {
54
+ const m = def.type.match(/\bdefault\s+(\S+)/i);
55
+ def.default = m[1].replace(/^['"]|['"]$/g, '');
56
+ strip(/\bdefault\s+\S+/gi);
57
+ }
58
+ return def;
59
+ }
60
+
61
+ function parseSchemaString(str) {
62
+ const out = {};
63
+ for (const seg of str.split(',')) {
64
+ const trimmed = seg.trim();
65
+ if (!trimmed) continue;
66
+ const parts = trimmed.split(/\s+/);
67
+ const name = parts.shift();
68
+ const def = parseShorthandSchema(parts.join(' ').toLowerCase().trim());
69
+ if (def.type.length === 0) def.type = 'string';
70
+ out[name] = def;
71
+ }
72
+ return out;
73
+ }
74
+
75
+ function mapNativeSchema(schema) {
76
+ if (typeof schema === 'string') schema = parseSchemaString(schema);
77
+ const mapped = {};
78
+ for (const [field, def] of Object.entries(schema || {})) {
79
+ if (typeof def === 'string') {
80
+ const parsed = parseShorthandSchema(def.toLowerCase().trim());
81
+ if (parsed.type.length === 0) parsed.type = 'string';
82
+ mapped[field] = { ...parsed, type: NATIVE_TYPE_MAP[parsed.type] || parsed.type };
83
+ } else if (def && typeof def === 'object') {
84
+ const t = (def.type || 'string').toLowerCase();
85
+ const out = { ...def, type: NATIVE_TYPE_MAP[t] || t };
86
+ if (out.primary_key !== undefined && out.primaryKey === undefined) { out.primaryKey = out.primary_key; delete out.primary_key; }
87
+ if (out.auto_increment !== undefined && out.autoIncrement === undefined) { out.autoIncrement = out.auto_increment; delete out.auto_increment; }
88
+ mapped[field] = out;
89
+ } else {
90
+ mapped[field] = { type: 'string' };
91
+ }
92
+ }
93
+ return mapped;
94
+ }
95
+
96
+ function restoreRow(row, schema) {
97
+ if (typeof row !== 'object' || row === null) return row;
98
+ let src = row;
99
+ if (row.fields && typeof row.fields === 'object' && row.fields !== null) {
100
+ src = { ...row.fields };
101
+ if (row.id !== undefined) {
102
+ const pkCols = [];
103
+ if (schema) {
104
+ for (const [k, def] of Object.entries(schema)) {
105
+ if (def && typeof def === 'object' && def.autoIncrement) continue;
106
+ const isPk = typeof def === 'string'
107
+ ? /\bprimary\s+key\b/i.test(def)
108
+ : !!(def && (def.primaryKey || def.primary_key));
109
+ if (isPk) pkCols.push(k);
110
+ }
111
+ } else if (src.id === undefined) {
112
+ pkCols.push('id');
113
+ }
114
+ for (const c of pkCols) {
115
+ const v = src[c];
116
+ if (v === undefined || v === null || v === 0 || v === '' || v === false) src[c] = row.id;
117
+ }
118
+ }
119
+ if (row.created_at !== undefined) src.created_at = row.created_at;
120
+ if (row.updated_at !== undefined) src.updated_at = row.updated_at;
121
+ }
122
+ if (!schema) return src;
123
+ const out = {};
124
+ for (const [field, value] of Object.entries(src)) {
125
+ const colDef = schema[field];
126
+ let t = null;
127
+ if (typeof colDef === 'string') t = colDef.toLowerCase();
128
+ else if (colDef && typeof colDef === 'object' && colDef.type) t = String(colDef.type).toLowerCase();
129
+ if (['json', 'array', 'object'].includes(t) && typeof value === 'string') {
130
+ try { out[field] = JSON.parse(value); } catch (e) { out[field] = value; }
131
+ } else if ((t === 'integer' || t === 'int' || t === 'bigint') && typeof value === 'string' && /^-?\d+$/.test(value)) {
132
+ out[field] = Number(value);
133
+ } else if ((t === 'float' || t === 'double' || t === 'number') && typeof value === 'string' && !Number.isNaN(Number(value))) {
134
+ out[field] = Number(value);
135
+ } else {
136
+ out[field] = value;
137
+ }
138
+ }
139
+ return out;
140
+ }
141
+
142
+ const INT64_TAG = 1;
143
+ const FLOAT_TAG = 2;
144
+ const STR_TAG = 3;
145
+ const BOOL_TAG = 4;
146
+ const INT32_TAG = 5;
147
+
148
+
149
+ export class JSQL {
150
+ constructor(opts = {}) {
151
+ this._flushThreshold = opts.flushThreshold || 5000;
152
+ this._buffer = {};
153
+ this._bufferSize = 0;
154
+ this._tableNames = new Set();
155
+ this._schemas = {};
156
+ this._txId = undefined;
157
+ this._autoPlugins = opts.modules !== false;
158
+
159
+ this._plugins = [];
160
+ this._hooks = {
161
+ beforeInsert: [], afterInsert: [],
162
+ beforeUpdate: [], afterUpdate: [],
163
+ beforeDelete: [], afterDelete: [],
164
+ beforeFind: [], afterFind: [],
165
+ beforeCreateTable: [], afterCreateTable: [],
166
+ beforeDropTable: [], afterDropTable: [],
167
+ beforeFlush: [], afterFlush: [],
168
+ beforeCount: [], afterCount: [],
169
+ onStart: [], onStop: []
170
+ };
171
+ this._eventListeners = [];
172
+ if (this._autoPlugins && typeof globalThis.__jsqlLoadModules === 'function') {
173
+ globalThis.__jsqlLoadModules(this);
174
+ }
175
+ }
176
+
177
+ use(plugin, opts) {
178
+ if (typeof plugin === 'string') {
179
+ throw new Error('use: builtin plugin names require the Node plugin runtime; pass a plugin object');
180
+ }
181
+ if (typeof plugin === 'function') {
182
+ plugin = { install: plugin };
183
+ }
184
+ if (opts && plugin && typeof plugin === 'object') {
185
+ plugin.config = Object.assign({}, plugin.config || {}, opts);
186
+ }
187
+ if (plugin.hooks) {
188
+ for (const [event, fn] of Object.entries(plugin.hooks)) {
189
+ if (this._hooks[event]) {
190
+ this._hooks[event].push(fn);
191
+ }
192
+ }
193
+ }
194
+ if (typeof plugin.install === 'function') {
195
+ plugin.install(this, this._buildCtx(plugin));
196
+ }
197
+ if (typeof plugin.onEvent === 'function') {
198
+ this._eventListeners.push(plugin.onEvent);
199
+ }
200
+ this._plugins.push(plugin);
201
+ return this;
202
+ }
203
+
204
+ _buildCtx(plugin) {
205
+ const self = this;
206
+ return {
207
+ name: plugin.name || 'anonymous',
208
+ engine: this,
209
+ plugin,
210
+ on(hook, fn) { return self.on(hook, fn); },
211
+ onEvent(fn) { return self.onEvent(fn); },
212
+ emit(eventName, data) { self._emit(eventName, data); },
213
+ tables() { return Array.from(self._tableNames); },
214
+ hasTable(name) { return self._tableNames.has(name); },
215
+ getTableSchema(name) { return self._schemas[name] || null; }
216
+ };
217
+ }
218
+
219
+ on(event, fn) {
220
+ if (this._hooks[event]) {
221
+ this._hooks[event].push(fn);
222
+ }
223
+ return this;
224
+ }
225
+
226
+ onEvent(fn) {
227
+ this._eventListeners.push(fn);
228
+ return this;
229
+ }
230
+
231
+ _emit(eventName, data) {
232
+ for (const fn of this._eventListeners) {
233
+ try { fn(eventName, data); } catch (e) { /* ignore */ }
234
+ }
235
+ }
236
+
237
+ _runHooks(hookName, args) {
238
+ const hooks = this._hooks[hookName];
239
+ if (!hooks || hooks.length === 0) return true;
240
+ for (const fn of hooks) {
241
+ const r = fn(...args);
242
+ if (r === false) return false;
243
+ if (r !== undefined && args.length > 0) {
244
+ args[0] = r;
245
+ }
246
+ }
247
+ return true;
248
+ }
249
+
250
+ async start() {
251
+ await init();
252
+ jsql_reset();
253
+ this._runHooks('onStart', []);
254
+ this._emit('start', {});
255
+ }
256
+
257
+ _pkOf(table) {
258
+ const schema = this._schemas[table];
259
+ if (!schema) return null;
260
+ for (const [k, def] of Object.entries(schema)) {
261
+ const isPk = (typeof def === 'string' && /\bprimary\s+key\b/i.test(def))
262
+ || !!(def && typeof def === 'object' && (def.primaryKey || def.primary_key));
263
+ if (isPk) return k;
264
+ }
265
+ return null;
266
+ }
267
+
268
+ _pkAutoIncrement(table) {
269
+ const schema = this._schemas[table];
270
+ const pk = this._pkOf(table);
271
+ if (!pk || !schema) return false;
272
+ const def = schema[pk];
273
+ if (typeof def === 'string') return /\bauto_?increment\b/i.test(def);
274
+ return !!(def && def.autoIncrement);
275
+ }
276
+
277
+ _coercePkId(table, id) {
278
+ const schema = this._schemas[table];
279
+ const pk = this._pkOf(table);
280
+ if (!schema || !pk) return id;
281
+ const def = schema[pk];
282
+ let t = null;
283
+ if (typeof def === 'string') t = def.toLowerCase();
284
+ else if (def && typeof def === 'object' && def.type) t = String(def.type).toLowerCase();
285
+ if (['integer', 'int', 'bigint'].includes(t)) return Number(id);
286
+ return id;
287
+ }
288
+
289
+ _findRawById(table, id) {
290
+ const pk = this._pkOf(table);
291
+ if (pk) {
292
+ const filter = {};
293
+ filter[pk] = this._coercePkId(table, id);
294
+ const r = safeJsonParse(jsql_find(table, JSON.stringify(filter), 1, 0));
295
+ if (r && r.error) return r;
296
+ return Array.isArray(r) && r.length > 0 ? r[0] : null;
297
+ }
298
+ return safeJsonParse(jsql_find_by_id(table, BigInt(id)));
299
+ }
300
+
301
+ _seqIdByPk(table, id) {
302
+ const pk = this._pkOf(table);
303
+ if (pk) {
304
+ const filter = {};
305
+ filter[pk] = this._coercePkId(table, id);
306
+ const r = safeJsonParse(jsql_find(table, JSON.stringify(filter), 1, 0));
307
+ if (Array.isArray(r) && r.length > 0) return r[0].id;
308
+ return null;
309
+ }
310
+ return Number(id);
311
+ }
312
+
313
+ async _insertBatch(table, rows) {
314
+ const schema = this._schemas[table];
315
+ if (schema) {
316
+ rows = rows.map(row => {
317
+ const out = {};
318
+ for (const [k, v] of Object.entries(row)) {
319
+ const def = schema[k];
320
+ let t = null;
321
+ if (typeof def === 'string') t = def.toLowerCase();
322
+ else if (def && typeof def === 'object' && def.type) t = String(def.type).toLowerCase();
323
+ if (v !== null && v !== undefined && ['json', 'array', 'object'].includes(t) && typeof v !== 'string') {
324
+ out[k] = JSON.stringify(v);
325
+ } else if (v instanceof Date) {
326
+ out[k] = v.toISOString();
327
+ } else {
328
+ out[k] = v;
329
+ }
330
+ }
331
+ return out;
332
+ });
333
+ }
334
+ const r = safeJsonParse(jsql_insert_json(table, JSON.stringify(rows)));
335
+ if (r && r.error) throw new Error(r.error);
336
+ if (r && Array.isArray(r) && !this._pkAutoIncrement(table)) {
337
+ const pk = this._pkOf(table);
338
+ if (pk) {
339
+ return r.map((seq, i) => {
340
+ const row = rows[i];
341
+ return (row && row[pk] !== undefined && row[pk] !== null) ? row[pk] : seq;
342
+ });
343
+ }
344
+ }
345
+ return r;
346
+ }
347
+
348
+ async _flush() {
349
+ if (!this._runHooks('beforeFlush', [])) return null;
350
+ const flushed = {};
351
+ for (const [table, rows] of Object.entries(this._buffer)) {
352
+ if (rows.length === 0) continue;
353
+ const r = await this._insertBatch(table, rows);
354
+ flushed[table] = r;
355
+ }
356
+ this._buffer = {};
357
+ this._bufferSize = 0;
358
+ this._runHooks('afterFlush', []);
359
+ return flushed;
360
+ }
361
+
362
+ async flush() {
363
+ await this._flush();
364
+ }
365
+
366
+ async insert(table, data) {
367
+ const arr = Array.isArray(data) ? data : [data];
368
+ if (!this._runHooks('beforeInsert', [table, arr])) return [];
369
+ if (arr.length > 1) {
370
+ await this._flush();
371
+ let result;
372
+ for (let i = 0; i < arr.length; i += this._flushThreshold) {
373
+ const chunk = arr.slice(i, i + this._flushThreshold);
374
+ const r = await this._insertBatch(table, chunk);
375
+ if (r && r.error) throw new Error(r.error);
376
+ if (!result) result = r;
377
+ }
378
+ this._emit('insert', { table, count: arr.length, ids: result });
379
+ this._runHooks('afterInsert', [table, arr, result]);
380
+ return result;
381
+ }
382
+ if (!this._buffer[table]) this._buffer[table] = [];
383
+ this._buffer[table].push(arr[0]);
384
+ this._bufferSize++;
385
+ const flushed = await this._flush();
386
+ const result = flushed && flushed[table] ? flushed[table] : null;
387
+ this._emit('insert', { table, count: arr.length, ids: result });
388
+ this._runHooks('afterInsert', [table, arr, result]);
389
+ return result;
390
+ }
391
+
392
+ async insertMany(table, data) {
393
+ return this.insert(table, data);
394
+ }
395
+
396
+ async createTable(name, schema) {
397
+ await this._flush();
398
+ if (typeof schema === 'string') schema = parseSchemaString(schema);
399
+ if (!this._runHooks('beforeCreateTable', [name, schema])) return null;
400
+ const r = safeJsonParse(jsql_create_table(name, JSON.stringify(mapNativeSchema(schema))));
401
+ if (r && r.ok === false) throw new Error(r.error || 'create table failed');
402
+ this._tableNames.add(name);
403
+ this._schemas[name] = typeof schema === 'string' ? mapNativeSchema(schema) : schema;
404
+ this._emit('createTable', { name, schema });
405
+ this._runHooks('afterCreateTable', [name, schema]);
406
+ return r;
407
+ }
408
+
409
+ async addColumn(table, name, def) {
410
+ await this._flush();
411
+ const mapped = mapNativeSchema({ [name]: def })[name];
412
+ const r = safeJsonParse(jsql_add_column(table, name, JSON.stringify(mapped)));
413
+ if (r && r.ok === false) throw new Error(r.error || 'add column failed');
414
+ if (!this._schemas[table]) this._schemas[table] = {};
415
+ this._schemas[table][name] = mapped;
416
+ this._emit('addColumn', { table, name, def: mapped });
417
+ return r;
418
+ }
419
+
420
+ async dropTable(name) {
421
+ await this._flush();
422
+ if (!this._runHooks('beforeDropTable', [name])) return null;
423
+ const r = safeJsonParse(jsql_drop_table(name));
424
+ if (r && r.ok === false) throw new Error(r.error || 'drop table failed');
425
+ this._tableNames.delete(name);
426
+ delete this._schemas[name];
427
+ this._emit('dropTable', { name });
428
+ this._runHooks('afterDropTable', [name]);
429
+ return r;
430
+ }
431
+
432
+ async findById(table, id) {
433
+ await this._flush();
434
+ if (!this._runHooks('beforeFind', [table, { id }])) return null;
435
+ const r = this._findRawById(table, id);
436
+ if (r && r.error) throw new Error(r.error);
437
+ this._runHooks('afterFind', [table, { id }, r]);
438
+ const schema = this._schemas[table];
439
+ if (schema && r && typeof r === 'object') return restoreRow(r, schema);
440
+ return r;
441
+ }
442
+
443
+ async find(table, filter, opts = {}) {
444
+ await this._flush();
445
+ if (!this._runHooks('beforeFind', [table, { filter, opts }])) return [];
446
+ const filterStr = filter ? JSON.stringify(filter) : '';
447
+ const { limit = 100, offset = 0 } = opts;
448
+ const r = safeJsonParse(jsql_find(table, filterStr, limit, offset));
449
+ if (r && r.error) throw new Error(r.error);
450
+ this._runHooks('afterFind', [table, { filter, opts }, r]);
451
+ const schema = this._schemas[table];
452
+ if (schema && Array.isArray(r)) return r.map(row => restoreRow(row, schema));
453
+ return r;
454
+ }
455
+
456
+ async count(table) {
457
+ await this._flush();
458
+ this._runHooks('beforeCount', [table]);
459
+ const r = parseInt(jsql_count(table), 10);
460
+ const n = isNaN(r) ? 0 : r;
461
+ this._runHooks('afterCount', [table, n]);
462
+ return n;
463
+ }
464
+
465
+ async updateByIds(table, entries) {
466
+ const pairs = [];
467
+ for (const [id, data] of entries) {
468
+ const seq = this._seqIdByPk(table, id);
469
+ if (seq !== null) pairs.push([seq, data]);
470
+ }
471
+ if (!this._runHooks('beforeUpdate', [table, pairs])) return;
472
+ await this._flush();
473
+ const r = safeJsonParse(jsql_update_by_ids(table, JSON.stringify(pairs)));
474
+ if (r && r.error) throw new Error(r.error);
475
+ this._emit('update', { table, entries: pairs, result: r });
476
+ this._runHooks('afterUpdate', [table, pairs, r]);
477
+ return r;
478
+ }
479
+
480
+ async removeByIds(table, ids) {
481
+ if (!this._runHooks('beforeDelete', [table, ids])) return;
482
+ await this._flush();
483
+ const seqs = ids.map(id => this._seqIdByPk(table, id)).filter(s => s !== null);
484
+ const r = safeJsonParse(jsql_remove_by_ids(table, JSON.stringify(seqs)));
485
+ if (r && r.error) throw new Error(r.error);
486
+ this._emit('delete', { table, ids: seqs, result: r });
487
+ this._runHooks('afterDelete', [table, ids, r]);
488
+ return r;
489
+ }
490
+
491
+ async findByIds(table, ids) {
492
+ await this._flush();
493
+ if (!this._runHooks('beforeFind', [table, { ids }])) return null;
494
+ let r;
495
+ if (this._pkOf(table)) {
496
+ r = ids.map(id => this._findRawById(table, id)).filter(x => x !== null && !(x && x.error));
497
+ } else {
498
+ r = safeJsonParse(jsql_find_by_ids(table, JSON.stringify(ids)));
499
+ }
500
+ if (r && r.error) throw new Error(r.error);
501
+ this._runHooks('afterFind', [table, { ids }, r]);
502
+ const schema = this._schemas[table];
503
+ if (schema && Array.isArray(r)) return r.map(row => restoreRow(row, schema));
504
+ return r;
505
+ }
506
+
507
+ findByIdsRaw(table, ids) {
508
+ return this.findByIds(table, ids);
509
+ }
510
+
511
+ async updateById(table, id, data) {
512
+ if (!this._runHooks('beforeUpdate', [table, id, data])) return;
513
+ await this._flush();
514
+ const seq = this._seqIdByPk(table, id);
515
+ if (seq === null) return null;
516
+ const r = safeJsonParse(jsql_update_by_id(table, BigInt(seq), JSON.stringify(data)));
517
+ if (r && r.ok === false) throw new Error(r.error || 'update failed');
518
+ this._emit('update', { table, id, data });
519
+ this._runHooks('afterUpdate', [table, id, data, r]);
520
+ return r;
521
+ }
522
+
523
+ async removeById(table, id) {
524
+ if (!this._runHooks('beforeDelete', [table, id])) return;
525
+ await this._flush();
526
+ const seq = this._seqIdByPk(table, id);
527
+ if (seq === null) return null;
528
+ const r = safeJsonParse(jsql_remove_by_id(table, BigInt(seq)));
529
+ if (r && r.ok === false) throw new Error(r.error || 'remove failed');
530
+ this._emit('delete', { table, id });
531
+ this._runHooks('afterDelete', [table, id, r]);
532
+ return r;
533
+ }
534
+
535
+ async beginTx() {
536
+ await this._flush();
537
+ const r = safeJsonParse(jsql_begin_tx());
538
+ if (r && r.ok === false) throw new Error(r.error || 'begin transaction failed');
539
+ this._txId = r.txId;
540
+ return r.txId;
541
+ }
542
+
543
+ async commitTx(txId) {
544
+ const r = safeJsonParse(jsql_commit_tx(String(txId)));
545
+ if (r && r.ok === false) throw new Error(r.error || 'commit transaction failed');
546
+ return true;
547
+ }
548
+
549
+ async rollbackTx(txId) {
550
+ const r = safeJsonParse(jsql_rollback_tx(String(txId)));
551
+ if (r && r.ok === false) throw new Error(r.error || 'rollback transaction failed');
552
+ return true;
553
+ }
554
+
555
+ async beginTransaction() {
556
+ return this.beginTx();
557
+ }
558
+
559
+ async commit() {
560
+ if (this._txId === undefined) return true;
561
+ const r = await this.commitTx(this._txId);
562
+ this._txId = undefined;
563
+ return r;
564
+ }
565
+
566
+ async rollback() {
567
+ if (this._txId === undefined) return true;
568
+ const r = await this.rollbackTx(this._txId);
569
+ this._txId = undefined;
570
+ return r;
571
+ }
572
+
573
+ async hasTable(name) {
574
+ return this._tableNames.has(name);
575
+ }
576
+
577
+ async getTables() {
578
+ return Array.from(this._tableNames);
579
+ }
580
+
581
+ async getTableSchema(name) {
582
+ return this._schemas[name] || null;
583
+ }
584
+
585
+ async stop() {
586
+ await this._flush();
587
+ this._runHooks('onStop', []);
588
+ this._emit('stop', {});
589
+ }
590
+ }
591
+