@cqlite/node 0.3.1-rc5 → 0.9.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.
package/README.md CHANGED
@@ -225,6 +225,68 @@ CQL types are automatically converted to JavaScript types:
225
225
  \* **Note:** With `execute()`, `varint` returns `"0x{hex}"` and `decimal` returns `"decimal:{scale}:0x{hex}"`.
226
226
  Use `executeNative()` for human-readable formats.
227
227
 
228
+ ## Write Operations
229
+
230
+ CQLite v0.9.0 adds write support to the Node.js bindings. Open the database with
231
+ `writable: true` and a `writeDir` to enable write operations.
232
+
233
+ ```javascript
234
+ const { Database } = require('@cqlite/node');
235
+
236
+ const db = await Database.open('path/to/sstables', {
237
+ schema: 'schema.cql',
238
+ writable: true,
239
+ writeDir: '/tmp/my-writes',
240
+ });
241
+
242
+ // Write rows via CQL INSERT, UPDATE, or DELETE
243
+ await db.execute(
244
+ "INSERT INTO test_basic.simple_table (id, name, age) " +
245
+ "VALUES (22222222-2222-2222-2222-222222222222, 'Bob', 25)"
246
+ );
247
+ await db.execute(
248
+ "UPDATE test_basic.simple_table SET age = 26 " +
249
+ "WHERE id = 22222222-2222-2222-2222-222222222222"
250
+ );
251
+
252
+ // Flush the in-memory write buffer (memtable) to an SSTable on disk.
253
+ // Returns the path to the flushed Data.db file, or "" if memtable was empty.
254
+ const path = await db.flushRun();
255
+ console.log('Flushed to:', path);
256
+
257
+ // Run background compaction within a time budget
258
+ const report = await db.maintenanceStep({ budgetMs: 100 });
259
+ console.log(`Merged ${report.rowsMerged} rows in ${report.timeSpentMs}ms`);
260
+ if (report.pendingCompaction) {
261
+ console.log('More compaction work available');
262
+ }
263
+
264
+ // Inspect write statistics (synchronous getter)
265
+ const stats = db.writeStats;
266
+ console.log('Memtable size:', stats.memtableSizeBytes, 'bytes');
267
+ console.log('Total flushed:', stats.totalWrittenBytes, 'bytes');
268
+
269
+ await db.close();
270
+ ```
271
+
272
+ ### Write API
273
+
274
+ | Method / Property | Description |
275
+ |-------------------|-------------|
276
+ | `db.execute(cql)` | Execute a CQL INSERT, UPDATE, or DELETE statement |
277
+ | `db.flushRun()` | Flush memtable to SSTable; returns the Data.db path or `""` if memtable was empty |
278
+ | `db.maintenanceStep(options?)` | Run STCS compaction for up to `options.budgetMs` ms (default: 100); returns `MaintenanceReport` |
279
+ | `db.writeStats` | Synchronous getter: `memtableSizeBytes`, `memtableRowCount`, `totalWrittenBytes`, `l0SstableCount` |
280
+
281
+ ### Known Limitations
282
+
283
+ - Counter columns cannot be written — `execute()` throws `CqliteError` for
284
+ counter mutations.
285
+ - BTI-format index files are not produced; the writer emits BIG format.
286
+
287
+ See [docs/write-support-limitations.md](../../docs/write-support-limitations.md)
288
+ for the full limitations reference.
289
+
228
290
  ## Examples
229
291
 
230
292
  See the [examples/](examples/) directory for complete working examples:
@@ -239,6 +301,7 @@ See the [examples/](examples/) directory for complete working examples:
239
301
 
240
302
  - [TypeScript Definitions](lib/index.d.ts) - Complete API type hints
241
303
  - [Main Project README](../../README.md) - CQLite project overview
