-
Notifications
You must be signed in to change notification settings - Fork 92
/
query.ts
86 lines (68 loc) · 2.22 KB
/
query.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
86
import { RowDescription, Column, Format } from "./connection.ts";
import { Connection } from "./connection.ts";
import { encode, EncodedArg } from "./encode.ts";
import { decode } from "./decode.ts";
export interface QueryConfig {
text: string;
args?: any[];
name?: string;
encoder?: (arg: any) => EncodedArg,
}
export class QueryResult {
private rowDescription: RowDescription;
private _done = false;
public rows: any[] = []; // actual results
constructor(public query: Query) {}
handleRowDescription(description: RowDescription) {
this.rowDescription = description;
}
private _parseDataRow(dataRow: any[]): any[] {
const parsedRow = [];
for (let i = 0, len = dataRow.length; i < len; i++) {
const column = this.rowDescription.columns[i];
const rawValue = dataRow[i];
if (rawValue === null) {
parsedRow.push(null);
} else {
parsedRow.push(decode(rawValue, column))
}
}
return parsedRow;
}
handleDataRow(dataRow: any[]): void {
if (this._done) {
throw new Error("New data row, after result if done.");
}
const parsedRow = this._parseDataRow(dataRow);
this.rows.push(parsedRow);
}
rowsOfObjects() {
return this.rows.map((row, index) => {
const rv: {[key: string]: any} = {};
this.rowDescription.columns.forEach(column => {
rv[column.name] = row[index];
})
return rv;
})
}
done() {
this._done = true;
}
}
export class Query {
public text: string;
public args: EncodedArg[];
public result: QueryResult;
constructor(public connection: Connection, config: QueryConfig) {
this.text = config.text;
this.args = this._prepareArgs(config);
this.result = new QueryResult(this);
}
private _prepareArgs(config: QueryConfig): EncodedArg[] {
const encodingFn = config.encoder ? config.encoder : encode;
return config.args.map(encodingFn);
}
async execute(): Promise<QueryResult> {
return await this.connection.query(this);
}
}