[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,14 +18,19 @@ 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);
for (;;) {
const response = iter.next();
const rows = decodeRows(response); const rows = decodeRows(response);
if (rows.length === 0) {
iter.free();
break;
}
for (const row of rows) { for (const row of rows) {
if (this.headerRow === null) { if (this.headerRow === null) {
this.headerRow = row.r; this.headerRow = row.r;
@ -34,6 +39,7 @@ export default class CBuilder<
yield this.formatRow(row.r); yield this.formatRow(row.r);
} }
} }
}
async Query<T = InstanceType<I>>(): Promise<T[]> { async Query<T = InstanceType<I>>(): Promise<T[]> {
const rows = this.Rows(); const rows = this.Rows();
const result: T[] = []; const result: 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);
} }
} }