-
Notifications
You must be signed in to change notification settings - Fork 35
/
index.ts
381 lines (322 loc) · 9.38 KB
/
index.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
import { cast } from './cast.js'
export { cast } from './cast.js'
import { format } from './sanitization.js'
export { format } from './sanitization.js'
export { hex } from './text.js'
import { Version } from './version.js'
type Row<T extends ExecuteAs = 'object'> = T extends 'array' ? any[] : T extends 'object' ? Record<string, any> : never
interface VitessError {
message: string
code: string
}
export class DatabaseError extends Error {
body: VitessError
status: number
constructor(message: string, status: number, body: VitessError) {
super(message)
this.status = status
this.name = 'DatabaseError'
this.body = body
}
}
type Types = Record<string, string>
export interface ExecutedQuery<T = Row<'array'> | Row<'object'>> {
headers: string[]
types: Types
rows: T[]
fields: Field[]
size: number
statement: string
insertId: string
rowsAffected: number
time: number
}
type Fetch = (input: string, init?: Req) => Promise<Res>
type Req = {
method: string
headers: Record<string, string>
body: string
cache?: RequestCache
}
type Res = {
ok: boolean
status: number
statusText: string
json(): Promise<any>
text(): Promise<string>
}
export type Cast = typeof cast
type Format = typeof format
export interface Config {
url?: string
username?: string
password?: string
host?: string
fetch?: Fetch
format?: Format
cast?: Cast
}
interface QueryResultRow {
lengths: string[]
values?: string
}
export interface Field {
name: string
type: string
table?: string
// Only populated for included fields
orgTable?: string | null
database?: string | null
orgName?: string | null
columnLength?: number | null
charset?: number | null
decimals?: number
flags?: number | null
columnType?: string | null
}
type QuerySession = unknown
interface QueryExecuteResponse {
session: QuerySession
result: QueryResult | null
error?: VitessError
timing?: number // duration in seconds
}
interface QueryResult {
rowsAffected?: string | null
insertId?: string | null
fields?: Field[] | null
rows?: QueryResultRow[]
}
type ExecuteAs = 'array' | 'object'
type ExecuteArgs = Record<string, any> | any[] | null
type ExecuteOptions<T extends ExecuteAs = 'object'> = T extends 'array'
? { as?: 'object'; cast?: Cast }
: T extends 'object'
? { as: 'array'; cast?: Cast }
: never
export class Client {
public readonly config: Config
constructor(config: Config) {
this.config = config
}
async transaction<T>(fn: (tx: Transaction) => Promise<T>): Promise<T> {
return this.connection().transaction(fn)
}
async execute<T = Row<'object'>>(
query: string,
args?: ExecuteArgs,
options?: ExecuteOptions<'object'>
): Promise<ExecutedQuery<T>>
async execute<T = Row<'array'>>(
query: string,
args: ExecuteArgs,
options: ExecuteOptions<'array'>
): Promise<ExecutedQuery<T>>
async execute<T = Row<'object'> | Row<'array'>>(
query: string,
args: ExecuteArgs = null,
options: any = { as: 'object' }
): Promise<ExecutedQuery<T>> {
return this.connection().execute<T>(query, args, options)
}
connection(): Connection {
return new Connection(this.config)
}
}
export type Transaction = Tx
class Tx {
private conn: Connection
constructor(conn: Connection) {
this.conn = conn
}
async execute<T = Row<'object'>>(
query: string,
args?: ExecuteArgs,
options?: ExecuteOptions<'object'>
): Promise<ExecutedQuery<T>>
async execute<T = Row<'array'>>(
query: string,
args: ExecuteArgs,
options: ExecuteOptions<'array'>
): Promise<ExecutedQuery<T>>
async execute<T = Row<'object'> | Row<'array'>>(
query: string,
args: ExecuteArgs = null,
options: any = { as: 'object' }
): Promise<ExecutedQuery<T>> {
return this.conn.execute<T>(query, args, options)
}
}
function protocol(protocol: string): string {
return protocol === 'http:' ? protocol : 'https:'
}
function buildURL(url: URL): string {
const scheme = `${protocol(url.protocol)}//`
return new URL(url.pathname, `${scheme}${url.host}`).toString()
}
export class Connection {
public readonly config: Config
private fetch: Fetch
private session: QuerySession | null
private url: string
constructor(config: Config) {
this.config = config
this.fetch = config.fetch || fetch!
this.session = null
if (config.url) {
const url = new URL(config.url)
this.config.username = url.username
this.config.password = url.password
this.config.host = url.hostname
this.url = buildURL(url)
} else {
this.url = new URL(`https://${this.config.host}`).toString()
}
}
async transaction<T>(fn: (tx: Transaction) => Promise<T>): Promise<T> {
const conn = new Connection(this.config) // Create a new connection specifically for the transaction
const tx = new Tx(conn)
try {
await tx.execute('BEGIN')
const res = await fn(tx)
await tx.execute('COMMIT')
return res
} catch (err) {
await tx.execute('ROLLBACK')
throw err
}
}
async refresh(): Promise<void> {
await this.createSession()
}
async execute<T = Row<'object'>>(
query: string,
args?: ExecuteArgs,
options?: ExecuteOptions<'object'>
): Promise<ExecutedQuery<T>>
async execute<T = Row<'array'>>(
query: string,
args: ExecuteArgs,
options: ExecuteOptions<'array'>
): Promise<ExecutedQuery<T>>
async execute<T = Row<'object'> | Row<'array'>>(
query: string,
args: ExecuteArgs = null,
options: any = { as: 'object' }
): Promise<ExecutedQuery<T>> {
const url = new URL('/psdb.v1alpha1.Database/Execute', this.url)
const formatter = this.config.format || format
const sql = args ? formatter(query, args) : query
const saved = await postJSON<QueryExecuteResponse>(this.config, this.fetch, url, {
query: sql,
session: this.session
})
const { result, session, error, timing } = saved
if (session) {
this.session = session
}
if (error) {
throw new DatabaseError(error.message, 400, error)
}
const rowsAffected = result?.rowsAffected ? parseInt(result.rowsAffected, 10) : 0
const insertId = result?.insertId ?? '0'
const fields = result?.fields ?? []
// ensure each field has a type assigned,
// the only case it would be omitted is in the case of
// NULL due to the protojson spec. NULL in our enum
// is 0, and empty fields are omitted from the JSON response,
// so we should backfill an expected type.
for (const field of fields) {
field.type ||= 'NULL'
}
const castFn = options.cast || this.config.cast || cast
const rows = result ? parse<T>(result, castFn, options.as || 'object') : []
const headers = fields.map((f) => f.name)
const typeByName = (acc: Types, { name, type }: Field) => ({ ...acc, [name]: type })
const types = fields.reduce<Types>(typeByName, {})
const timingSeconds = timing ?? 0
return {
headers,
types,
fields,
rows,
rowsAffected,
insertId,
size: rows.length,
statement: sql,
time: timingSeconds * 1000
}
}
private async createSession(): Promise<QuerySession> {
const url = new URL('/psdb.v1alpha1.Database/CreateSession', this.url)
const { session } = await postJSON<QueryExecuteResponse>(this.config, this.fetch, url)
this.session = session
return session
}
}
async function postJSON<T>(config: Config, fetch: Fetch, url: string | URL, body = {}): Promise<T> {
const auth = btoa(`${config.username}:${config.password}`)
const response = await fetch(url.toString(), {
method: 'POST',
body: JSON.stringify(body),
headers: {
'Content-Type': 'application/json',
'User-Agent': `database-js/${Version}`,
Authorization: `Basic ${auth}`
},
cache: 'no-store'
})
if (response.ok) {
return await response.json()
} else {
let error = null
try {
const e = (await response.json()).error
error = new DatabaseError(e.message, response.status, e)
} catch {
error = new DatabaseError(response.statusText, response.status, {
code: 'internal',
message: response.statusText
})
}
throw error
}
}
export function connect(config: Config): Connection {
return new Connection(config)
}
function parseArrayRow<T>(fields: Field[], rawRow: QueryResultRow, cast: Cast): T {
const row = decodeRow(rawRow)
return fields.map((field, ix) => {
return cast(field, row[ix])
}) as T
}
function parseObjectRow<T>(fields: Field[], rawRow: QueryResultRow, cast: Cast): T {
const row = decodeRow(rawRow)
return fields.reduce(
(acc, field, ix) => {
acc[field.name] = cast(field, row[ix])
return acc
},
{} as Record<string, ReturnType<Cast>>
) as T
}
function parse<T>(result: QueryResult, cast: Cast, returnAs: ExecuteAs): T[] {
const fields = result.fields ?? []
const rows = result.rows ?? []
return rows.map((row) =>
returnAs === 'array' ? parseArrayRow<T>(fields, row, cast) : parseObjectRow<T>(fields, row, cast)
)
}
function decodeRow(row: QueryResultRow): Array<string | null> {
const values = row.values ? atob(row.values) : ''
let offset = 0
return row.lengths.map((size) => {
const width = parseInt(size, 10)
// Negative length indicates a null value.
if (width < 0) return null
const splice = values.substring(offset, offset + width)
offset += width
return splice
})
}