-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathindex.ts
More file actions
211 lines (179 loc) · 5.95 KB
/
index.ts
File metadata and controls
211 lines (179 loc) · 5.95 KB
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
import { format } from './format.js'
import { cast } from './decode.js'
import { DatabaseError } from './error.js'
import { Config, ExecuteOptions, ExecuteArgs, TxOptions, Decoders, ColumnType } from './config.js'
import { postQuery } from './serverless.js'
export { Config, ExecuteOptions, ExecuteArgs, DatabaseError, Decoders, ColumnType }
// serverless driver returns a full result by default
export type Row = Record<string, any> | any[]
export type Types = Record<string, string>
export interface FullResult {
types: Types | null
rows: Row[] | null
statement: string
rowCount: number | null
rowsAffected: number | null
lastInsertId: string | null
}
// serverless backend results
type Session = string | null
export interface Field {
name: string
type: string
nullable: boolean
}
interface QueryExecuteResponse {
session: Session
types: Field[] | null
rows: string[][] | null
rowsAffected: number | null
sLastInsertID: string | null
}
const defaultExecuteOptions: ExecuteOptions = {}
export class Tx<T extends Config> {
private conn: Connection<T>
constructor(conn: Connection<T>) {
this.conn = conn
}
async execute<E extends ExecuteOptions>(
query: string,
args: ExecuteArgs = null,
options: E = defaultExecuteOptions as E
): Promise<ExecuteResult<E, T>> {
return this.conn.execute(query, args, options)
}
async commit(): Promise<T['fullResult'] extends true ? FullResult : Row[]> {
return this.conn.execute('COMMIT')
}
async rollback(): Promise<T['fullResult'] extends true ? FullResult : Row[]> {
return this.conn.execute('ROLLBACK')
}
}
export type ExecuteResult<E extends ExecuteOptions, T extends Config> = E extends { fullResult: boolean }
? E['fullResult'] extends true
? FullResult
: Row[]
: T['fullResult'] extends true
? FullResult
: Row[]
export class Connection<T extends Config> {
private config: T
private session: Session
constructor(config: T) {
this.session = null
this.config = { ...config }
if (typeof fetch !== 'undefined') {
this.config.fetch ||= fetch
}
if (config.url) {
const url = new URL(config.url)
if (!this.config.username) {
this.config.username = decodeURIComponent(url.username)
}
if (!this.config.password) {
this.config.password = decodeURIComponent(url.password)
}
if (!this.config.host) {
this.config.host = url.hostname
}
if (!this.config.database) {
this.config.database = decodeURIComponent(url.pathname.slice(1))
}
}
}
getConfig(): Config {
return this.config
}
async begin(txOptions: TxOptions = {}) {
const conn = new Connection<T>(this.config)
const tx = new Tx<T>(conn)
await conn.execute('BEGIN', undefined, undefined, txOptions)
return tx
}
async persist() {
const conn = new Connection<T>(this.config)
await conn.execute('', null, defaultExecuteOptions as ExecuteOptions, {}, 'open')
const stateful = new StatefulConnection<T>(conn)
return stateful
}
async execute<E extends ExecuteOptions>(
query: string,
args: ExecuteArgs = null,
options: E = defaultExecuteOptions as E,
txOptions: TxOptions = {},
statefulAction?: 'open' | 'close'
): Promise<ExecuteResult<E, T>> {
const sql = args ? format(query, args) : query
const body = JSON.stringify({ query: sql })
const debug = options.debug ?? this.config.debug ?? false
if (debug) {
console.log(`[serverless-js debug] sql: ${sql}`)
}
const resp = await postQuery<QueryExecuteResponse>(
this.config,
body,
this.session ?? '',
sql == 'BEGIN' ? txOptions.isolation : null,
debug,
statefulAction
)
this.session = resp?.session ?? null
if (this.session === null || this.session === '') {
throw new DatabaseError('empty session, please try again', 500, null)
}
const arrayMode = options.arrayMode ?? this.config.arrayMode ?? false
const fullResult = options.fullResult ?? this.config.fullResult ?? false
const decoders = { ...this.config.decoders, ...options.decoders }
const fields = resp?.types ?? []
const rows = resp ? parse(fields, resp?.rows ?? [], cast, arrayMode, decoders) : []
if (fullResult) {
const rowsAffected = resp?.rowsAffected ?? null
const lastInsertId = resp?.sLastInsertID ?? null
const typeByName = (acc, { name, type }) => ({ ...acc, [name]: type })
const types = fields.reduce<Types>(typeByName, {})
return {
statement: sql,
types,
rows,
rowsAffected,
lastInsertId,
rowCount: rows.length
} as ExecuteResult<E, T>
}
return rows as ExecuteResult<E, T>
}
}
export class StatefulConnection<T extends Config> {
private conn: Connection<T>
constructor(conn: Connection<T>) {
this.conn = conn
}
async execute<E extends ExecuteOptions>(
query: string,
args: ExecuteArgs = null,
options: E = defaultExecuteOptions as E
): Promise<ExecuteResult<E, T>> {
return this.conn.execute(query, args, options)
}
async close(): Promise<void> {
await this.conn.execute('', null, defaultExecuteOptions as ExecuteOptions, {}, 'close')
}
}
export function connect<T extends Config>(config: T): Connection<T> {
return new Connection<T>(config)
}
type Cast = typeof cast
function parseArrayRow(fields: Field[], rawRow: string[], cast: Cast, decoders: Decoders): Row {
return fields.map((field, ix) => {
return cast(field, rawRow[ix], decoders)
})
}
function parseObjectRow(fields: Field[], rawRow: string[], cast: Cast, decoders: Decoders): Row {
return fields.reduce((acc, field, ix) => {
acc[field.name] = cast(field, rawRow[ix], decoders)
return acc
}, {} as Row)
}
function parse(fields: Field[], rows: string[][], cast: Cast, arrayMode: boolean, decode: Decoders): Row[] {
return rows.map((row) => (arrayMode === true ? parseArrayRow(fields, row, cast, decode) : parseObjectRow(fields, row, cast, decode)))
}