-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.ts
executable file
·85 lines (79 loc) · 2.58 KB
/
mod.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import type { Database } from "@db/sqlite";
import type * as zen from "@dldc/zendb";
export interface TDbDatabase {
exec<Op extends zen.TOperation>(op: Op): zen.TOperationResult<Op>;
execMany<Op extends zen.TOperation>(ops: Op[]): zen.TOperationResult<Op>[];
readonly sqlDb: Database;
}
export function DbDatabase(sqlDb: Database): TDbDatabase {
return {
exec,
execMany,
sqlDb,
};
function exec<Op extends zen.TOperation>(op: Op): zen.TOperationResult<Op> {
if (op.kind === "CreateTable") {
sqlDb.exec(op.sql);
return opResult<zen.TCreateTableOperation>(null);
}
if (op.kind === "DropTable") {
sqlDb.exec(op.sql);
return opResult<zen.TDropTableOperation>(null);
}
if (op.kind === "Insert") {
sqlDb.prepare(op.sql).run(op.params);
return opResult<zen.TInsertOperation<any>>(op.parse());
}
if (op.kind === "InsertMany") {
sqlDb.prepare(op.sql).run(op.params);
return opResult<zen.TInsertOperation<any>>(op.parse());
}
if (op.kind === "Delete") {
const stmt = sqlDb.prepare(op.sql);
const res = op.params ? stmt.run(op.params) : stmt.run();
return opResult<zen.TDeleteOperation>(op.parse({ deleted: res }));
}
if (op.kind === "Update") {
const stmt = sqlDb.prepare(op.sql);
const res = op.params ? stmt.run(op.params) : stmt.run();
return opResult<zen.TUpdateOperation>(op.parse({ updated: res }));
}
if (op.kind === "Query") {
const stmt = sqlDb.prepare(op.sql);
const res = op.params ? stmt.all(op.params) : stmt.all();
return opResult<zen.TQueryOperation<any>>(
op.parse(res as Record<string, any>[]),
);
}
if (op.kind === "ListTables") {
const res = sqlDb.prepare(op.sql).all();
return opResult<zen.TListTablesOperation>(
op.parse(res as Record<string, any>[]),
);
}
if (op.kind === "Pragma") {
const res = sqlDb.prepare(op.sql).all();
return opResult<zen.TPragmaOperation<any>>(
op.parse(res as Record<string, any>[]),
);
}
if (op.kind === "PragmaSet") {
sqlDb.prepare(op.sql).run();
return opResult<zen.TPragmaSetOperation>(null);
}
return expectNever(op);
}
function opResult<Op extends zen.TOperation>(
res: zen.TOperationResult<Op>,
): zen.TOperationResult<zen.TOperation> {
return res;
}
function execMany<Op extends zen.TOperation>(
ops: Op[],
): zen.TOperationResult<Op>[] {
return ops.map((op) => exec(op));
}
}
function expectNever(val: never): never {
throw new Error(`Unexpected value: ${val as any}`);
}