-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
281 lines (238 loc) · 6.57 KB
/
index.js
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
// AWS Aurora MySQL Data API Client
// -------
const { ExecuteStatementCommand, RDSDataClient } = require('@aws-sdk/client-rds-data');
const { NodeHttpHandler } = require('@smithy/node-http-handler');
const map = require('lodash.map');
const Client_MySQL = require('knex/lib/dialects/mysql'); // eslint-disable-line camelcase
const Transaction = require('./transaction');
function getAuroraDataValue (value) {
if ('blobValue' in value) {
return Buffer.from(value.blobValue, 'base64');
} else if ('doubleValue' in value) {
return value.doubleValue;
} else if ('isNull' in value) {
return null;
} else if ('longValue' in value) {
return value.longValue;
} else if ('stringValue' in value) {
return value.stringValue;
} else /* istanbul ignore else */ if ('booleanValue' in value) {
return value.booleanValue;
} else {
const type = Object.keys(value)[0];
throw new Error(`Unknown value type '${type}' from row`);
}
}
function hydrateRecord (record, fields) {
return record.reduce((row, value, index) => {
const field = fields[index];
value = getAuroraDataValue(value);
if (value !== null) {
switch (field.typeName) {
case 'DECIMAL':
value = Number(value);
break;
case 'DATE':
case 'DATETIME':
case 'TIMESTAMP':
case 'YEAR':
value = new Date(value + 'Z');
break;
default:
break;
}
}
row[field.label] = value;
return row;
}, {});
}
class Client_AuroraDataMySQL extends Client_MySQL { // eslint-disable-line camelcase
transaction () {
return new Transaction(this, ...arguments);
}
_driver () {
let RDSDataService;
try {
RDSDataService = RDSDataClient;
} catch (err) { /* istanbul ignore next */
throw new Error(`Failed to load aws-sdk rdsdataservice client, did you forget to install it as a dependency? (${err.message})`);
}
const isHttp = this.config.connection.sdkConfig && String(this.config.connection.sdkConfig.endpoint).startsWith('http:');
const https = isHttp
? require('http')
: require('https');
const agent = new https.Agent({
keepAlive: true
});
const requestHandler = new NodeHttpHandler({
[isHttp ? 'httpAgent' : 'httpsAgent']: agent
});
const config = {
requestHandler,
...(this.config.connection.sdkConfig || {})
};
return new RDSDataService(config);
}
initializePool () {
/* istanbul ignore if */
if (this.pool) {
this.logger.warn('The pool has already been initialized');
return;
}
this.knexUid = 0;
// common parameters for Data API requests
const parameters = {
database: this.config.connection.database,
resourceArn: this.config.connection.resourceArn,
secretArn: this.config.connection.secretArn
};
this.pool = {
acquire: () => ({
promise: Promise.resolve({
client: this.driver,
parameters,
transactions: {},
__knexUid: this.knexUid++
})
}),
release: () => true,
destroy: () => true
};
}
prepBindings (bindings) {
return bindings.map((value, index) => {
const name = index.toString();
switch (typeof value) {
case 'boolean':
return {
name,
value: {
booleanValue: value
}
};
case 'number':
if (Number.isInteger(value)) {
return {
name,
value: {
longValue: value
}
};
} else {
return {
name,
typeHint: 'DECIMAL',
value: {
stringValue: value.toString()
}
};
}
case 'string':
return {
name,
value: {
stringValue: value
}
};
case 'object':
break;
default:
throw new Error(
`Unknown binding value type '${typeof value}' for value at index ${index}`
);
}
if (value === null) {
return {
name,
value: {
isNull: true
}
};
}
if (Buffer.isBuffer(value) || ArrayBuffer.isView(value)) {
return {
name,
value: {
blobValue: value.toString('base64')
}
};
}
if (value instanceof Date) {
return {
name,
typeHint: 'TIMESTAMP',
value: {
stringValue: value.toISOString().replace('T', ' ').replace('Z', '')
}
};
}
throw new Error(
`Unknown binding value object of class '${value.constructor.name}' for value at index ${index}`
);
});
}
positionBindings (sql) {
let questionCount = 0;
return sql.replace(/\?/g, function () {
return `:${questionCount++}`;
});
}
_stream (connection, obj, stream, options) {
throw new Error(
'Streams are not supported by the aurora-data-mysql dialect'
);
}
async _query (connection, obj) {
const params = {
...connection.parameters,
includeResultMetadata: true,
sql: obj.sql,
parameters: obj.bindings
};
if ('__knexTxId' in connection) {
params.transactionId = connection.transactions[connection.__knexTxId];
}
const command = new ExecuteStatementCommand(params);
obj.data = await connection.client.send(command);
return obj;
}
processResponse (resp, runner) {
const { method, data } = resp;
const {
columnMetadata: fields,
generatedFields,
numberOfRecordsUpdated,
records
} = data;
const rows = records
? records.map((record) => hydrateRecord(record, fields))
: [];
if (resp.output) {
return resp.output.call(runner, rows, fields);
}
switch (method) {
case 'select':
case 'pluck':
case 'first': {
if (method === 'pluck') {
return map(rows, resp.pluck);
}
return method === 'first' ? rows[0] : rows;
}
case 'insert':
if (generatedFields.length > 0) {
return [getAuroraDataValue(generatedFields[0])];
} else {
return [undefined];
}
case 'del':
case 'update':
case 'counter':
return numberOfRecordsUpdated;
default:
return { rows, fields };
}
}
}
Client_AuroraDataMySQL.prototype.driverName = 'aurora-data-mysql';
module.exports = Client_AuroraDataMySQL; // eslint-disable-line camelcase