flatsql 0.4.3 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/README.md +116 -6
  2. package/dist/artifacts/builder.d.ts +31 -0
  3. package/dist/artifacts/builder.d.ts.map +1 -0
  4. package/dist/artifacts/builder.js +514 -0
  5. package/dist/artifacts/builder.js.map +1 -0
  6. package/dist/artifacts/demo-extractors.d.ts +15 -0
  7. package/dist/artifacts/demo-extractors.d.ts.map +1 -0
  8. package/dist/artifacts/demo-extractors.js +238 -0
  9. package/dist/artifacts/demo-extractors.js.map +1 -0
  10. package/dist/artifacts/index.d.ts +5 -0
  11. package/dist/artifacts/index.d.ts.map +1 -0
  12. package/dist/artifacts/index.js +5 -0
  13. package/dist/artifacts/index.js.map +1 -0
  14. package/dist/artifacts/standalone-builder.d.ts +62 -0
  15. package/dist/artifacts/standalone-builder.d.ts.map +1 -0
  16. package/dist/artifacts/standalone-builder.js +144 -0
  17. package/dist/artifacts/standalone-builder.js.map +1 -0
  18. package/dist/artifacts/transport.d.ts +5 -0
  19. package/dist/artifacts/transport.d.ts.map +1 -0
  20. package/dist/artifacts/transport.js +45 -0
  21. package/dist/artifacts/transport.js.map +1 -0
  22. package/dist/artifacts/types.d.ts +34 -0
  23. package/dist/artifacts/types.d.ts.map +1 -0
  24. package/dist/artifacts/types.js +2 -0
  25. package/dist/artifacts/types.js.map +1 -0
  26. package/dist/artifacts/worker-client.d.ts +32 -0
  27. package/dist/artifacts/worker-client.d.ts.map +1 -0
  28. package/dist/artifacts/worker-client.js +415 -0
  29. package/dist/artifacts/worker-client.js.map +1 -0
  30. package/dist/btree/btree.d.ts.map +1 -1
  31. package/dist/btree/btree.js +13 -14
  32. package/dist/btree/btree.js.map +1 -1
  33. package/dist/core/database.d.ts +2 -0
  34. package/dist/core/database.d.ts.map +1 -1
  35. package/dist/core/database.js +18 -0
  36. package/dist/core/database.js.map +1 -1
  37. package/dist/core/table-store.d.ts +1 -0
  38. package/dist/core/table-store.d.ts.map +1 -1
  39. package/dist/core/table-store.js +31 -0
  40. package/dist/core/table-store.js.map +1 -1
  41. package/dist/index.d.ts +3 -0
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.js +3 -0
  44. package/dist/index.js.map +1 -1
  45. package/dist/response/artifact.d.ts +5 -0
  46. package/dist/response/artifact.d.ts.map +1 -0
  47. package/dist/response/artifact.js +102 -0
  48. package/dist/response/artifact.js.map +1 -0
  49. package/dist/response/cache-key.d.ts +6 -0
  50. package/dist/response/cache-key.d.ts.map +1 -0
  51. package/dist/response/cache-key.js +114 -0
  52. package/dist/response/cache-key.js.map +1 -0
  53. package/dist/response/index.d.ts +5 -0
  54. package/dist/response/index.d.ts.map +1 -0
  55. package/dist/response/index.js +5 -0
  56. package/dist/response/index.js.map +1 -0
  57. package/dist/response/memory-cache.d.ts +17 -0
  58. package/dist/response/memory-cache.d.ts.map +1 -0
  59. package/dist/response/memory-cache.js +76 -0
  60. package/dist/response/memory-cache.js.map +1 -0
  61. package/dist/response/types.d.ts +51 -0
  62. package/dist/response/types.d.ts.map +1 -0
  63. package/dist/response/types.js +2 -0
  64. package/dist/response/types.js.map +1 -0
  65. package/dist/standalone/index.d.ts +3 -0
  66. package/dist/standalone/index.d.ts.map +1 -0
  67. package/dist/standalone/index.js +3 -0
  68. package/dist/standalone/index.js.map +1 -0
  69. package/dist/standalone/process-client.d.ts +85 -0
  70. package/dist/standalone/process-client.d.ts.map +1 -0
  71. package/dist/standalone/process-client.js +537 -0
  72. package/dist/standalone/process-client.js.map +1 -0
  73. package/dist/standalone/wasmedge-runner.d.ts +19 -0
  74. package/dist/standalone/wasmedge-runner.d.ts.map +1 -0
  75. package/dist/standalone/wasmedge-runner.js +108 -0
  76. package/dist/standalone/wasmedge-runner.js.map +1 -0
  77. package/dist/stress/aggregate.d.ts +3 -0
  78. package/dist/stress/aggregate.d.ts.map +1 -0
  79. package/dist/stress/aggregate.js +61 -0
  80. package/dist/stress/aggregate.js.map +1 -0
  81. package/dist/stress/docker-compose.d.ts +17 -0
  82. package/dist/stress/docker-compose.d.ts.map +1 -0
  83. package/dist/stress/docker-compose.js +156 -0
  84. package/dist/stress/docker-compose.js.map +1 -0
  85. package/dist/stress/index.d.ts +11 -0
  86. package/dist/stress/index.d.ts.map +1 -0
  87. package/dist/stress/index.js +11 -0
  88. package/dist/stress/index.js.map +1 -0
  89. package/dist/stress/metrics.d.ts +3 -0
  90. package/dist/stress/metrics.d.ts.map +1 -0
  91. package/dist/stress/metrics.js +83 -0
  92. package/dist/stress/metrics.js.map +1 -0
  93. package/dist/stress/native-publish-event-workload.d.ts +3 -0
  94. package/dist/stress/native-publish-event-workload.d.ts.map +1 -0
  95. package/dist/stress/native-publish-event-workload.js +455 -0
  96. package/dist/stress/native-publish-event-workload.js.map +1 -0
  97. package/dist/stress/production-gate.d.ts +4 -0
  98. package/dist/stress/production-gate.d.ts.map +1 -0
  99. package/dist/stress/production-gate.js +12 -0
  100. package/dist/stress/production-gate.js.map +1 -0
  101. package/dist/stress/publish-event-workload.d.ts +3 -0
  102. package/dist/stress/publish-event-workload.d.ts.map +1 -0
  103. package/dist/stress/publish-event-workload.js +467 -0
  104. package/dist/stress/publish-event-workload.js.map +1 -0
  105. package/dist/stress/report.d.ts +3 -0
  106. package/dist/stress/report.d.ts.map +1 -0
  107. package/dist/stress/report.js +174 -0
  108. package/dist/stress/report.js.map +1 -0
  109. package/dist/stress/sds-discovery.d.ts +4 -0
  110. package/dist/stress/sds-discovery.d.ts.map +1 -0
  111. package/dist/stress/sds-discovery.js +40 -0
  112. package/dist/stress/sds-discovery.js.map +1 -0
  113. package/dist/stress/smoke-runner.d.ts +3 -0
  114. package/dist/stress/smoke-runner.d.ts.map +1 -0
  115. package/dist/stress/smoke-runner.js +63 -0
  116. package/dist/stress/smoke-runner.js.map +1 -0
  117. package/dist/stress/types.d.ts +219 -0
  118. package/dist/stress/types.d.ts.map +1 -0
  119. package/dist/stress/types.js +2 -0
  120. package/dist/stress/types.js.map +1 -0
  121. package/dist/stress/workload.d.ts +6 -0
  122. package/dist/stress/workload.d.ts.map +1 -0
  123. package/dist/stress/workload.js +144 -0
  124. package/dist/stress/workload.js.map +1 -0
  125. package/docs/agents/response-artifacts.md +65 -0
  126. package/docs/response-artifacts.md +86 -0
  127. package/package.json +36 -6
  128. package/scripts/stress-docker.sh +279 -0
  129. package/sdm/flatsql-spatial.wasm +0 -0
  130. package/stress/docker/Dockerfile +11 -0
  131. package/stress/docker/docker-compose.yml +51 -0
  132. package/stress/sds/aggregate.mjs +97 -0
  133. package/stress/sds/run.mjs +105 -0
  134. package/stress/sds/write-compose.mjs +96 -0
  135. package/wasm/flatsql-artifact.worker.js +847 -0
  136. package/wasm/flatsql-wasi.wasm +0 -0
  137. package/wasm/flatsql.js +2 -16
  138. package/wasm/flatsql.wasm +0 -0
  139. package/wasm/index.d.ts +119 -2
  140. package/wasm/index.js +450 -60
  141. package/wasm/native/flatsql_wasmedge_runner.cpp +858 -0
  142. package/wasm/standalone.d.ts +91 -0
  143. package/wasm/standalone.js +740 -0
