-
-
Notifications
You must be signed in to change notification settings - Fork 89
/
tag.ts
66 lines (56 loc) · 1.74 KB
/
tag.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
import { processTSQueryAST } from './preprocessor-ts';
import { processSQLQueryAST } from './preprocessor-sql';
import { Query as QueryAST } from './loader/sql';
import { parseTSQuery, TSQueryAST } from './loader/typescript';
export interface IDatabaseConnection {
query: (query: string, bindings: any[]) => Promise<{ rows: any[] }>;
}
/* Used for SQL-in-TS */
export class TaggedQuery<TTypePair extends { params: any; result: any }> {
public run: (
params: TTypePair['params'],
dbConnection: IDatabaseConnection,
) => Promise<Array<TTypePair['result']>>;
private readonly query: TSQueryAST;
constructor(query: TSQueryAST) {
this.query = query;
this.run = async (params, connection) => {
const { query: processedQuery, bindings } = processTSQueryAST(
this.query,
params as any,
);
const result = await connection.query(processedQuery, bindings);
return result.rows;
};
}
}
interface ITypePair {
params: any;
result: any;
}
const sql = <TTypePair extends ITypePair>(
stringsArray: TemplateStringsArray,
) => {
const { query } = parseTSQuery(stringsArray[0]);
return new TaggedQuery<TTypePair>(query);
};
/* Used for pure SQL */
export class PreparedQuery<TParamType, TResultType> {
public run: (
params: TParamType,
dbConnection: IDatabaseConnection,
) => Promise<Array<TResultType>>;
private readonly query: QueryAST;
constructor(query: QueryAST) {
this.query = query;
this.run = async (params, connection) => {
const { query: processedQuery, bindings } = processSQLQueryAST(
this.query,
params as any,
);
const result = await connection.query(processedQuery, bindings);
return result.rows;
};
}
}
export default sql;