2024-08-21 01:28:40 +00:00
|
|
|
import Builder from "./Builder";
|
2024-09-02 23:11:17 +00:00
|
|
|
import Napi from "./napi";
|
2024-08-21 01:28:40 +00:00
|
|
|
import { encodeRequest, decodeRows, decodeResponse } from "./Protocol";
|
2024-09-02 23:11:17 +00:00
|
|
|
import type { ExecResult, IError } from "./Protocol";
|
2024-08-21 01:28:40 +00:00
|
|
|
|
2024-09-02 10:37:34 +00:00
|
|
|
//@ts-ignore
|
2024-09-02 23:11:17 +00:00
|
|
|
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.
|
|
|
|
*/
|
2024-09-02 23:11:17 +00:00
|
|
|
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: "" });
|
|
|
|
}
|
2024-09-02 23:11:17 +00:00
|
|
|
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);
|
2024-08-26 20:51:43 +00:00
|
|
|
for (;;) {
|
2024-09-02 23:11:17 +00:00
|
|
|
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
|
|
|
}
|
2024-09-02 23:11:17 +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;
|
2024-08-26 20:51:43 +00:00
|
|
|
}
|
|
|
|
for (const row of rows) {
|
|
|
|
if (this.headerRow === null) {
|
|
|
|
this.headerRow = row.r;
|
|
|
|
continue;
|
|
|
|
}
|
2024-09-02 23:11:17 +00:00
|
|
|
yield [this.formatRow(row.r), null];
|
2024-08-21 01:28:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-09-02 23:11:17 +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);
|
2024-08-26 20:51:43 +00:00
|
|
|
const response = iter.next();
|
2024-09-02 10:37:34 +00:00
|
|
|
return decodeResponse(response)!;
|
2024-08-21 01:28:40 +00:00
|
|
|
}
|
|
|
|
}
|