@@ -0,0 +1,740 @@
1
+ const DEFAULT_STANDALONE_URL = new URL('./flatsql-wasi.wasm', import.meta.url);
2
+
3
+ const PARAM_NULL = 0;
4
+ const PARAM_BOOL = 1;
5
+ const PARAM_INT64 = 2;
6
+ const PARAM_FLOAT64 = 3;
7
+ const PARAM_STRING = 4;
8
+ const PARAM_BYTES = 5;
9
+
10
+ const textEncoder = new TextEncoder();
11
+ const textDecoder = new TextDecoder();
12
+
13
+ export function getFlatSQLStandaloneWasmURL() {
14
+ return DEFAULT_STANDALONE_URL;
15
+ }
16
+
17
+ async function readViaFsPath(path) {
18
+ const fs = await import('node:fs/promises');
19
+ return new Uint8Array(await fs.readFile(path));
20
+ }
21
+
22
+ async function loadWasmBytes(options = {}) {
23
+ if (options.bytes instanceof Uint8Array) {
24
+ return options.bytes;
25
+ }
26
+ if (options.bytes instanceof ArrayBuffer) {
27
+ return new Uint8Array(options.bytes);
28
+ }
29
+ if (ArrayBuffer.isView(options.bytes)) {
30
+ return new Uint8Array(options.bytes.buffer, options.bytes.byteOffset, options.bytes.byteLength);
31
+ }
32
+ if (options.path) {
33
+ return readViaFsPath(options.path);
34
+ }
35
+
36
+ const wasmUrl = options.url ? new URL(options.url, import.meta.url) : DEFAULT_STANDALONE_URL;
37
+ if (wasmUrl.protocol === 'file:') {
38
+ const { fileURLToPath } = await import('node:url');
39
+ return readViaFsPath(fileURLToPath(wasmUrl));
40
+ }
41
+
42
+ const response = await fetch(wasmUrl);
43
+ if (!response.ok) {
44
+ throw new Error(`Failed to load flatsql-wasi.wasm: ${response.status}`);
45
+ }
46
+ return new Uint8Array(await response.arrayBuffer());
47
+ }
48
+
49
+ function makeWasiImports(state, options = {}) {
50
+ const stdout = options.stdout ?? (() => {});
51
+ const stderr = options.stderr ?? (() => {});
52
+ const stdin = options.stdin instanceof Uint8Array ? options.stdin : new Uint8Array();
53
+ let stdinOffset = 0;
54
+
55
+ function view() {
56
+ return new DataView(state.memory.buffer);
57
+ }
58
+
59
+ function heap() {
60
+ return new Uint8Array(state.memory.buffer);
61
+ }
62
+
63
+ function writeUint64(ptr, value) {
64
+ view().setBigUint64(ptr, BigInt(value), true);
65
+ }
66
+
67
+ function readIov(iovPtr, iovIndex) {
68
+ const base = iovPtr + iovIndex * 8;
69
+ return {
70
+ ptr: view().getUint32(base, true),
71
+ length: view().getUint32(base + 4, true),
72
+ };
73
+ }
74
+
75
+ function writeFd(fd, iovPtr, iovCount, bytesWrittenPtr) {
76
+ let written = 0;
77
+ const chunks = [];
78
+ const memory = heap();
79
+ for (let index = 0; index < iovCount; index++) {
80
+ const iov = readIov(iovPtr, index);
81
+ chunks.push(memory.slice(iov.ptr, iov.ptr + iov.length));
82
+ written += iov.length;
83
+ }
84
+ view().setUint32(bytesWrittenPtr, written, true);
85
+
86
+ if (chunks.length > 0) {
87
+ const total = new Uint8Array(written);
88
+ let offset = 0;
89
+ for (const chunk of chunks) {
90
+ total.set(chunk, offset);
91
+ offset += chunk.length;
92
+ }
93
+ const text = textDecoder.decode(total);
94
+ if (fd === 2) {
95
+ stderr(text);
96
+ } else {
97
+ stdout(text);
98
+ }
99
+ }
100
+ return 0;
101
+ }
102
+
103
+ function readFd(fd, iovPtr, iovCount, bytesReadPtr) {
104
+ if (fd !== 0 || stdinOffset >= stdin.length) {
105
+ view().setUint32(bytesReadPtr, 0, true);
106
+ return 0;
107
+ }
108
+
109
+ let read = 0;
110
+ const memory = heap();
111
+ for (let index = 0; index < iovCount && stdinOffset < stdin.length; index++) {
112
+ const iov = readIov(iovPtr, index);
113
+ const length = Math.min(iov.length, stdin.length - stdinOffset);
114
+ memory.set(stdin.subarray(stdinOffset, stdinOffset + length), iov.ptr);
115
+ stdinOffset += length;
116
+ read += length;
117
+ }
118
+ view().setUint32(bytesReadPtr, read, true);
119
+ return 0;
120
+ }
121
+
122
+ function randomGet(ptr, length) {
123
+ const target = heap().subarray(ptr, ptr + length);
124
+ const cryptoApi = globalThis.crypto;
125
+ if (cryptoApi?.getRandomValues) {
126
+ cryptoApi.getRandomValues(target);
127
+ return 0;
128
+ }
129
+ for (let index = 0; index < target.length; index++) {
130
+ target[index] = Math.floor(Math.random() * 256);
131
+ }
132
+ return 0;
133
+ }
134
+
135
+ return {
136
+ wasi_snapshot_preview1: {
137
+ clock_time_get(clockId, _precision, timePtr) {
138
+ const millis = clockId === 0 ? Date.now() : performance.now();
139
+ writeUint64(timePtr, Math.round(millis * 1_000_000));
140
+ return 0;
141
+ },
142
+ fd_write: writeFd,
143
+ fd_read: readFd,
144
+ environ_sizes_get(environCountPtr, environBufferSizePtr) {
145
+ view().setUint32(environCountPtr, 0, true);
146
+ view().setUint32(environBufferSizePtr, 0, true);
147
+ return 0;
148
+ },
149
+ environ_get() {
150
+ return 0;
151
+ },
152
+ random_get: randomGet,
153
+ },
154
+ };
155
+ }
156
+
157
+ function encodeQueryParams(params) {
158
+ const parts = [];
159
+ let total = 0;
160
+
161
+ for (const value of params) {
162
+ let tag;
163
+ let payload;
164
+
165
+ if (value === null) {
166
+ tag = PARAM_NULL;
167
+ payload = new Uint8Array(0);
168
+ } else if (typeof value === 'boolean') {
169
+ tag = PARAM_BOOL;
170
+ payload = Uint8Array.of(value ? 1 : 0);
171
+ } else if (typeof value === 'number' && Number.isInteger(value)) {
172
+ if (!Number.isSafeInteger(value)) {
173
+ throw new TypeError('Integer query parameters must be safe integers');
174
+ }
175
+ tag = PARAM_INT64;
176
+ payload = new Uint8Array(8);
177
+ new DataView(payload.buffer).setBigInt64(0, BigInt(value), true);
178
+ } else if (typeof value === 'number') {
179
+ tag = PARAM_FLOAT64;
180
+ payload = new Uint8Array(8);
181
+ new DataView(payload.buffer).setFloat64(0, value, true);
182
+ } else if (typeof value === 'string') {
183
+ tag = PARAM_STRING;
184
+ payload = textEncoder.encode(value);
185
+ } else if (value instanceof Uint8Array) {
186
+ tag = PARAM_BYTES;
187
+ payload = value;
188
+ } else {
189
+ throw new TypeError(`Unsupported query parameter type: ${typeof value}`);
190
+ }
191
+
192
+ const header = new Uint8Array(5);
193
+ const headerView = new DataView(header.buffer);
194
+ headerView.setUint8(0, tag);
195
+ headerView.setUint32(1, payload.length, true);
196
+ parts.push(header, payload);
197
+ total += header.length + payload.length;
198
+ }
199
+
200
+ const encoded = new Uint8Array(total);
201
+ let offset = 0;
202
+ for (const part of parts) {
203
+ encoded.set(part, offset);
204
+ offset += part.length;
205
+ }
206
+ return encoded;
207
+ }
208
+
209
+ function encodeQueryRequests(queries) {
210
+ const parts = [];
211
+ let total = 0;
212
+
213
+ for (const query of queries) {
214
+ const sqlBytes = textEncoder.encode(query.sql);
215
+ const params = query.params ?? [];
216
+ const paramBytes = encodeQueryParams(params);
217
+ const header = new Uint8Array(12);
218
+ const headerView = new DataView(header.buffer);
219
+ headerView.setUint32(0, sqlBytes.length, true);
220
+ headerView.setUint32(4, params.length, true);
221
+ headerView.setUint32(8, paramBytes.length, true);
222
+ parts.push(header, sqlBytes, paramBytes);
223
+ total += header.length + sqlBytes.length + paramBytes.length;
224
+ }
225
+
226
+ const encoded = new Uint8Array(total);
227
+ let offset = 0;
228
+ for (const part of parts) {
229
+ encoded.set(part, offset);
230
+ offset += part.length;
231
+ }
232
+ return encoded;
233
+ }
234
+
235
+ function buildSizePrefixedStream(buffers) {
236
+ let total = 0;
237
+ for (const buffer of buffers) {
238
+ total += 4 + buffer.length;
239
+ }
240
+
241
+ const stream = new Uint8Array(total);
242
+ let offset = 0;
243
+ for (const buffer of buffers) {
244
+ new DataView(stream.buffer, offset, 4).setUint32(0, buffer.length, true);
245
+ offset += 4;
246
+ stream.set(buffer, offset);
247
+ offset += buffer.length;
248
+ }
249
+ return stream;
250
+ }
251
+
252
+ function createRuntime(exports) {
253
+ const memory = exports.memory;
254
+ if (!(memory instanceof WebAssembly.Memory)) {
255
+ throw new Error('Standalone FlatSQL artifact does not export WebAssembly.Memory as memory.');
256
+ }
257
+
258
+ function heap() {
259
+ return new Uint8Array(memory.buffer);
260
+ }
261
+
262
+ function malloc(size) {
263
+ const ptr = exports.malloc(size);
264
+ if (!ptr) {
265
+ throw new Error(`FlatSQL standalone allocation failed for ${size} bytes`);
266
+ }
267
+ return ptr;
268
+ }
269
+
270
+ function free(ptr) {
271
+ if (ptr) {
272
+ exports.free(ptr);
273
+ }
274
+ }
275
+
276
+ function readCString(ptr) {
277
+ if (!ptr) {
278
+ return '';
279
+ }
280
+ const memoryBytes = heap();
281
+ if (ptr < 0 || ptr >= memoryBytes.length) {
282
+ throw new Error(`FlatSQL standalone string pointer is outside memory: ${ptr}`);
283
+ }
284
+ let end = ptr;
285
+ while (end < memoryBytes.length && memoryBytes[end] !== 0) {
286
+ end++;
287
+ }
288
+ if (end === memoryBytes.length) {
289
+ throw new Error(`FlatSQL standalone string is not null-terminated at pointer ${ptr}`);
290
+ }
291
+ return textDecoder.decode(memoryBytes.subarray(ptr, end));
292
+ }
293
+
294
+ function withCString(value, callback) {
295
+ const bytes = textEncoder.encode(String(value));
296
+ const ptr = malloc(bytes.length + 1);
297
+ try {
298
+ heap().set(bytes, ptr);
299
+ heap()[ptr + bytes.length] = 0;
300
+ return callback(ptr);
301
+ } finally {
302
+ free(ptr);
303
+ }
304
+ }
305
+
306
+ function withBytes(bytes, callback) {
307
+ if (bytes.length === 0) {
308
+ return callback(0);
309
+ }
310
+ const ptr = malloc(bytes.length);
311
+ try {
312
+ heap().set(bytes, ptr);
313
+ return callback(ptr);
314
+ } finally {
315
+ free(ptr);
316
+ }
317
+ }
318
+
319
+ function check(success) {
320
+ if (!success) {
321
+ throw new Error(readCString(exports.flatsql_get_error()));
322
+ }
323
+ }
324
+
325
+ function readCellValue(row, column) {
326
+ const type = exports.flatsql_result_cell_type(row, column);
327
+ switch (type) {
328
+ case 0:
329
+ return null;
330
+ case 1:
331
+ return exports.flatsql_result_cell_number(row, column) !== 0;
332
+ case 2:
333
+ case 3:
334
+ case 4:
335
+ return exports.flatsql_result_cell_number(row, column);
336
+ case 5:
337
+ return readCString(exports.flatsql_result_cell_string(row, column));
338
+ case 6: {
339
+ const ptr = exports.flatsql_result_cell_blob(row, column);
340
+ const size = exports.flatsql_result_cell_blob_size(row, column);
341
+ return ptr && size > 0 ? Array.from(heap().slice(ptr, ptr + size)) : [];
342
+ }
343
+ default:
344
+ return null;
345
+ }
346
+ }
347
+
348
+ function readQueryResult() {
349
+ const columnCount = exports.flatsql_result_column_count();
350
+ const rowCount = exports.flatsql_result_row_count();
351
+ const columns = [];
352
+ const rows = [];
353
+
354
+ for (let column = 0; column < columnCount; column++) {
355
+ columns.push(readCString(exports.flatsql_result_column_name(column)));
356
+ }
357
+ for (let row = 0; row < rowCount; row++) {
358
+ const values = [];
359
+ for (let column = 0; column < columnCount; column++) {
360
+ values.push(readCellValue(row, column));
361
+ }
362
+ rows.push(values);
363
+ }
364
+ return { columns, rows };
365
+ }
366
+
367
+ return {
368
+ exports,
369
+ memory,
370
+ readCString,
371
+ withCString,
372
+ withBytes,
373
+ check,
374
+ readQueryResult,
375
+ readBytes(ptr, size) {
376
+ return heap().slice(ptr, ptr + size);
377
+ },
378
+ };
379
+ }
380
+
381
+ export async function loadFlatSQLStandalone(options = {}) {
382
+ const wasmBytes = await loadWasmBytes(options);
383
+ const state = { memory: null };
384
+ const imports = makeWasiImports(state, options.wasi ?? options);
385
+ const mergedImports = options.imports
386
+ ? {
387
+ ...imports,
388
+ ...options.imports,
389
+ wasi_snapshot_preview1: {
390
+ ...imports.wasi_snapshot_preview1,
391
+ ...(options.imports.wasi_snapshot_preview1 ?? {}),
392
+ },
393
+ }
394
+ : imports;
395
+ const { instance, module } = await WebAssembly.instantiate(wasmBytes, mergedImports);
396
+ state.memory = instance.exports.memory;
397
+
398
+ if (typeof instance.exports._initialize === 'function') {
399
+ instance.exports._initialize();
400
+ }
401
+
402
+ return new FlatSQLStandalone(createRuntime(instance.exports), module);
403
+ }
404
+
405
+ export const createStandaloneFlatSQL = loadFlatSQLStandalone;
406
+
407
+ export class FlatSQLStandalone {
408
+ constructor(runtime, module) {
409
+ this._runtime = runtime;
410
+ this.module = module;
411
+ this.memory = runtime.memory;
412
+ }
413
+
414
+ createDatabase(schema, dbName = 'default') {
415
+ const handle = this._runtime.withCString(schema, (schemaPtr) =>
416
+ this._runtime.withCString(dbName, (namePtr) =>
417
+ this._runtime.exports.flatsql_create_db(schemaPtr, namePtr)
418
+ )
419
+ );
420
+ if (!handle) {
421
+ throw new Error('Failed to create FlatSQL standalone database.');
422
+ }
423
+ return new FlatSQLStandaloneDatabase(this._runtime, handle);
424
+ }
425
+
426
+ createTestUser(id, name, email, age) {
427
+ const ptr = this._runtime.withCString(name, (namePtr) =>
428
+ this._runtime.withCString(email, (emailPtr) =>
429
+ this._runtime.exports.flatsql_create_test_user(id, namePtr, emailPtr, age)
430
+ )
431
+ );
432
+ const size = this._runtime.exports.flatsql_test_buffer_size();
433
+ return this._runtime.readBytes(ptr, size);
434
+ }
435
+
436
+ createTestPost(id, userId, title) {
437
+ const ptr = this._runtime.withCString(title, (titlePtr) =>
438
+ this._runtime.exports.flatsql_create_test_post(id, userId, titlePtr)
439
+ );
440
+ const size = this._runtime.exports.flatsql_test_buffer_size();
441
+ return this._runtime.readBytes(ptr, size);
442
+ }
443
+
444
+ createTestPublishEvent(fileId, recordId, eventIndex, payloadSize) {
445
+ const ptr = this._runtime.withCString(fileId, (fileIdPtr) =>
446
+ this._runtime.withCString(recordId, (recordIdPtr) =>
447
+ this._runtime.exports.flatsql_create_test_publish_event(
448
+ fileIdPtr,
449
+ recordIdPtr,
450
+ eventIndex,
451
+ payloadSize
452
+ )
453
+ )
454
+ );
455
+ const size = this._runtime.exports.flatsql_test_buffer_size();
456
+ return this._runtime.readBytes(ptr, size);
457
+ }
458
+
459
+ buildQueryCacheKey(dataset, artifactVersion, queryId, params = []) {
460
+ const paramBytes = encodeQueryParams(params);
461
+ const keyPtr = this._runtime.withCString(dataset, (datasetPtr) =>
462
+ this._runtime.withCString(artifactVersion, (versionPtr) =>
463
+ this._runtime.withCString(queryId, (queryIdPtr) =>
464
+ this._runtime.withBytes(paramBytes, (paramPtr) =>
465
+ this._runtime.exports.flatsql_build_query_cache_key(
466
+ datasetPtr,
467
+ versionPtr,
468
+ queryIdPtr,
469
+ paramPtr,
470
+ paramBytes.length,
471
+ params.length
472
+ )
473
+ )
474
+ )
475
+ )
476
+ );
477
+ const key = this._runtime.readCString(keyPtr);
478
+ if (!key) {
479
+ throw new Error(this._runtime.readCString(this._runtime.exports.flatsql_get_error()));
480
+ }
481
+ return key;
482
+ }
483
+
484
+ buildResponseArtifactCacheKey(schemaName, schemaVersion, sql, options = {}) {
485
+ const format = options.format ?? 'json';
486
+ const publishEventKey = options.publishEventKey ?? '';
487
+ const projectionList = (options.projection ?? []).join('\n');
488
+ const params = options.params ?? [];
489
+ const paramBytes = encodeQueryParams(params);
490
+ const keyPtr = this._runtime.withCString(schemaName, (schemaPtr) =>
491
+ this._runtime.withCString(schemaVersion, (versionPtr) =>
492
+ this._runtime.withCString(sql, (sqlPtr) =>
493
+ this._runtime.withCString(format, (formatPtr) =>
494
+ this._runtime.withCString(publishEventKey, (eventPtr) =>
495
+ this._runtime.withCString(projectionList, (projectionPtr) =>
496
+ this._runtime.withBytes(paramBytes, (paramPtr) =>
497
+ this._runtime.exports.flatsql_build_response_artifact_cache_key(
498
+ schemaPtr,
499
+ versionPtr,
500
+ sqlPtr,
501
+ formatPtr,
502
+ eventPtr,
503
+ projectionPtr,
504
+ paramPtr,
505
+ paramBytes.length,
506
+ params.length
507
+ )
508
+ )
509
+ )
510
+ )
511
+ )
512
+ )
513
+ )
514
+ );
515
+ const key = this._runtime.readCString(keyPtr);
516
+ if (!key) {
517
+ throw new Error(this._runtime.readCString(this._runtime.exports.flatsql_get_error()));
518
+ }
519
+ return key;
520
+ }
521
+ }
522
+
523
+ export class FlatSQLStandaloneDatabase {
524
+ constructor(runtime, handle) {
525
+ this._runtime = runtime;
526
+ this._handle = handle;
527
+ }
528
+
529
+ destroy() {
530
+ if (this._handle) {
531
+ this._runtime.exports.flatsql_destroy_db(this._handle);
532
+ this._handle = 0;
533
+ }
534
+ }
535
+
536
+ registerFileId(fileId, tableName) {
537
+ this._runtime.withCString(fileId, (filePtr) =>
538
+ this._runtime.withCString(tableName, (tablePtr) =>
539
+ this._runtime.exports.flatsql_register_file_id(this._handle, filePtr, tablePtr)
540
+ )
541
+ );
542
+ }
543
+
544
+ enableDemoExtractors() {
545
+ this._runtime.exports.flatsql_enable_demo_extractors(this._handle);
546
+ }
547
+
548
+ ingest(data, source = null) {
549
+ return this._runtime.withBytes(data, (ptr) => {
550
+ if (source) {
551
+ return this._runtime.withCString(source, (sourcePtr) =>
552
+ this._runtime.exports.flatsql_ingest_with_source(this._handle, ptr, data.length, sourcePtr)
553
+ );
554
+ }
555
+ return this._runtime.exports.flatsql_ingest(this._handle, ptr, data.length);
556
+ });
557
+ }
558
+
559
+ ingestBuffers(buffers, source = null) {
560
+ return this.ingest(buildSizePrefixedStream(buffers), source);
561
+ }
562
+
563
+ ingestOne(data, source = null) {
564
+ return this._runtime.withBytes(data, (ptr) => {
565
+ if (source) {
566
+ return this._runtime.withCString(source, (sourcePtr) =>
567
+ this._runtime.exports.flatsql_ingest_one_with_source(this._handle, ptr, data.length, sourcePtr)
568
+ );
569
+ }
570
+ return this._runtime.exports.flatsql_ingest_one(this._handle, ptr, data.length);
571
+ });
572
+ }
573
+
574
+ query(sql, params = undefined) {
575
+ const success = this._runtime.withCString(sql, (sqlPtr) => {
576
+ if (params === undefined) {
577
+ return this._runtime.exports.flatsql_query(this._handle, sqlPtr);
578
+ }
579
+ const paramBytes = encodeQueryParams(params);
580
+ return this._runtime.withBytes(paramBytes, (paramPtr) =>
581
+ this._runtime.exports.flatsql_query_params(
582
+ this._handle,
583
+ sqlPtr,
584
+ paramPtr,
585
+ paramBytes.length,
586
+ params.length
587
+ )
588
+ );
589
+ });
590
+ this._runtime.check(success);
591
+ return this._runtime.readQueryResult();
592
+ }
593
+
594
+ queryMany(queries) {
595
+ if (queries.length === 0) {
596
+ return [];
597
+ }
598
+ const requestBytes = encodeQueryRequests(queries);
599
+ const success = this._runtime.withBytes(requestBytes, (ptr) =>
600
+ this._runtime.exports.flatsql_query_many(this._handle, ptr, requestBytes.length, queries.length)
601
+ );
602
+ this._runtime.check(success);
603
+
604
+ const count = this._runtime.exports.flatsql_batch_result_count();
605
+ const results = [];
606
+ for (let index = 0; index < count; index++) {
607
+ this._runtime.check(this._runtime.exports.flatsql_select_batch_result(index));
608
+ results.push(this._runtime.readQueryResult());
609
+ }
610
+ return results;
611
+ }
612
+
613
+ queryRawFlatBufferStream(sql, params = []) {
614
+ const paramBytes = encodeQueryParams(params);
615
+ const success = this._runtime.withCString(sql, (sqlPtr) =>
616
+ this._runtime.withBytes(paramBytes, (paramPtr) =>
617
+ this._runtime.exports.flatsql_query_raw_flatbuffer_stream(
618
+ this._handle,
619
+ sqlPtr,
620
+ paramPtr,
621
+ paramBytes.length,
622
+ params.length
623
+ )
624
+ )
625
+ );
626
+ this._runtime.check(success);
627
+
628
+ const ptr = this._runtime.exports.flatsql_response_artifact_data();
629
+ const size = this._runtime.exports.flatsql_response_artifact_size();
630
+ return ptr && size > 0 ? this._runtime.readBytes(ptr, size) : new Uint8Array();
631
+ }
632
+
633
+ registerQueryTemplate(queryId, sql, cacheable = true) {
634
+ const success = this._runtime.withCString(queryId, (queryIdPtr) =>
635
+ this._runtime.withCString(sql, (sqlPtr) =>
636
+ this._runtime.exports.flatsql_register_query_template(
637
+ this._handle,
638
+ queryIdPtr,
639
+ sqlPtr,
640
+ cacheable ? 1 : 0
641
+ )
642
+ )
643
+ );
644
+ this._runtime.check(success);
645
+ }
646
+
647
+ queryTemplate(queryId, params = []) {
648
+ const paramBytes = encodeQueryParams(params);
649
+ const success = this._runtime.withCString(queryId, (queryIdPtr) =>
650
+ this._runtime.withBytes(paramBytes, (paramPtr) =>
651
+ this._runtime.exports.flatsql_query_template(
652
+ this._handle,
653
+ queryIdPtr,
654
+ paramPtr,
655
+ paramBytes.length,
656
+ params.length
657
+ )
658
+ )
659
+ );
660
+ this._runtime.check(success);
661
+ return this._runtime.readQueryResult();
662
+ }
663
+
664
+ clearQueryCache() {
665
+ this._runtime.exports.flatsql_clear_query_cache(this._handle);
666
+ }
667
+
668
+ configureQueryCache({ maxEntries, maxRows }) {
669
+ if (!Number.isSafeInteger(maxEntries) || maxEntries <= 0) {
670
+ throw new TypeError(`maxEntries must be a positive safe integer, received: ${maxEntries}`);
671
+ }
672
+ if (!Number.isSafeInteger(maxRows) || maxRows <= 0) {
673
+ throw new TypeError(`maxRows must be a positive safe integer, received: ${maxRows}`);
674
+ }
675
+ this._runtime.check(
676
+ this._runtime.exports.flatsql_configure_query_cache(this._handle, maxEntries, maxRows)
677
+ );
678
+ }
679
+
680
+ getQueryCacheStats() {
681
+ return {
682
+ hits: this._runtime.exports.flatsql_query_cache_hits(this._handle),
683
+ misses: this._runtime.exports.flatsql_query_cache_misses(this._handle),
684
+ size: this._runtime.exports.flatsql_query_cache_size(this._handle),
685
+ generation: this._runtime.exports.flatsql_query_cache_generation(this._handle),
686
+ maxEntries: this._runtime.exports.flatsql_query_cache_max_entries(this._handle),
687
+ maxRows: this._runtime.exports.flatsql_query_cache_max_rows(this._handle),
688
+ };
689
+ }
690
+
691
+ exportData() {
692
+ const ptr = this._runtime.exports.flatsql_export_data(this._handle);
693
+ const size = this._runtime.exports.flatsql_export_size();
694
+ return this._runtime.readBytes(ptr, size);
695
+ }
696
+
697
+ loadAndRebuild(data) {
698
+ this._runtime.withBytes(data, (ptr) =>
699
+ this._runtime.exports.flatsql_load_and_rebuild(this._handle, ptr, data.length)
700
+ );
701
+ }
702
+
703
+ reserveStorageBytes(bytes) {
704
+ this._runtime.exports.flatsql_reserve_storage(this._handle, bytes);
705
+ }
706
+
707
+ loadAndRebuildFrom(sourceDb) {
708
+ if (!sourceDb?._handle) {
709
+ throw new TypeError('loadAndRebuildFrom requires a FlatSQL standalone database.');
710
+ }
711
+ this._runtime.exports.flatsql_load_from_db(this._handle, sourceDb._handle);
712
+ }
713
+
714
+ getFlatBufferByIndex(tableName, indexName, keyParams = []) {
715
+ const paramBytes = encodeQueryParams(keyParams);
716
+ const ptr = this._runtime.withCString(tableName, (tablePtr) =>
717
+ this._runtime.withCString(indexName, (indexPtr) =>
718
+ this._runtime.withBytes(paramBytes, (paramPtr) =>
719
+ this._runtime.exports.flatsql_get_flatbuffer_by_index(
720
+ this._handle,
721
+ tablePtr,
722
+ indexPtr,
723
+ paramPtr,
724
+ paramBytes.length,
725
+ keyParams.length
726
+ )
727
+ )
728
+ )
729
+ );
730
+ const size = this._runtime.exports.flatsql_get_raw_flatbuffer_size();
731
+ return ptr && size > 0 ? this._runtime.readBytes(ptr, size) : null;
732
+ }
733
+
734
+ getStorageInfo() {
735
+ return {
736
+ ptr: this._runtime.exports.flatsql_get_storage_buffer(this._handle),
737
+ size: this._runtime.exports.flatsql_get_storage_size(this._handle),
738
+ };
739
+ }
740
+ }