304
+ - [Write Support Guide](../../docs/write-support.md) - Detailed write documentation
242
305
  - [Issue Tracker](https://github.com/pmcfadin/cqlite/issues) - Report bugs or request features
243
306
 
244
307
  ## License
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -189,7 +189,12 @@ function createWrappedDatabase(NativeDatabase, wrapPreparedStatement) {
189
189
  async execute(query) {
190
190
  try {
191
191
  const result = await this._native.execute(query);
192
- result.rowsAffected = result.rowCount; // M4 spec alias (Issue #348)
192
+ // For SELECT: rowsAffected = rowCount (alias, Issue #348).
193
+ // For DML (INSERT/UPDATE/DELETE): rowsAffected is already set by Rust layer to 1;
194
+ // do NOT overwrite it with rowCount (which would be 0 for writes).
195
+ if (result.rowsAffected === undefined || result.rowsAffected === null) {
196
+ result.rowsAffected = result.rowCount;
197
+ }
193
198
  return result;
194
199
  } catch (error) {
195
200
  throw enhanceError(error);
@@ -199,7 +204,10 @@ function createWrappedDatabase(NativeDatabase, wrapPreparedStatement) {
199
204
  async executeNative(query) {
200
205
  try {
201
206
  const result = await this._native.executeNative(query);
202
- result.rowsAffected = result.rowCount; // M4 spec alias (Issue #348)
207
+ // Same pattern as execute(): preserve rowsAffected from Rust layer.
208
+ if (result.rowsAffected === undefined || result.rowsAffected === null) {
209
+ result.rowsAffected = result.rowCount;
210
+ }
203
211
  return result;
204
212
  } catch (error) {
205
213
  throw enhanceError(error);
@@ -362,6 +370,55 @@ function createWrappedDatabase(NativeDatabase, wrapPreparedStatement) {
362
370
  throw enhanceError(error);
363
371
  }
364
372
  }
373
+
374
+ /**
375
+ * Flush the in-memory write buffer (memtable) to an SSTable on disk.
376
+ *
377
+ * Returns the path to the created Data.db file.
378
+ * Returns an empty string if the memtable was empty (no-op flush).
379
+ *
380
+ * Requires the database to have been opened with `{ writable: true }`.
381
+ *
382
+ * @returns {Promise<string>} Absolute path to the Data.db file, or "" if nothing flushed
383
+ * @throws {CqliteError} If write support is not enabled or the flush fails
384
+ */
385
+ async flushRun() {
386
+ try {
387
+ return await this._native.flushRun();
388
+ } catch (error) {
389
+ throw enhanceError(error);
390
+ }
391
+ }
392
+
393
+ /**
394
+ * Perform time-bounded background maintenance (compaction).
395
+ *
396
+ * @param {Object} [options] - Maintenance options
397
+ * @param {number} [options.budgetMs=100] - Time budget in milliseconds
398
+ * @returns {Promise<Object>} MaintenanceReport with timeSpentMs, rowsMerged, etc.
399
+ * @throws {CqliteError} If write support is not enabled or maintenance fails
400
+ */
401
+ async maintenanceStep(options) {
402
+ try {
403
+ return await this._native.maintenanceStep(options);
404
+ } catch (error) {
405
+ throw enhanceError(error);
406
+ }
407
+ }
408
+
409
+ /**
410
+ * Get current write engine statistics (synchronous getter).
411
+ *
412
+ * @returns {Object} WriteStats with memtableSize, memtableRows, walSize, l0Count, totalWritten
413
+ * @throws {CqliteError} If write support is not enabled
414
+ */
415
+ get writeStats() {
416
+ try {
417
+ return this._native.writeStats;
418
+ } catch (error) {
419
+ throw enhanceError(error);
420
+ }
421
+ }
365
422
  }
366
423
 
367
424
  return Database;
package/lib/index.d.ts CHANGED
@@ -220,10 +220,8 @@ export interface QueryResult {
220
220
  rowCount: number;
221
221
 
222
222
  /**
223
- * Number of rows returned (M4 spec alias for rowCount).
224
- *
225
- * Note: CQLite is read-only. For SELECT queries, this represents
226
- * the number of rows read, not modified.
223
+ * Number of rows affected by the write (INSERT/UPDATE/DELETE).
224
+ * 0 for SELECT queries.
227
225
  */
228
226
  rowsAffected: number;
229
227
 
@@ -262,10 +260,8 @@ export interface NativeQueryResult {
262
260
  rowCount: number;
263
261
 
264
262
  /**
265
- * Number of rows returned (M4 spec alias for rowCount).
266
- *
267
- * Note: CQLite is read-only. For SELECT queries, this represents
268
- * the number of rows read, not modified.
263
+ * Number of rows affected by the write (INSERT/UPDATE/DELETE).
264
+ * 0 for SELECT queries.
269
265
  */
270
266
  rowsAffected: number;
271
267
 
@@ -316,18 +312,27 @@ export interface DatabaseStats {
316
312
  *
317
313
  * @example
318
314
  * ```typescript
315
+ * // Read-only
319
316
  * const options: DatabaseOptions = {
320
317
  * schema: '/path/to/schema.cql',
321
318
  * memoryLimit: 256 * 1024 * 1024, // 256MB
322
319
  * cacheEnabled: true
323
320
  * };
324
321
  * const db = await Database.open('/path/to/data', options);
322
+ *
323
+ * // Read-write
324
+ * const db = await Database.open('/path/to/data', {
325
+ * schema: '/path/to/schema.cql',
326
+ * writable: true,
327
+ * writeDir: '/tmp/cqlite-writes',
328
+ * });
325
329
  * ```
326
330
  */
327
331
  export interface DatabaseOptions {
328
332
  /**
329
333
  * Path to a CQL schema file (.cql).
330
334
  * If provided, the schema will be loaded and used for query execution.
335
+ * Required when `writable` is true.
331
336
  */
332
337
  schema?: string;
333
338
 
@@ -350,6 +355,114 @@ export interface DatabaseOptions {
350
355
  * Set to false to minimize memory usage at the cost of performance.
351
356
  */
352
357
  cacheEnabled?: boolean;
358
+
359
+ /**
360
+ * Enable write support (INSERT, UPDATE, DELETE).
361
+ * When true, `writeDir` must also be provided and a `schema` is required.
362
+ * Default: false (read-only mode).
363
+ */
364
+ writable?: boolean;
365
+
366
+ /**
367
+ * Directory for write-engine data (memtable flush targets and WAL files).
368
+ * Required when `writable` is true.
369
+ * Sub-directories `data/` and `wal/` are created automatically.
370
+ *
371
+ * @example
372
+ * ```typescript
373
+ * { writable: true, writeDir: '/tmp/cqlite-writes' }
374
+ * ```
375
+ */
376
+ writeDir?: string;
377
+ }
378
+
379
+ // ============================================================================
380
+ // Write Support
381
+ // ============================================================================
382
+
383
+ /**
384
+ * Write engine statistics.
385
+ *
386
+ * Returned synchronously by `Database.writeStats`.
387
+ * Reflects the current state of the in-memory write buffer and WAL.
388
+ *
389
+ * @example
390
+ * ```typescript
391
+ * const stats = db.writeStats;
392
+ * console.log(`Memtable: ${stats.memtableSize} bytes, ${stats.memtableRows} rows`);
393
+ * console.log(`L0 files: ${stats.l0Count}`);
394
+ * ```
395
+ */
396
+ export interface WriteStats {
397
+ /** Current memtable size in bytes. */
398
+ memtableSize: number;
399
+
400
+ /** Current number of rows in the memtable. */
401
+ memtableRows: number;
402
+
403
+ /** Current write-ahead log (WAL) size in bytes. */
404
+ walSize: number;
405
+
406
+ /**
407
+ * Number of L0 SSTable files flushed during this session.
408
+ * Increases by 1 for each `flushRun()` call that produced data.
409
+ */
410
+ l0Count: number;
411
+
412
+ /** Total bytes written to SSTables across all flushes in this session. */
413
+ totalWritten: number;
414
+ }
415
+
416
+ /**
417
+ * Options for `Database.maintenanceStep()`.
418
+ *
419
+ * Controls time-bounded background compaction.
420
+ *
421
+ * @example
422
+ * ```typescript
423
+ * const report = await db.maintenanceStep({ budgetMs: 200 });
424
+ * ```
425
+ */
426
+ export interface MaintenanceOptions {
427
+ /**
428
+ * Maximum time to spend in this maintenance step, in milliseconds.
429
+ * Default: 100.
430
+ */
431
+ budgetMs?: number;
432
+ }
433
+
434
+ /**
435
+ * Report returned by `Database.maintenanceStep()`.
436
+ *
437
+ * Describes progress made during one time-bounded compaction step.
438
+ *
439
+ * @example
440
+ * ```typescript
441
+ * const report = await db.maintenanceStep({ budgetMs: 100 });
442
+ * console.log(`Merged ${report.rowsMerged} rows in ${report.timeSpentMs}ms`);
443
+ * if (report.pendingCompaction) {
444
+ * console.log('More compaction work pending');
445
+ * }
446
+ * ```
447
+ */
448
+ export interface MaintenanceReport {
449
+ /** Time actually spent in the maintenance step, in milliseconds. */
450
+ timeSpentMs: number;
451
+
452
+ /** Number of rows merged during this step. */
453
+ rowsMerged: number;
454
+
455
+ /** Number of bytes written during this step. */
456
+ bytesWritten: number;
457
+
458
+ /**
459
+ * Paths of SSTables produced by merges completed in this step.
460
+ * Empty array when no merge was completed (step was partial progress).
461
+ */
462
+ completedMerges: string[];
463
+
464
+ /** Whether there is more compaction work pending after this step. */
465
+ pendingCompaction: boolean;
353
466
  }
354
467
 
355
468
  /**
@@ -854,6 +967,75 @@ export declare class Database {
854
967
  * @throws {CqliteError} If the query cannot be prepared
855
968
  */
856
969
  prepare(query: string): Promise<PreparedStatement>;
970
+
971
+ /**
972
+ * Flush the in-memory write buffer (memtable) to an SSTable on disk.
973
+ *
974
+ * Returns the path to the created Data.db file.
975
+ * If the memtable is empty, an empty string is returned (no-op flush).
976
+ *
977
+ * Requires the database to have been opened with `{ writable: true }`.
978
+ *
979
+ * @returns Promise resolving to the Data.db path, or "" if nothing was flushed
980
+ * @throws {CqliteError} If write support is not enabled or the flush fails
981
+ *
982
+ * @example
983
+ * ```typescript
984
+ * const db = await Database.open('/data', {
985
+ * schema: 'schema.cql',
986
+ * writable: true,
987
+ * writeDir: '/tmp/writes',
988
+ * });
989
+ * await db.execute("INSERT INTO t (id, name) VALUES (uuid(), 'Alice')");
990
+ * const sstablePath = await db.flushRun();
991
+ * console.log(`Flushed to: ${sstablePath}`);
992
+ * ```
993
+ */
994
+ flushRun(): Promise<string>;
995
+
996
+ /**
997
+ * Perform time-bounded background maintenance (compaction).
998
+ *
999
+ * Runs incremental compaction work within the provided time budget.
1000
+ * Can be called repeatedly to drain pending compaction work.
1001
+ *
1002
+ * Requires the database to have been opened with `{ writable: true }`.
1003
+ *
1004
+ * @param options - Optional maintenance options (default budgetMs: 100)
1005
+ * @returns Promise resolving to a MaintenanceReport
1006
+ * @throws {CqliteError} If write support is not enabled or maintenance fails
1007
+ *
1008
+ * @example
1009
+ * ```typescript
1010
+ * let report: MaintenanceReport;
1011
+ * do {
1012
+ * report = await db.maintenanceStep({ budgetMs: 100 });
1013
+ * console.log(`Merged ${report.rowsMerged} rows`);
1014
+ * } while (report.pendingCompaction);
1015
+ * ```
1016
+ */
1017
+ maintenanceStep(options?: MaintenanceOptions): Promise<MaintenanceReport>;
1018
+
1019
+ /**
1020
+ * Get current write engine statistics (synchronous getter).
1021
+ *
1022
+ * Returns a snapshot of the in-memory write buffer (memtable) and WAL state.
1023
+ *
1024
+ * Requires the database to have been opened with `{ writable: true }`.
1025
+ *
1026
+ * @returns WriteStats snapshot
1027
+ * @throws {CqliteError} If write support is not enabled
1028
+ *
1029
+ * @example
1030
+ * ```typescript
1031
+ * const stats = db.writeStats;
1032
+ * console.log(`Memtable: ${stats.memtableSize} bytes, ${stats.memtableRows} rows`);
1033
+ * console.log(`WAL: ${stats.walSize} bytes`);
1034
+ * console.log(`L0 files: ${stats.l0Count}`);
1035
+ * console.log(`Total written: ${stats.totalWritten} bytes`);
1036
+ * ```
1037
+ */
1038
+ get writeStats(): WriteStats;
857
1039
  }
858
1040
 
859
1041
  // ============================================================================
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cqlite/node",
3
- "version": "0.3.1-rc5",
3
+ "version": "0.9.1",
4
4
  "description": "Node.js bindings for CQLite - read Apache Cassandra 5.0 SSTables without cluster dependencies",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",
@@ -27,8 +27,10 @@
27
27
  "access": "public"
28
28
  },
29
29
  "scripts": {
30
- "build": "napi build --platform --release",
31
- "build:debug": "napi build --platform",
30
+ "build": "napi build --platform --release --features write-support",
31
+ "postbuild": "node scripts/generate-loader.mjs",
32
+ "build:debug": "napi build --platform --features write-support",
33
+ "pretest": "node scripts/generate-loader.mjs",
32
34
  "test": "jest",
33
35
  "test:watch": "jest --watch",
34
36
  "test:coverage": "jest --coverage",
package/index.d.ts DELETED
@@ -1,413 +0,0 @@
1
- /* tslint:disable */
2
- /* eslint-disable */
3
-
4
- /* auto-generated by NAPI-RS */
5
-
6
- /**
7
- * Column metadata information.
8
- *
9
- * Provides information about a column in the query result set,
10
- * including name, data type, and nullability.
11
- */
12
- export interface ColumnInfo {
13
- /** Column name. */
14
- name: string
15
- /** CQL data type as a string (e.g., "Text", "Integer", "List"). */
16
- dataType: string
17
- /** Whether the column can contain null values. */
18
- nullable: boolean
19
- /** Column position in the result set (0-indexed). */
20
- position: number
21
- /** Original table name (for joined queries). */
22
- tableName?: string
23
- }
24
- /**
25
- * Query execution result.
26
- *
27
- * Contains the query results serialized as JSON values for JavaScript
28
- * consumption, along with metadata about the execution.
29
- */
30
- export interface QueryResult {
31
- /**
32
- * Result rows as JSON objects.
33
- * Each row is a JSON object with column names as keys.
34
- */
35
- rows: Array<any>
36
- /** Number of rows returned. */
37
- rowCount: number
38
- /** Query execution time in milliseconds. */
39
- executionTimeMs: number
40
- /**
41
- * Column metadata for the result set.
42
- * Contains information about each column's name, type, and nullability.
43
- */
44
- columns: Array<ColumnInfo>
45
- }
46
- /**
47
- * Database statistics.
48
- *
49
- * Provides information about the database state including
50
- * storage and memory metrics.
51
- */
52
- export interface DatabaseStats {
53
- /** Total number of SSTable files. */
54
- totalSstables: number
55
- /** Total number of rows across all SSTables. */
56
- totalRows: bigint
57
- /** Memory currently used by the database in bytes. */
58
- memoryUsedBytes: bigint
59
- }
60
- /**
61
- * Database open options.
62
- *
63
- * Configuration options for opening a database.
64
- */
65
- export interface DatabaseOptions {
66
- /**
67
- * Path to a CQL schema file (.cql).
68
- * If provided, the schema will be loaded and used for query execution.
69
- */
70
- schema?: string
71
- /**
72
- * Maximum memory usage in bytes.
73
- * Default: 1GB (1073741824 bytes).
74
- * Controls the overall memory budget for caches and internal buffers.
75
- * JavaScript numbers can safely represent up to 2^53 bytes (~9 petabytes).
76
- */
77
- memoryLimit?: number
78
- /**
79
- * Enable or disable all caches (block, row, query).
80
- * Default: true (caches enabled).
81
- * Set to false to minimize memory usage at the cost of performance.
82
- */
83
- cacheEnabled?: boolean
84
- }
85
- /**
86
- * Configuration for streaming query execution.
87
- *
88
- * Controls memory usage during large result set iteration.
89
- * Used with `executeStreaming()` for memory-efficient processing
90
- * of large result sets.
91
- *
92
- * ## Example
93
- *
94
- * ```javascript
95
- * const config = { bufferSize: 512, chunkSize: 5000 };
96
- * for await (const row of db.executeStreaming(query, config)) {
97
- * console.log(row);
98
- * }
99
- * ```
100
- *
101
- * ## Memory Budget
102
- *
103
- * Default values (~11MB peak usage):
104
- * - bufferSize: 1024 rows × ~1KB = ~1MB in flight
105
- * - chunkSize: 10000 rows × ~1KB = ~10MB per chunk
106
- *
107
- * For rows with large blobs, reduce buffer sizes proportionally.
108
- */
109
- export interface StreamingConfig {
110
- /**
111
- * Number of rows to buffer in memory during streaming.
112
- * Controls backpressure. Default: 1024.
113
- */
114
- bufferSize?: number
115
- /**
116
- * Number of rows per fetch chunk from storage.
117
- * Larger chunks improve throughput, smaller chunks reduce memory.
118
- * Default: 10000.
119
- */
120
- chunkSize?: number
121
- }
122
- /**
123
- * Statistics about a prepared statement.
124
- *
125
- * Contains query plan information useful for optimization
126
- * and debugging query performance.
127
- */
128
- export interface PreparedStatementStats {
129
- /** Number of parameters in the query. */
130
- parameterCount: number
131
- /** Type of execution plan (TableScan, IndexScan, PointLookup). */
132
- planType: string
133
- /** Estimated execution cost (relative metric for comparing plans). */
134
- estimatedCost: number
135
- /** Estimated number of rows to be returned. */
136
- estimatedRows: bigint
137
- /** Whether the query is cache-friendly. */
138
- cacheFriendly: boolean
139
- }
140
- /**
141
- * Returns the version of the cqlite-node binding.
142
- *
143
- * @returns The semantic version string (e.g., "0.3.0")
144
- *
145
- * @example
146
- * ```javascript
147
- * const { version } = require('@cqlite/node');
148
- * console.log(`CQLite version: ${version()}`);
149
- * ```
150
- */
151
- export declare function version(): string
152
- /**
153
- * A CQLite database handle.
154
- *
155
- * Use `Database.open()` to create a Database instance.
156
- * Always close the database when done to release resources.
157
- *
158
- * ## Example
159
- *
160
- * ```javascript
161
- * const db = await Database.open('/path/to/data', { schema: '/path/to/schema.cql' });
162
- * try {
163
- * const result = await db.execute('SELECT * FROM users LIMIT 10');
164
- * console.log(`Got ${result.rowCount} rows`);
165
- * } finally {
166
- * await db.close();
167
- * }
168
- * ```
169
- *
170
- * ## Thread Safety
171
- *
172
- * Database handles are thread-safe and can be shared across worker threads.
173
- * The `close()` method is idempotent - calling it multiple times is safe.
174
- */
175
- export declare class Database {
176
- /**
177
- * Opens a database at the specified data directory.
178
- *
179
- * @param dataDir - Path to the SSTable data directory
180
- * @param options - Optional configuration (schema path, etc.)
181
- * @returns Promise resolving to a Database instance
182
- *
183
- * @example
184
- * ```javascript
185
- * // Basic open
186
- * const db = await Database.open('/path/to/sstables');
187
- *
188
- * // With schema file
189
- * const db = await Database.open('/path/to/sstables', {
190
- * schema: '/path/to/schema.cql'
191
- * });
192
- * ```
193
- */
194
- static open(dataDir: string, options?: DatabaseOptions | undefined | null): Promise<Database>
195
- /**
196
- * Execute a CQL query and return results.
197
- *
198
- * Executes a query against the database and returns all matching rows.
199
- * For large result sets, consider using streaming (future feature).
200
- *
201
- * @param query - CQL SELECT statement to execute
202
- * @returns Promise resolving to QueryResult with rows and metadata
203
- *
204
- * @example
205
- * ```javascript
206
- * const result = await db.execute('SELECT * FROM users LIMIT 10');
207
- * console.log(`Got ${result.rowCount} rows in ${result.executionTimeMs}ms`);
208
- * for (const row of result.rows) {
209
- * console.log(row.name);
210
- * }
211
- * ```
212
- */
213
- execute(query: string): Promise<QueryResult>
214
- /**
215
- * Get database statistics.
216
- *
217
- * Returns information about storage, memory usage, and other metrics.
218
- *
219
- * @returns Promise resolving to DatabaseStats
220
- *
221
- * @example
222
- * ```javascript
223
- * const stats = await db.getStats();
224
- * console.log(`SSTables: ${stats.totalSstables}`);
225
- * console.log(`Total rows: ${stats.totalRows}`);
226
- * console.log(`Memory: ${stats.memoryUsedBytes} bytes`);
227
- * ```
228
- */
229
- getStats(): Promise<DatabaseStats>
230
- /**
231
- * Close the database and release resources.
232
- *
233
- * This method is idempotent - calling it multiple times is safe.
234
- * After closing, any operations on the database will throw an error.
235
- *
236
- * @returns Promise resolving when close is complete
237
- *
238
- * @example
239
- * ```javascript
240
- * const db = await Database.open('/path/to/data');
241
- * // ... use database ...
242
- * await db.close();
243
- * await db.close(); // Safe to call again
244
- * ```
245
- */
246
- close(): Promise<void>
247
- /**
248
- * Check if the database is closed.
249
- *
250
- * @returns True if the database has been closed, false otherwise
251
- */
252
- get isClosed(): boolean
253
- /**
254
- * Execute a CQL query with streaming results.
255
- *
256
- * Returns a `StreamingResult` that yields rows one at a time for memory-efficient
257
- * processing of large result sets. Use with JavaScript's `for await...of` loop.
258
- *
259
- * Memory stays bounded by `StreamingConfig` settings (default ~11MB peak):
260
- * - `bufferSize`: 1024 rows in flight
261
- * - `chunkSize`: 10,000 rows per fetch chunk
262
- *
263
- * @param query - CQL SELECT statement to execute
264
- * @param config - Optional StreamingConfig for buffer/chunk sizes
265
- * @returns StreamingResult async iterable (JS wrapper makes this sync)
266
- *
267
- * Note: The native Rust layer returns a Promise, but the JavaScript wrapper
268
- * in error-wrapper.js converts this to a synchronous return of AsyncIterable,
269
- * per M4 spec requirement (Issue #347).
270
- *
271
- * @example
272
- * ```javascript
273
- * // No await on executeStreaming - returns AsyncIterable directly
274
- * for await (const row of db.executeStreaming('SELECT * FROM large_table')) {
275
- * console.log(row.name);
276
- * }
277
- *
278
- * // With custom config for memory constraints
279
- * const config = { bufferSize: 256, chunkSize: 2500 };
280
- * for await (const row of db.executeStreaming(query, config)) {
281
- * process(row);
282
- * }
283
- *
284
- * // Early termination is safe - resources cleaned up automatically
285
- * for await (const row of db.executeStreaming('SELECT * FROM huge_table')) {
286
- * if (row.id === targetId) {
287
- * break;
288
- * }
289
- * }
290
- * ```
291
- */
292
- executeStreaming(query: string, config?: StreamingConfig | undefined | null): Promise<StreamingResult>
293
- /**
294
- * Execute a CQL query and return results with native JavaScript types.
295
- *
296
- * This method returns native JavaScript types instead of JSON:
297
- * - BigInt for bigint/counter columns (preserves 64-bit precision)
298
- * - Buffer for blob columns
299
- * - Date for timestamp/date columns
300
- * - Set for set columns
301
- * - Map for map columns
302
- *
303
- * @param query - CQL SELECT statement to execute
304
- * @returns Promise resolving to NativeQueryResult with native typed rows
305
- *
306
- * @example
307
- * ```javascript
308
- * const result = await db.executeNative('SELECT * FROM users LIMIT 10');
309
- * console.log(`Got ${result.rowCount} rows`);
310
- * for (const row of result.rows) {
311
- * // row.id is a BigInt if the column is bigint type
312
- * // row.created_at is a Date if the column is timestamp
313
- * // row.data is a Buffer if the column is blob
314
- * console.log(row.name, typeof row.id);
315
- * }
316
- * ```
317
- */
318
- executeNative(query: string): Promise<{rows: object[], rowCount: number, executionTimeMs: number, columns: ColumnInfo[]}>
319
- /**
320
- * Prepare a CQL query for analysis.
321
- *
322
- * Returns a PreparedStatement that can be inspected for query plan
323
- * information and statistics.
324
- */
325
- prepare(query: string): Promise<PreparedStatement>
326
- }
327
- /**
328
- * A prepared CQL statement.
329
- *
330
- * PreparedStatement holds a pre-parsed and planned query that can be
331
- * inspected for metadata and statistics. Created via Database.prepare().
332
- */
333
- export declare class PreparedStatement {
334
- /** The original CQL query text. */
335
- get query(): string
336
- /**
337
- * Number of parameters in the query.
338
- * Returns count of placeholder parameters (?), clamped to u32::MAX.
339
- */
340
- get parameterCount(): number
341
- /** Get statistics about this prepared statement. */
342
- stats(): PreparedStatementStats
343
- /** String representation of the prepared statement. */
344
- toString(): string
345
- }
346
- /**
347
- * Streaming query result iterator.
348
- *
349
- * Yields rows one at a time via `next()` method which returns an AsyncTask.
350
- * JavaScript wrapper implements `Symbol.asyncIterator` for `for await...of` support.
351
- *
352
- * ## Resource Cleanup
353
- *
354
- * Resources are cleaned up when:
355
- * 1. All rows consumed (`next()` returns `done: true`)
356
- * 2. Iterator dropped (early break from loop triggers `return()`)
357
- * 3. `close()` called explicitly
358
- * 4. Error occurs
359
- *
360
- * ## Example (JavaScript)
361
- *
362
- * ```javascript
363
- * // No await on executeStreaming - it returns an AsyncIterable directly
364
- * for await (const row of db.executeStreaming('SELECT * FROM large_table')) {
365
- * console.log(row);
366
- * }
367
- * ```
368
- */
369
- export declare class StreamingResult {
370
- /**
371
- * Get the next row from the stream.
372
- *
373
- * Returns an object matching JavaScript's iterator protocol:
374
- * - `{ value: Row, done: false }` - More rows available
375
- * - `{ value: undefined, done: true }` - Stream exhausted
376
- *
377
- * Errors are thrown as exceptions with structured error properties
378
- * (code, category, isRecoverable).
379
- *
380
- * @returns Promise resolving to iterator result object
381
- */
382
- next(): Promise<unknown>
383
- /**
384
- * Number of rows received so far.
385
- *
386
- * This counter increases as rows are yielded from the stream.
387
- * Useful for progress tracking.
388
- *
389
- * @returns Number of rows received
390
- */
391
- get rowsReceived(): number
392
- /**
393
- * Column metadata for the result set.
394
- *
395
- * Contains information about each column's name, type, and nullability.
396
- * Available immediately after creating the streaming result.
397
- *
398
- * @returns Array of ColumnInfo objects
399
- */
400
- get columns(): Array<ColumnInfo>
401
- /**
402
- * Release resources early (synchronous).
403
- *
404
- * Called automatically when:
405
- * - All rows are consumed
406
- * - JavaScript iterator's `return()` is called (e.g., `break` from loop)
407
- * - Error occurs during iteration
408
- *
409
- * Safe to call multiple times - subsequent calls are no-ops.
410
- * This method is synchronous and does not need to be awaited.
411
- */
412
- close(): void
413
- }
package/index.js DELETED
@@ -1,318 +0,0 @@
1
- /* tslint:disable */
2
- /* eslint-disable */
3
- /* prettier-ignore */
4
-
5
- /* auto-generated by NAPI-RS */
6
-
7
- const { existsSync, readFileSync } = require('fs')
8
- const { join } = require('path')
9
-
10
- const { platform, arch } = process
11
-
12
- let nativeBinding = null
13
- let localFileExisted = false
14
- let loadError = null
15
-
16
- function isMusl() {
17
- // For Node 10
18
- if (!process.report || typeof process.report.getReport !== 'function') {
19
- try {
20
- const lddPath = require('child_process').execSync('which ldd').toString().trim()
21
- return readFileSync(lddPath, 'utf8').includes('musl')
22
- } catch (e) {
23
- return true
24
- }
25
- } else {
26
- const { glibcVersionRuntime } = process.report.getReport().header
27
- return !glibcVersionRuntime
28
- }
29
- }
30
-
31
- switch (platform) {
32
- case 'android':
33
- switch (arch) {
34
- case 'arm64':
35
- localFileExisted = existsSync(join(__dirname, 'cqlite-node.android-arm64.node'))
36
- try {
37
- if (localFileExisted) {
38
- nativeBinding = require('./cqlite-node.android-arm64.node')
39
- } else {
40
- nativeBinding = require('@cqlite/node-android-arm64')
41
- }
42
- } catch (e) {
43
- loadError = e
44
- }
45
- break
46
- case 'arm':
47
- localFileExisted = existsSync(join(__dirname, 'cqlite-node.android-arm-eabi.node'))
48
- try {
49
- if (localFileExisted) {
50
- nativeBinding = require('./cqlite-node.android-arm-eabi.node')
51
- } else {
52
- nativeBinding = require('@cqlite/node-android-arm-eabi')
53
- }
54
- } catch (e) {
55
- loadError = e
56
- }
57
- break
58
- default:
59
- throw new Error(`Unsupported architecture on Android ${arch}`)
60
- }
61
- break
62
- case 'win32':
63
- switch (arch) {
64
- case 'x64':
65
- localFileExisted = existsSync(
66
- join(__dirname, 'cqlite-node.win32-x64-msvc.node')
67
- )
68
- try {
69
- if (localFileExisted) {
70
- nativeBinding = require('./cqlite-node.win32-x64-msvc.node')
71
- } else {
72
- nativeBinding = require('@cqlite/node-win32-x64-msvc')
73
- }
74
- } catch (e) {
75
- loadError = e
76
- }
77
- break
78
- case 'ia32':
79
- localFileExisted = existsSync(
80
- join(__dirname, 'cqlite-node.win32-ia32-msvc.node')
81
- )
82
- try {
83
- if (localFileExisted) {
84
- nativeBinding = require('./cqlite-node.win32-ia32-msvc.node')
85
- } else {
86
- nativeBinding = require('@cqlite/node-win32-ia32-msvc')
87
- }
88
- } catch (e) {
89
- loadError = e
90
- }
91
- break
92
- case 'arm64':
93
- localFileExisted = existsSync(
94
- join(__dirname, 'cqlite-node.win32-arm64-msvc.node')
95
- )
96
- try {
97
- if (localFileExisted) {
98
- nativeBinding = require('./cqlite-node.win32-arm64-msvc.node')
99
- } else {
100
- nativeBinding = require('@cqlite/node-win32-arm64-msvc')
101
- }
102
- } catch (e) {
103
- loadError = e
104
- }
105
- break
106
- default:
107
- throw new Error(`Unsupported architecture on Windows: ${arch}`)
108
- }
109
- break
110
- case 'darwin':
111
- localFileExisted = existsSync(join(__dirname, 'cqlite-node.darwin-universal.node'))
112
- try {
113
- if (localFileExisted) {
114
- nativeBinding = require('./cqlite-node.darwin-universal.node')
115
- } else {
116
- nativeBinding = require('@cqlite/node-darwin-universal')
117
- }
118
- break
119
- } catch {}
120
- switch (arch) {
121
- case 'x64':
122
- localFileExisted = existsSync(join(__dirname, 'cqlite-node.darwin-x64.node'))
123
- try {
124
- if (localFileExisted) {
125
- nativeBinding = require('./cqlite-node.darwin-x64.node')
126
- } else {
127
- nativeBinding = require('@cqlite/node-darwin-x64')
128
- }
129
- } catch (e) {
130
- loadError = e
131
- }
132
- break
133
- case 'arm64':
134
- localFileExisted = existsSync(
135
- join(__dirname, 'cqlite-node.darwin-arm64.node')
136
- )
137
- try {
138
- if (localFileExisted) {
139
- nativeBinding = require('./cqlite-node.darwin-arm64.node')
140
- } else {
141
- nativeBinding = require('@cqlite/node-darwin-arm64')
142
- }
143
- } catch (e) {
144
- loadError = e
145
- }
146
- break
147
- default:
148
- throw new Error(`Unsupported architecture on macOS: ${arch}`)
149
- }
150
- break
151
- case 'freebsd':
152
- if (arch !== 'x64') {
153
- throw new Error(`Unsupported architecture on FreeBSD: ${arch}`)
154
- }
155
- localFileExisted = existsSync(join(__dirname, 'cqlite-node.freebsd-x64.node'))
156
- try {
157
- if (localFileExisted) {
158
- nativeBinding = require('./cqlite-node.freebsd-x64.node')
159
- } else {
160
- nativeBinding = require('@cqlite/node-freebsd-x64')
161
- }
162
- } catch (e) {
163
- loadError = e
164
- }
165
- break
166
- case 'linux':
167
- switch (arch) {
168
- case 'x64':
169
- if (isMusl()) {
170
- localFileExisted = existsSync(
171
- join(__dirname, 'cqlite-node.linux-x64-musl.node')
172
- )
173
- try {
174
- if (localFileExisted) {
175
- nativeBinding = require('./cqlite-node.linux-x64-musl.node')
176
- } else {
177
- nativeBinding = require('@cqlite/node-linux-x64-musl')
178
- }
179
- } catch (e) {
180
- loadError = e
181
- }
182
- } else {
183
- localFileExisted = existsSync(
184
- join(__dirname, 'cqlite-node.linux-x64-gnu.node')
185
- )
186
- try {
187
- if (localFileExisted) {
188
- nativeBinding = require('./cqlite-node.linux-x64-gnu.node')
189
- } else {
190
- nativeBinding = require('@cqlite/node-linux-x64-gnu')
191
- }
192
- } catch (e) {
193
- loadError = e
194
- }
195
- }
196
- break
197
- case 'arm64':
198
- if (isMusl()) {
199
- localFileExisted = existsSync(
200
- join(__dirname, 'cqlite-node.linux-arm64-musl.node')
201
- )
202
- try {
203
- if (localFileExisted) {
204
- nativeBinding = require('./cqlite-node.linux-arm64-musl.node')
205
- } else {
206
- nativeBinding = require('@cqlite/node-linux-arm64-musl')
207
- }
208
- } catch (e) {
209
- loadError = e
210
- }
211
- } else {
212
- localFileExisted = existsSync(
213
- join(__dirname, 'cqlite-node.linux-arm64-gnu.node')
214
- )
215
- try {
216
- if (localFileExisted) {
217
- nativeBinding = require('./cqlite-node.linux-arm64-gnu.node')
218
- } else {
219
- nativeBinding = require('@cqlite/node-linux-arm64-gnu')
220
- }
221
- } catch (e) {
222
- loadError = e
223
- }
224
- }
225
- break
226
- case 'arm':
227
- if (isMusl()) {
228
- localFileExisted = existsSync(
229
- join(__dirname, 'cqlite-node.linux-arm-musleabihf.node')
230
- )
231
- try {
232
- if (localFileExisted) {
233
- nativeBinding = require('./cqlite-node.linux-arm-musleabihf.node')
234
- } else {
235
- nativeBinding = require('@cqlite/node-linux-arm-musleabihf')
236
- }
237
- } catch (e) {
238
- loadError = e
239
- }
240
- } else {
241
- localFileExisted = existsSync(
242
- join(__dirname, 'cqlite-node.linux-arm-gnueabihf.node')
243
- )
244
- try {
245
- if (localFileExisted) {
246
- nativeBinding = require('./cqlite-node.linux-arm-gnueabihf.node')
247
- } else {
248
- nativeBinding = require('@cqlite/node-linux-arm-gnueabihf')
249
- }
250
- } catch (e) {
251
- loadError = e
252
- }
253
- }
254
- break
255
- case 'riscv64':
256
- if (isMusl()) {
257
- localFileExisted = existsSync(
258
- join(__dirname, 'cqlite-node.linux-riscv64-musl.node')
259
- )
260
- try {
261
- if (localFileExisted) {
262
- nativeBinding = require('./cqlite-node.linux-riscv64-musl.node')
263
- } else {
264
- nativeBinding = require('@cqlite/node-linux-riscv64-musl')
265
- }
266
- } catch (e) {
267
- loadError = e
268
- }
269
- } else {
270
- localFileExisted = existsSync(
271
- join(__dirname, 'cqlite-node.linux-riscv64-gnu.node')
272
- )
273
- try {
274
- if (localFileExisted) {
275
- nativeBinding = require('./cqlite-node.linux-riscv64-gnu.node')
276
- } else {
277
- nativeBinding = require('@cqlite/node-linux-riscv64-gnu')
278
- }
279
- } catch (e) {
280
- loadError = e
281
- }
282
- }
283
- break
284
- case 's390x':
285
- localFileExisted = existsSync(
286
- join(__dirname, 'cqlite-node.linux-s390x-gnu.node')
287
- )
288
- try {
289
- if (localFileExisted) {
290
- nativeBinding = require('./cqlite-node.linux-s390x-gnu.node')
291
- } else {
292
- nativeBinding = require('@cqlite/node-linux-s390x-gnu')
293
- }
294
- } catch (e) {
295
- loadError = e
296
- }
297
- break
298
- default:
299
- throw new Error(`Unsupported architecture on Linux: ${arch}`)
300
- }
301
- break
302
- default:
303
- throw new Error(`Unsupported OS: ${platform}, architecture: ${arch}`)
304
- }
305
-
306
- if (!nativeBinding) {
307
- if (loadError) {
308
- throw loadError
309
- }
310
- throw new Error(`Failed to load native binding`)
311
- }
312
-
313
- const { Database, PreparedStatement, StreamingResult, version } = nativeBinding
314
-
315
- module.exports.Database = Database
316
- module.exports.PreparedStatement = PreparedStatement
317
- module.exports.StreamingResult = StreamingResult
318
- module.exports.version = version