dal/client/native.ts

56 lines
1.5 KiB
TypeScript
Raw Normal View History

2024-08-21 01:28:40 +00:00
import Builder from "./Builder";
import Napi from "./napi";
2024-08-21 01:28:40 +00:00
import { encodeRequest, decodeRows, decodeResponse } from "./Protocol";
import type { ExecResult, IError } from "./Protocol";
2024-08-21 01:28:40 +00:00
2024-09-02 10:37:34 +00:00
//@ts-ignore
const Binding = Napi.default ?? Napi;
2024-09-02 10:37:34 +00:00
2024-08-21 01:28:40 +00:00
type Options = {
database: string;
};
/**
* Allows to use SQLite databases in a NodeJS process.
*/
export default class C <
2024-08-21 01:28:40 +00:00
I extends abstract new (...args: any) => any,
> extends Builder<I> {
constructor(opts: Options) {
super({ database: opts.database, url: "" });
}
async *Rows<T = InstanceType<I>>(): AsyncGenerator<[T, IError]> {
2024-08-21 01:28:40 +00:00
this.formatRequest();
const req = Buffer.from(encodeRequest(this.request));
2024-08-29 20:13:48 +00:00
const iter = Binding.rowIterator(req);
for (;;) {
const data = iter.next() as Buffer;
const [_, error] = decodeResponse(data);
if (error) {
yield [{} as T, error];
iter.cleanup();
return;
2024-09-02 10:37:34 +00:00
}
const [rows, err] = decodeRows(data);
if (err || !rows || rows.length === 0) {
2024-08-29 20:39:27 +00:00
iter.cleanup();
2024-09-02 10:37:34 +00:00
return;
}
for (const row of rows) {
if (this.headerRow === null) {
this.headerRow = row.r;
continue;
}
yield [this.formatRow(row.r), null];
2024-08-21 01:28:40 +00:00
}
}
}
async Exec(): Promise<[ExecResult, IError]> {
2024-08-21 01:28:40 +00:00
this.formatRequest();
const req = Buffer.from(encodeRequest(this.request));
2024-08-29 20:13:48 +00:00
const iter = Binding.rowIterator(req);
const response = iter.next();
2024-09-02 10:37:34 +00:00
return decodeResponse(response)!;
2024-08-21 01:28:40 +00:00
}
}