This repository has been archived by the owner on Nov 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
connection.ts
70 lines (59 loc) · 1.67 KB
/
connection.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import {
deno_sqlite3_close,
deno_sqlite3_open,
fill_result,
get_last_error,
get_result_len,
sqlite3_execute,
sqlite3_execute_sync,
sqlite3_open_memory,
sqlite3_query,
Value,
} from "./bindings/bindings.ts";
import { decodeArray, encode, fromValue, intoValue } from "./value.ts";
const CONNECTION_IDS: Connection[] = [];
async function exec(f: () => Promise<number> | number) {
const err_len = await f();
if (err_len !== -1) {
const err_slice = new Uint8Array(err_len);
get_last_error(err_slice);
const error = decode(err_slice);
throw new TypeError(error);
}
}
export class Connection {
#_id: number | null = null;
get id(): number {
if (this.#_id == null) throw new TypeError("Connection is closed.");
return this.#_id;
}
async open(path: string) {
this.#_id = CONNECTION_IDS.push(this);
await exec(() => this.#open(path));
}
#open(specifier: string) {
if (specifier == ":memory:") {
return sqlite3_open_memory(this.id);
}
return deno_sqlite3_open(this.id, specifier);
}
close() {
exec(() => deno_sqlite3_close(this.id));
this.#_id = null;
}
async execute(stmt: string, params: any[] = []) {
const u8 = encode(params);
await exec(() => sqlite3_execute(this.id, stmt, u8));
}
async query(stmt: string, params: any[] = []) {
const u8 = encode(params);
const resultLen = new Uint8Array(4);
const view = new DataView(resultLen.buffer);
await exec(() => sqlite3_query(this.id, stmt, u8, resultLen));
const len = view.getUint32(0);
const resultBuf = new Uint8Array(len);
fill_result(resultBuf);
const result = decodeArray(resultBuf);
return result;
}
}