[fix] #1 js bindings

Signed-off-by: Anton Nesterov <anton@demiurg.io>
This commit is contained in:
Anton Nesterov 2024-08-26 22:51:43 +02:00
parent ad8614f30c
commit 48a26223c0
No known key found for this signature in database
GPG key ID: 59121E8AE2851FB5
2 changed files with 22 additions and 11 deletions

View file

@ -1,7 +1,11 @@
import { createRequire } from "node:module"; import { createRequire } from "node:module";
const require = createRequire(import.meta.url); const require = createRequire(import.meta.url);
type RowIterator = {
next: () => Buffer;
free: () => void;
};
type SQLite = { type SQLite = {
InitSQLite: (pragmas: Buffer) => void; InitSQLite: (pragmas: Buffer) => void;
Handle: (input: Buffer) => Buffer; RowIterator: (input: Buffer) => RowIterator;
}; };
export default require("../build/Release/dal.node") as SQLite; export default require("../build/Release/dal.node") as SQLite;

View file

@ -18,20 +18,26 @@ export default class CBuilder<
super({ database: opts.database, url: "" }); super({ database: opts.database, url: "" });
} }
/** /**
* Not really an iterator, since addonn allocates memory for all rows * TODO: handle responses
* but returns an iterator
*/ */
async *Rows<T = InstanceType<I>>(): AsyncGenerator<T> { async *Rows<T = InstanceType<I>>(): AsyncGenerator<T> {
this.formatRequest(); this.formatRequest();
const req = Buffer.from(encodeRequest(this.request)); const req = Buffer.from(encodeRequest(this.request));
const response = Binding.Handle(req); const iter = Binding.RowIterator(req);
const rows = decodeRows(response); for (;;) {
for (const row of rows) { const response = iter.next();
if (this.headerRow === null) { const rows = decodeRows(response);
this.headerRow = row.r; if (rows.length === 0) {
continue; iter.free();
break;
}
for (const row of rows) {
if (this.headerRow === null) {
this.headerRow = row.r;
continue;
}
yield this.formatRow(row.r);
} }
yield this.formatRow(row.r);
} }
} }
async Query<T = InstanceType<I>>(): Promise<T[]> { async Query<T = InstanceType<I>>(): Promise<T[]> {
@ -45,7 +51,8 @@ export default class CBuilder<
async Exec(): Promise<ExecResult> { async Exec(): Promise<ExecResult> {
this.formatRequest(); this.formatRequest();
const req = Buffer.from(encodeRequest(this.request)); const req = Buffer.from(encodeRequest(this.request));
const response = Binding.Handle(req); const iter = Binding.RowIterator(req);
const response = iter.next();
return decodeResponse(response); return decodeResponse(response);
} }
} }