-
Notifications
You must be signed in to change notification settings - Fork 0
/
cursor.ts
307 lines (252 loc) · 9.04 KB
/
cursor.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import {
Connection
} from './connection.ts'
import {
DeferredStack
} from './deferred.ts'
import {
TypeReader,
TypeWriter
} from './types.ts'
export interface CursorOptions {
maxRows?: number
}
export class Cursor {
connections?: DeferredStack<Connection>
constructor(
public connection: Connection | DeferredStack<Connection>,
public options: CursorOptions
) {
// check current connection is DeferredStack
if (connection instanceof DeferredStack) {
this.connections = connection
}
}
async _query(options: QueryOptions, type: QueryResultType): Promise<QueryResult> {
let connection: Connection
// if connections pool, then acquire this connection
if (this.connections) {
connection = await this.connections.pop()
// this only normal connection without pool
} else {
connection = this.connection as Connection
}
try {
// execute connection query
return await connection.query(options, type)
} finally {
// if connections pool, then release this connection
if (this.connections) {
this.connections.push(connection)
}
}
}
}
export class ArrayCursor extends Cursor {
query<ResultT extends Array<unknown>>(
query: string,
// deno-lint-ignore no-explicit-any
...paramenters: any[]
): Promise<ArrayQueryResult<ResultT>>
query<ResultT extends Array<unknown>>(
options: QueryOptions
): Promise<ArrayQueryResult<ResultT>>
query<ResultT extends Array<unknown>>(
template: TemplateStringsArray,
// deno-lint-ignore no-explicit-any
...paramenters: any[]
): Promise<ArrayQueryResult<ResultT>>
query<ResultT extends Array<unknown> = Array<unknown>>(
overloadArg: string | QueryOptions | TemplateStringsArray,
// deno-lint-ignore no-explicit-any
...paramenters: any[]
): Promise<ArrayQueryResult<ResultT>> {
let queryOptions;
if (typeof overloadArg === 'string') {
queryOptions = new QueryOptions(overloadArg, ...paramenters)
// } else if (Array.isArray(overloadArg)) {
} else if (templateString(overloadArg)) {
const options = overloadArg.reduce((current, next, index) => {
return `${current}$${index}${next}`
})
queryOptions = new QueryOptions(options, ...paramenters)
} else {
queryOptions = new QueryOptions(overloadArg)
}
return this._query(
queryOptions,
QueryResultType.ARRAY
) as Promise<ArrayQueryResult<ResultT>>
}
}
export class ObjectCursor extends Cursor {
query<ResultT extends Record<string, unknown>>(
query: string,
// deno-lint-ignore no-explicit-any
...paramenters: any[]
): Promise<ObjectQueryResult<ResultT>>
query<ResultT extends Record<string, unknown>>(
options: QueryOptions
): Promise<ObjectQueryResult<ResultT>>
query<ResultT extends Record<string, unknown>>(
template: TemplateStringsArray,
// deno-lint-ignore no-explicit-any
...paramenters: any[]
): Promise<ObjectQueryResult<ResultT>>
query<ResultT extends Record<string, unknown> = Record<string, unknown>>(
overloadArg: string | QueryOptions | TemplateStringsArray,
// deno-lint-ignore no-explicit-any
...paramenters: any[]
): Promise<ObjectQueryResult<ResultT>> {
let queryOptions;
if (typeof overloadArg === 'string') {
queryOptions = new QueryOptions(overloadArg, ...paramenters)
// } else if (Array.isArray(overloadArg)) {
} else if (templateString(overloadArg)) {
const options = overloadArg.reduce((current, next, index) => {
return `${current}$${index}${next}`
})
queryOptions = new QueryOptions(options, ...paramenters)
} else {
queryOptions = new QueryOptions(overloadArg)
}
return this._query(
queryOptions,
QueryResultType.ARRAY
) as Promise<ObjectQueryResult<ResultT>>
}
}
export type EncodedParameter = null | string | Uint8Array
/**
* query options pased to simpleQuery/entendedQuery
*/
export interface ArrayQueryOptions {
portal?: string, // postgres portal name, default is empty string
statement?: string, // postgres prepare statement name, default is empty string
query: string,
parameters?: Array<unknown>,
parameterMapper?: (parameter: unknown) => EncodedParameter
}
export interface ObjectQueryOptions {
portal?: string, // postgres portal name, default is empty string
statement?: string, // postgres prepare statement name, default is empty string
query: string,
parameters?: Array<unknown>,
parameterMapper?: (parameter: unknown) => EncodedParameter
fields?: string[] // special for object query
}
export class QueryOptions {
public portal: string
public statement: string
public query: string
public parameters?: EncodedParameter[]
public fields?: string[]
constructor(options: ObjectQueryOptions)
constructor(query: string, ...parameters: unknown[])
constructor(overloadArg: ObjectQueryOptions | string, ...parameters: unknown[]) {
let queryOptions: ArrayQueryOptions
if (typeof overloadArg === 'string') {
queryOptions = {
query: overloadArg,
parameters
}
} else {
const {
fields,
...restOptions
} = overloadArg
// check fields valid
if (fields) {
const cleanFields = fields.map((field) =>
field.toString().toLowerCase()
)
if ((new Set(cleanFields)).size !== cleanFields.length) {
throw new Error(`fields for query not unique`)
}
this.fields = cleanFields
}
queryOptions = restOptions
}
this.portal = queryOptions.portal || ''
this.statement = queryOptions.statement || ''
this.query = queryOptions.query
this.parameters = this.optionsParameters(queryOptions)
}
private optionsParameters(options: ArrayQueryOptions): EncodedParameter[] {
const parameterMapper = options.parameterMapper ? options.parameterMapper : new TypeWriter().encode
return (options.parameters || []).map(parameterMapper)
}
}
/**
* query result prepare for cursor query
*/
const typeReader = new TypeReader()
export class QueryResult {
public command?: string // command tag
public count?: number = 0 // rowCount
// deno-lint-ignore no-explicit-any
public description?: Record<string, any> = {} // rowDescription
// deno-lint-ignore no-explicit-any
public warnings?: Record<string, any> = {}
constructor(public queryOptions: QueryOptions) {}
insert(row: Uint8Array[]) {
throw new Error(`not implemented`)
}
}
export class ArrayQueryResult<ResultT extends Array<unknown>> extends QueryResult {
public rows: ResultT[] = [] // dataRow
insert(row: Uint8Array[]) {
if (!this.description) {
throw new Error(`row description required before rows parse`)
}
const decodedValue = row.map((rawValue, index) => {
const field = this.description!.fields[index]
if (rawValue === null) {
return null
}
return typeReader.decode(rawValue, field.dataTypeId)
}) as ResultT
this.rows.push(decodedValue)
}
}
export class ObjectQueryResult<ResultT extends Record<string, unknown>> extends QueryResult {
public rows: ResultT[] = [] // dataRow
insert(row: Uint8Array[]) {
if (!this.description) {
throw new Error(`row description required before rows parse`)
}
if (
this.queryOptions.fields
&& this.queryOptions.fields.length !== this.description!.fields.length
) {
throw new Error(`fields provided for query not match rows description fields`)
}
const decodedValue = row.reduce((row, rawValue, index) => {
const field = this.description!.fields[index]
const name = this.queryOptions.fields?.[index] ?? field.name
if (rawValue === null) {
row[name] = null
} else {
row[name] = typeReader.decode(rawValue, field.dataTypeId)
}
return row
}, {} as Record<string, unknown>) as ResultT
this.rows.push(decodedValue)
}
}
export enum QueryResultType {
ARRAY = 0x00,
OBJECT = 0x01,
}
/**
* this is typescript stupid check alias for Array.isArray
*/
function templateString(
// deno-lint-ignore no-explicit-any
template: any
): template is TemplateStringsArray {
if (Array.isArray(template)) {
return true
}
return false
}