-
Notifications
You must be signed in to change notification settings - Fork 30
/
index.ts
183 lines (162 loc) · 4.51 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
import {
BaseConnector,
ConnectionError,
CompiledQuery,
ResolvedParam,
QueryError,
} from '@latitude-data/base-connector'
import { readFileSync } from 'fs'
import { Pool, PoolConfig, Types, createPool } from 'mysql'
import QueryResult, { DataType, Field } from '@latitude-data/query_result'
export type SSLConfig = {
ca?: string
key?: string
cert?: string
rejectUnauthorized?: boolean
}
type SSLOptions = boolean | 'Amazon RDS' | SSLConfig
export type ConnectionParams = {
host: string
user: string
password: string
database: string
ssl?: SSLOptions
}
export default class MysqlConnector extends BaseConnector {
private pool: Pool
constructor(rootPath: string, connectionParams: ConnectionParams) {
super(rootPath)
this.pool = createPool({
connectionLimit: 10,
...this.buildConnectionParams(connectionParams),
})
}
async end(): Promise<void> {
this.pool.end()
}
resolve(value: unknown, _: number): ResolvedParam {
return {
value,
resolvedAs: '?',
}
}
runQuery(query: CompiledQuery): Promise<QueryResult> {
return new Promise((resolve, reject) => {
if (!this.pool) {
reject(new ConnectionError('Connection not established'))
return
}
this.pool.getConnection((err, connection) => {
if (err) {
return reject(new ConnectionError(err.message))
}
connection.query(
query.sql,
this.buildQueryParams(query.resolvedParams),
(error, results, fields) => {
connection.release()
if (error) {
return reject(new QueryError(error.message))
}
resolve(
new QueryResult({
rowCount: results.length,
fields: (fields ?? [])?.map(
(field) =>
({
name: field.name,
type: this.convertDataType(field.type),
}) as Field,
),
rows: results.map((row: Record<string, unknown>) =>
row ? Object.values(row) : [],
),
}),
)
},
)
})
})
}
private buildConnectionParams(params: ConnectionParams) {
const payload = {
host: params.host,
user: params.user,
password: params.password,
database: params.database,
ssl:
params.ssl !== undefined ? this.buildSSLConfig(params.ssl) : undefined,
} as Partial<PoolConfig>
return this.compact(payload)
}
private buildSSLConfig(ssl: SSLOptions) {
if (ssl === 'Amazon RDS') return 'Amazon RDS'
if (typeof ssl === 'boolean') {
if (ssl) return {}
else return undefined
}
const { ca, key, cert, rejectUnauthorized } = ssl
const payload = {
rejectUnauthorized,
ca: ca ? this.readSecureFile(ca) : undefined,
key: key ? this.readSecureFile(key) : undefined,
cert: cert ? this.readSecureFile(cert) : undefined,
}
return this.compact(payload)
}
private readSecureFile(filePath: string) {
try {
return readFileSync(filePath).toString()
} catch (error) {
throw new Error(
`Failed to read file at ${filePath}: ${(error as Error).message}`,
)
}
}
private compact(obj: Record<string, unknown>) {
return Object.fromEntries(
Object.entries(obj).filter(([, value]) => value !== undefined),
)
}
private buildQueryParams(params: ResolvedParam[]) {
return params.map((param) => param.value)
}
private convertDataType(dataTypeID: Types, fallbackType = DataType.Unknown) {
switch (dataTypeID) {
case Types.VARCHAR:
case Types.VAR_STRING:
case Types.STRING:
return DataType.String
case Types.TINY:
case Types.SHORT:
case Types.LONG:
case Types.INT24:
return DataType.Integer
case Types.DECIMAL:
case Types.FLOAT:
case Types.DOUBLE:
case Types.NEWDECIMAL:
return DataType.Float
case Types.TIME:
case Types.TIME2:
case Types.TIMESTAMP2:
case Types.DATETIME:
case Types.DATETIME2:
case Types.YEAR:
case Types.NEWDATE:
case Types.TIMESTAMP:
return DataType.Datetime
case Types.BLOB:
case Types.TINY_BLOB:
case Types.MEDIUM_BLOB:
case Types.LONG_BLOB:
case Types.ENUM:
case Types.JSON:
case Types.SET:
case Types.NULL:
case Types.GEOMETRY:
case Types.BIT:
return fallbackType
}
}
}