data-api-client 2.0.0-beta.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,344 @@
1
+ 'use strict';
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createPgClient = createPgClient;
7
+ exports.createPgPool = createPgPool;
8
+ const events_1 = require("events");
9
+ const pg_escape_1 = __importDefault(require("pg-escape"));
10
+ const client_1 = require("../client");
11
+ const errors_1 = require("./errors");
12
+ function convertPgPlaceholders(sql, params = []) {
13
+ const namedParams = {};
14
+ const convertedSql = sql.replace(/\$(\d+)/g, (match, index) => {
15
+ const paramIndex = parseInt(index, 10) - 1;
16
+ if (paramIndex >= 0 && paramIndex < params.length) {
17
+ const key = `p${index}`;
18
+ namedParams[key] = params[paramIndex];
19
+ return `:${key}`;
20
+ }
21
+ return match;
22
+ });
23
+ return { sql: convertedSql, params: namedParams };
24
+ }
25
+ function inferCommand(sql) {
26
+ var _a;
27
+ const match = (_a = sql.trim().split(/\s+/)[0]) === null || _a === void 0 ? void 0 : _a.toUpperCase();
28
+ const knownCommands = ['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'CREATE', 'DROP', 'ALTER', 'TRUNCATE', 'GRANT', 'REVOKE'];
29
+ return knownCommands.includes(match) ? match : 'QUERY';
30
+ }
31
+ function convertToPgResult(result, sql, rowMode) {
32
+ if (result.records && Array.isArray(result.records)) {
33
+ let rows = result.records;
34
+ const fields = rows.length > 0 && typeof rows[0] === 'object' && rows[0] !== null
35
+ ? Object.keys(rows[0]).map((name) => ({ name }))
36
+ : [];
37
+ if (rowMode === 'array' && rows.length > 0 && typeof rows[0] === 'object') {
38
+ rows = rows.map((row) => Object.values(row));
39
+ }
40
+ return {
41
+ rows,
42
+ rowCount: rows.length,
43
+ command: inferCommand(sql),
44
+ fields,
45
+ oid: 0
46
+ };
47
+ }
48
+ else if (result.numberOfRecordsUpdated !== undefined) {
49
+ return {
50
+ rows: [],
51
+ rowCount: result.numberOfRecordsUpdated,
52
+ command: inferCommand(sql),
53
+ fields: [],
54
+ oid: 0
55
+ };
56
+ }
57
+ else if (result.insertId !== undefined) {
58
+ return {
59
+ rows: [],
60
+ rowCount: 1,
61
+ command: 'INSERT',
62
+ fields: [],
63
+ oid: 0
64
+ };
65
+ }
66
+ else {
67
+ return {
68
+ rows: [],
69
+ rowCount: 0,
70
+ command: inferCommand(sql),
71
+ fields: [],
72
+ oid: 0
73
+ };
74
+ }
75
+ }
76
+ function createPgClient(config) {
77
+ const pgConfig = {
78
+ ...config,
79
+ engine: 'pg',
80
+ hydrateColumnNames: true
81
+ };
82
+ const core = (0, client_1.init)(pgConfig);
83
+ const eventEmitter = new events_1.EventEmitter();
84
+ let transactionId;
85
+ async function executeQuery(sqlOrConfig, params) {
86
+ let sql;
87
+ let values = [];
88
+ let rowMode;
89
+ if (typeof sqlOrConfig === 'string') {
90
+ sql = sqlOrConfig;
91
+ values = params || [];
92
+ }
93
+ else {
94
+ sql = sqlOrConfig.text;
95
+ values = params !== undefined ? params : (sqlOrConfig.values || []);
96
+ rowMode = sqlOrConfig.rowMode;
97
+ }
98
+ const upperSql = sql.trim().toUpperCase();
99
+ if (upperSql === 'BEGIN' || upperSql.startsWith('BEGIN ')) {
100
+ const txResult = await core.beginTransaction();
101
+ transactionId = txResult.transactionId;
102
+ return {
103
+ rows: [],
104
+ rowCount: 0,
105
+ command: 'BEGIN',
106
+ fields: []
107
+ };
108
+ }
109
+ if (upperSql === 'COMMIT') {
110
+ if (transactionId) {
111
+ await core.commitTransaction({ transactionId });
112
+ transactionId = undefined;
113
+ }
114
+ return {
115
+ rows: [],
116
+ rowCount: 0,
117
+ command: 'COMMIT',
118
+ fields: []
119
+ };
120
+ }
121
+ if (upperSql === 'ROLLBACK') {
122
+ if (transactionId) {
123
+ await core.rollbackTransaction({ transactionId });
124
+ transactionId = undefined;
125
+ }
126
+ return {
127
+ rows: [],
128
+ rowCount: 0,
129
+ command: 'ROLLBACK',
130
+ fields: []
131
+ };
132
+ }
133
+ const { sql: convertedSql, params: namedParams } = convertPgPlaceholders(sql, values);
134
+ const queryOptions = {
135
+ sql: convertedSql,
136
+ parameters: namedParams
137
+ };
138
+ if (transactionId) {
139
+ queryOptions.transactionId = transactionId;
140
+ }
141
+ const result = await core.query(queryOptions);
142
+ return convertToPgResult(result, sql, rowMode);
143
+ }
144
+ const client = Object.assign(eventEmitter, {
145
+ connect(callback) {
146
+ if (callback) {
147
+ process.nextTick(() => callback(null));
148
+ return;
149
+ }
150
+ return Promise.resolve();
151
+ },
152
+ end(callback) {
153
+ if (callback) {
154
+ process.nextTick(() => callback());
155
+ return;
156
+ }
157
+ return Promise.resolve();
158
+ },
159
+ copyFrom(_queryText) {
160
+ throw new Error('COPY FROM is not supported by RDS Data API');
161
+ },
162
+ copyTo(_queryText) {
163
+ throw new Error('COPY TO is not supported by RDS Data API');
164
+ },
165
+ pauseDrain() {
166
+ },
167
+ resumeDrain() {
168
+ },
169
+ escapeIdentifier(str) {
170
+ return pg_escape_1.default.ident(str);
171
+ },
172
+ escapeLiteral(str) {
173
+ return pg_escape_1.default.literal(str);
174
+ },
175
+ setTypeParser(_oid, _format, _parseFn) {
176
+ },
177
+ getTypeParser(_oid, _format) {
178
+ return (text) => text;
179
+ },
180
+ release(_err) {
181
+ },
182
+ query(sqlOrConfig, paramsOrCallback, callback) {
183
+ if (typeof sqlOrConfig === 'object' && 'submit' in sqlOrConfig) {
184
+ throw new Error('Query streams are not supported by RDS Data API');
185
+ }
186
+ let params = [];
187
+ let cb;
188
+ if (typeof sqlOrConfig === 'object' && 'text' in sqlOrConfig) {
189
+ if (typeof paramsOrCallback === 'function') {
190
+ cb = paramsOrCallback;
191
+ }
192
+ else if (Array.isArray(paramsOrCallback)) {
193
+ params = paramsOrCallback;
194
+ cb = callback;
195
+ }
196
+ }
197
+ else {
198
+ if (typeof paramsOrCallback === 'function') {
199
+ cb = paramsOrCallback;
200
+ }
201
+ else if (Array.isArray(paramsOrCallback)) {
202
+ params = paramsOrCallback;
203
+ cb = callback;
204
+ }
205
+ }
206
+ if (cb) {
207
+ executeQuery(sqlOrConfig, params)
208
+ .then((result) => cb(null, result))
209
+ .catch((err) => {
210
+ const pgError = (0, errors_1.mapToPostgresError)(err);
211
+ client.emit('error', pgError);
212
+ cb(pgError, null);
213
+ });
214
+ return;
215
+ }
216
+ return executeQuery(sqlOrConfig, params).catch((err) => {
217
+ const pgError = (0, errors_1.mapToPostgresError)(err);
218
+ client.emit('error', pgError);
219
+ throw pgError;
220
+ });
221
+ }
222
+ });
223
+ return client;
224
+ }
225
+ function createPgPool(config) {
226
+ const pgConfig = {
227
+ ...config,
228
+ engine: 'pg',
229
+ hydrateColumnNames: true
230
+ };
231
+ const core = (0, client_1.init)(pgConfig);
232
+ const eventEmitter = new events_1.EventEmitter();
233
+ async function executePoolQuery(sqlOrConfig, params) {
234
+ let sql;
235
+ let values = [];
236
+ let rowMode;
237
+ if (typeof sqlOrConfig === 'string') {
238
+ sql = sqlOrConfig;
239
+ values = params || [];
240
+ }
241
+ else {
242
+ sql = sqlOrConfig.text;
243
+ values = params !== undefined ? params : (sqlOrConfig.values || []);
244
+ rowMode = sqlOrConfig.rowMode;
245
+ }
246
+ const { sql: convertedSql, params: namedParams } = convertPgPlaceholders(sql, values);
247
+ const result = await core.query({
248
+ sql: convertedSql,
249
+ parameters: namedParams
250
+ });
251
+ return convertToPgResult(result, sql, rowMode);
252
+ }
253
+ const pool = Object.assign(eventEmitter, {
254
+ get totalCount() {
255
+ return 0;
256
+ },
257
+ get idleCount() {
258
+ return 0;
259
+ },
260
+ get waitingCount() {
261
+ return 0;
262
+ },
263
+ get expiredCount() {
264
+ return 0;
265
+ },
266
+ get ending() {
267
+ return false;
268
+ },
269
+ get ended() {
270
+ return false;
271
+ },
272
+ options: {},
273
+ connect(callback) {
274
+ const getClient = () => {
275
+ const client = createPgClient(config);
276
+ client.release = () => {
277
+ pool.emit('remove', client);
278
+ };
279
+ pool.emit('acquire', client);
280
+ pool.emit('connect', client);
281
+ return client;
282
+ };
283
+ if (callback) {
284
+ try {
285
+ const client = getClient();
286
+ process.nextTick(() => callback(null, client));
287
+ }
288
+ catch (err) {
289
+ process.nextTick(() => callback(err));
290
+ }
291
+ return;
292
+ }
293
+ return Promise.resolve(getClient());
294
+ },
295
+ end(callback) {
296
+ if (callback) {
297
+ process.nextTick(() => callback());
298
+ return;
299
+ }
300
+ return Promise.resolve();
301
+ },
302
+ query(sqlOrConfig, paramsOrCallback, callback) {
303
+ if (typeof sqlOrConfig === 'object' && 'submit' in sqlOrConfig) {
304
+ throw new Error('Query streams are not supported by RDS Data API');
305
+ }
306
+ let params = [];
307
+ let cb;
308
+ if (typeof sqlOrConfig === 'object' && 'text' in sqlOrConfig) {
309
+ if (typeof paramsOrCallback === 'function') {
310
+ cb = paramsOrCallback;
311
+ }
312
+ else if (Array.isArray(paramsOrCallback)) {
313
+ params = paramsOrCallback;
314
+ cb = callback;
315
+ }
316
+ }
317
+ else {
318
+ if (typeof paramsOrCallback === 'function') {
319
+ cb = paramsOrCallback;
320
+ }
321
+ else if (Array.isArray(paramsOrCallback)) {
322
+ params = paramsOrCallback;
323
+ cb = callback;
324
+ }
325
+ }
326
+ if (cb) {
327
+ executePoolQuery(sqlOrConfig, params)
328
+ .then((result) => cb(null, result))
329
+ .catch((err) => {
330
+ const pgError = (0, errors_1.mapToPostgresError)(err);
331
+ pool.emit('error', pgError);
332
+ cb(pgError, null);
333
+ });
334
+ return;
335
+ }
336
+ return executePoolQuery(sqlOrConfig, params).catch((err) => {
337
+ const pgError = (0, errors_1.mapToPostgresError)(err);
338
+ pool.emit('error', pgError);
339
+ throw pgError;
340
+ });
341
+ }
342
+ });
343
+ return pool;
344
+ }
@@ -0,0 +1,3 @@
1
+ import { init } from './client';
2
+ export = init;
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,IAAI,EAAE,MAAM,UAAU,CAAA;AAC/B,SAAS,IAAI,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ 'use strict';
2
+ const client_1 = require("./client");
3
+ module.exports = client_1.init;
@@ -0,0 +1,19 @@
1
+ import type { InternalConfig, Parameters, ParameterValue, NamedParameter, FormattedParameter, SqlParamInfo, FormatOptions, SupportedType } from './types';
2
+ export declare const parseParams: (args: any[]) => Parameters[];
3
+ export declare const parseDatabase: (config: InternalConfig, args: any[]) => string | undefined;
4
+ export declare const parseHydrate: (config: InternalConfig, args: any[]) => boolean;
5
+ export declare const parseFormatOptions: (config: InternalConfig, args: any[]) => Required<FormatOptions>;
6
+ export declare const prepareParams: ({ secretArn, resourceArn }: InternalConfig, args: any[]) => {
7
+ secretArn: string;
8
+ resourceArn: string;
9
+ [key: string]: any;
10
+ };
11
+ export declare const normalizeParams: (params: Parameters[]) => (NamedParameter | NamedParameter[])[];
12
+ export declare const processParams: (engine: string, sql: string, sqlParams: Record<string, SqlParamInfo>, params: (NamedParameter | NamedParameter[])[], formatOptions: Required<FormatOptions>, row?: number) => {
13
+ processedParams: (FormattedParameter | FormattedParameter[])[];
14
+ escapedSql: string;
15
+ };
16
+ export declare const formatParam: (n: string, v: ParameterValue, formatOptions: Required<FormatOptions>, engine?: string) => FormattedParameter;
17
+ export declare const splitParams: (p: Record<string, ParameterValue>) => NamedParameter[];
18
+ export declare const formatType: (name: string, value: ParameterValue, type: SupportedType | null | undefined, typeHint: string | undefined, formatOptions: Required<FormatOptions>) => FormattedParameter;
19
+ //# sourceMappingURL=params.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"params.d.ts","sourceRoot":"","sources":["../src/params.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EACV,cAAc,EACd,UAAU,EACV,cAAc,EACd,cAAc,EACd,kBAAkB,EAClB,YAAY,EACZ,aAAa,EACb,aAAa,EACd,MAAM,SAAS,CAAA;AAIhB,eAAO,MAAM,WAAW,GAAI,MAAM,GAAG,EAAE,KAAG,UAAU,EAa5C,CAAA;AAGR,eAAO,MAAM,aAAa,GAAI,QAAQ,cAAc,EAAE,MAAM,GAAG,EAAE,KAAG,MAAM,GAAG,SAS9D,CAAA;AAGf,eAAO,MAAM,YAAY,GAAI,QAAQ,cAAc,EAAE,MAAM,GAAG,EAAE,KAAG,OAKpC,CAAA;AAG/B,eAAO,MAAM,kBAAkB,GAAI,QAAQ,cAAc,EAAE,MAAM,GAAG,EAAE,KAAG,QAAQ,CAAC,aAAa,CAkBrE,CAAA;AAG1B,eAAO,MAAM,aAAa,GACxB,4BAA4B,cAAc,EAC1C,MAAM,GAAG,EAAE,KACV;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;CAK9D,CAAA;AAOD,eAAO,MAAM,eAAe,GAAI,QAAQ,UAAU,EAAE,KAAG,CAAC,cAAc,GAAG,cAAc,EAAE,CAAC,EAavF,CAAA;AAGH,eAAO,MAAM,aAAa,GACxB,QAAQ,MAAM,EACd,KAAK,MAAM,EACX,WAAW,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,EACvC,QAAQ,CAAC,cAAc,GAAG,cAAc,EAAE,CAAC,EAAE,EAC7C,eAAe,QAAQ,CAAC,aAAa,CAAC,EACtC,MAAK,MAAU,KACd;IAAE,eAAe,EAAE,CAAC,kBAAkB,GAAG,kBAAkB,EAAE,CAAC,EAAE,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAgCtF,CAAA;AAGD,eAAO,MAAM,WAAW,GAAI,GAAG,MAAM,EAAE,GAAG,cAAc,EAAE,eAAe,QAAQ,CAAC,aAAa,CAAC,EAAE,SAAS,MAAM,KAAG,kBAC/C,CAAA;AAGrE,eAAO,MAAM,WAAW,GAAI,GAAG,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,KAAG,cAAc,EACiB,CAAA;AAG/F,eAAO,MAAM,UAAU,GACrB,MAAM,MAAM,EACZ,OAAO,cAAc,EACrB,MAAM,aAAa,GAAG,IAAI,GAAG,SAAS,EACtC,UAAU,MAAM,GAAG,SAAS,EAC5B,eAAe,QAAQ,CAAC,aAAa,CAAC,KACrC,kBAgBF,CAAA"}
package/dist/params.js ADDED
@@ -0,0 +1,125 @@
1
+ 'use strict';
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.formatType = exports.splitParams = exports.formatParam = exports.processParams = exports.normalizeParams = exports.prepareParams = exports.parseFormatOptions = exports.parseHydrate = exports.parseDatabase = exports.parseParams = void 0;
7
+ const sqlstring_1 = __importDefault(require("sqlstring"));
8
+ const pg_escape_1 = __importDefault(require("pg-escape"));
9
+ const utils_1 = require("./utils");
10
+ const parseParams = (args) => Array.isArray(args[0].parameters)
11
+ ? args[0].parameters
12
+ : typeof args[0].parameters === 'object'
13
+ ? [args[0].parameters]
14
+ : Array.isArray(args[1])
15
+ ? args[1]
16
+ : typeof args[1] === 'object'
17
+ ? [args[1]]
18
+ : args[0].parameters
19
+ ? (0, utils_1.error)(`'parameters' must be an object or array`)
20
+ : args[1]
21
+ ? (0, utils_1.error)('Parameters must be an object or array')
22
+ : [];
23
+ exports.parseParams = parseParams;
24
+ const parseDatabase = (config, args) => config.transactionId
25
+ ? config.database
26
+ : typeof args[0].database === 'string'
27
+ ? args[0].database
28
+ : args[0].database
29
+ ? (0, utils_1.error)(`'database' must be a string.`)
30
+ : config.database
31
+ ? config.database
32
+ : undefined;
33
+ exports.parseDatabase = parseDatabase;
34
+ const parseHydrate = (config, args) => typeof args[0].hydrateColumnNames === 'boolean'
35
+ ? args[0].hydrateColumnNames
36
+ : args[0].hydrateColumnNames
37
+ ? (0, utils_1.error)(`'hydrateColumnNames' must be a boolean.`)
38
+ : config.hydrateColumnNames;
39
+ exports.parseHydrate = parseHydrate;
40
+ const parseFormatOptions = (config, args) => typeof args[0].formatOptions === 'object'
41
+ ? {
42
+ deserializeDate: typeof args[0].formatOptions.deserializeDate === 'boolean'
43
+ ? args[0].formatOptions.deserializeDate
44
+ : args[0].formatOptions.deserializeDate
45
+ ? (0, utils_1.error)(`'formatOptions.deserializeDate' must be a boolean.`)
46
+ : config.formatOptions.deserializeDate,
47
+ treatAsLocalDate: typeof args[0].formatOptions.treatAsLocalDate == 'boolean'
48
+ ? args[0].formatOptions.treatAsLocalDate
49
+ : args[0].formatOptions.treatAsLocalDate
50
+ ? (0, utils_1.error)(`'formatOptions.treatAsLocalDate' must be a boolean.`)
51
+ : config.formatOptions.treatAsLocalDate
52
+ }
53
+ : args[0].formatOptions
54
+ ? (0, utils_1.error)(`'formatOptions' must be an object.`)
55
+ : config.formatOptions;
56
+ exports.parseFormatOptions = parseFormatOptions;
57
+ const prepareParams = ({ secretArn, resourceArn }, args) => {
58
+ return Object.assign({ secretArn, resourceArn }, typeof args[0] === 'object' ? omit(args[0], ['hydrateColumnNames', 'parameters']) : {});
59
+ };
60
+ exports.prepareParams = prepareParams;
61
+ const omit = (obj, values) => Object.keys(obj).reduce((acc, x) => (values.includes(x) ? acc : Object.assign(acc, { [x]: obj[x] })), {});
62
+ const normalizeParams = (params) => params.reduce((acc, p) => Array.isArray(p)
63
+ ? acc.concat([(0, exports.normalizeParams)(p)])
64
+ : (Object.keys(p).length === 2 && 'name' in p && typeof p.value !== 'undefined') ||
65
+ (Object.keys(p).length === 3 &&
66
+ 'name' in p &&
67
+ typeof p.value !== 'undefined' &&
68
+ 'cast' in p)
69
+ ? acc.concat(p)
70
+ : acc.concat(...(0, exports.splitParams)(p)), []);
71
+ exports.normalizeParams = normalizeParams;
72
+ const processParams = (engine, sql, sqlParams, params, formatOptions, row = 0) => {
73
+ return {
74
+ processedParams: params.reduce((acc, p) => {
75
+ if (Array.isArray(p)) {
76
+ const result = (0, exports.processParams)(engine, sql, sqlParams, p, formatOptions, row);
77
+ if (row === 0) {
78
+ sql = result.escapedSql;
79
+ row++;
80
+ }
81
+ return acc.concat([result.processedParams]);
82
+ }
83
+ else if (sqlParams[p.name]) {
84
+ if (sqlParams[p.name].type === 'n_ph') {
85
+ if (p.cast) {
86
+ const regex = new RegExp(':' + p.name + '\\b', 'g');
87
+ sql = sql.replace(regex, engine === 'pg' ? `:${p.name}::${p.cast}` : `CAST(:${p.name} AS ${p.cast})`);
88
+ }
89
+ acc.push((0, exports.formatParam)(p.name, p.value, formatOptions, engine));
90
+ }
91
+ else if (row === 0) {
92
+ const regex = new RegExp('::' + p.name + '\\b', 'g');
93
+ const escapedId = engine === 'pg'
94
+ ? pg_escape_1.default.ident(p.value)
95
+ : sqlstring_1.default.escapeId(p.value);
96
+ sql = sql.replace(regex, escapedId);
97
+ }
98
+ return acc;
99
+ }
100
+ else {
101
+ return acc;
102
+ }
103
+ }, []),
104
+ escapedSql: sql
105
+ };
106
+ };
107
+ exports.processParams = processParams;
108
+ const formatParam = (n, v, formatOptions, engine) => (0, exports.formatType)(n, v, (0, utils_1.getType)(v), (0, utils_1.getTypeHint)(v, engine), formatOptions);
109
+ exports.formatParam = formatParam;
110
+ const splitParams = (p) => Object.keys(p).reduce((arr, x) => arr.concat({ name: x, value: p[x] }), []);
111
+ exports.splitParams = splitParams;
112
+ const formatType = (name, value, type, typeHint, formatOptions) => {
113
+ return Object.assign(typeHint != null ? { name, typeHint } : { name }, type === null
114
+ ? { value }
115
+ : {
116
+ value: {
117
+ [type ? type : (0, utils_1.error)(`'${name}' is an invalid type`)]: type === 'isNull'
118
+ ? true
119
+ : (0, utils_1.isDate)(value)
120
+ ? (0, utils_1.formatToTimeStamp)(value, formatOptions && formatOptions.treatAsLocalDate)
121
+ : value
122
+ }
123
+ });
124
+ };
125
+ exports.formatType = formatType;
@@ -0,0 +1,5 @@
1
+ import type { InternalConfig, QueryResult } from './types';
2
+ export declare const query: (this: {
3
+ rollback?: (err: Error, status: any) => void;
4
+ } | undefined, config: InternalConfig, ..._args: any[]) => Promise<QueryResult>;
5
+ //# sourceMappingURL=query.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query.d.ts","sourceRoot":"","sources":["../src/query.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,SAAS,CAAA;AAe1D,eAAO,MAAM,KAAK,GAChB,MAAM;IAAE,QAAQ,CAAC,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,KAAK,IAAI,CAAA;CAAE,GAAG,SAAS,EAClE,QAAQ,cAAc,EACtB,GAAG,OAAO,GAAG,EAAE,KACd,OAAO,CAAC,WAAW,CAoErB,CAAA"}
package/dist/query.js ADDED
@@ -0,0 +1,39 @@
1
+ 'use strict';
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.query = void 0;
4
+ const client_rds_data_1 = require("@aws-sdk/client-rds-data");
5
+ const utils_1 = require("./utils");
6
+ const params_1 = require("./params");
7
+ const results_1 = require("./results");
8
+ const retry_1 = require("./retry");
9
+ const query = async function (config, ..._args) {
10
+ const args = Array.isArray(_args[0]) ? (0, utils_1.flatten)(_args) : _args;
11
+ const sql = (0, utils_1.parseSQL)(args);
12
+ const sqlParams = (0, utils_1.getSqlParams)(sql);
13
+ const hydrateColumnNames = (0, params_1.parseHydrate)(config, args);
14
+ const formatOptions = (0, params_1.parseFormatOptions)(config, args);
15
+ const parameters = (0, params_1.normalizeParams)((0, params_1.parseParams)(args));
16
+ const { processedParams, escapedSql } = (0, params_1.processParams)(config.engine, sql, sqlParams, parameters, formatOptions);
17
+ const isBatch = processedParams.length > 0 && Array.isArray(processedParams[0]);
18
+ const params = Object.assign((0, params_1.prepareParams)(config, args), {
19
+ database: (0, params_1.parseDatabase)(config, args),
20
+ sql: escapedSql
21
+ }, processedParams.length > 0
22
+ ?
23
+ { [isBatch ? 'parameterSets' : 'parameters']: processedParams }
24
+ : {}, hydrateColumnNames && !isBatch ? { includeResultMetadata: true } : {}, config.transactionId ? { transactionId: config.transactionId } : {});
25
+ try {
26
+ const result = await (0, retry_1.withRetry)(() => isBatch
27
+ ? config.RDS.send(new client_rds_data_1.BatchExecuteStatementCommand(params))
28
+ : config.RDS.send(new client_rds_data_1.ExecuteStatementCommand(params)), config.retryOptions);
29
+ return (0, results_1.formatResults)(result, hydrateColumnNames, args[0].includeResultMetadata === true, formatOptions);
30
+ }
31
+ catch (e) {
32
+ if (this && this.rollback) {
33
+ const rollback = await config.RDS.send(new client_rds_data_1.RollbackTransactionCommand((0, utils_1.pick)(params, ['resourceArn', 'secretArn', 'transactionId'])));
34
+ this.rollback(e, rollback);
35
+ }
36
+ throw e;
37
+ }
38
+ };
39
+ exports.query = query;
@@ -0,0 +1,12 @@
1
+ import type { ExecuteStatementCommandOutput, BatchExecuteStatementCommandOutput, Field } from '@aws-sdk/client-rds-data';
2
+ import type { QueryResult, UpdateResult, FormatOptions } from './types';
3
+ export declare const formatResults: (result: ExecuteStatementCommandOutput | BatchExecuteStatementCommandOutput, hydrate: boolean, includeMeta: boolean, formatOptions: Required<FormatOptions>) => QueryResult;
4
+ export declare const formatRecords: (recs: Field[][] | undefined, columns: {
5
+ label?: string;
6
+ typeName?: string;
7
+ }[] | undefined, hydrate: boolean, formatOptions: Required<FormatOptions>) => any[];
8
+ export declare const formatRecordValue: (value: any, typeName: string | undefined, formatOptions: Required<FormatOptions>) => any;
9
+ export declare const formatUpdateResults: (res: {
10
+ generatedFields?: Field[];
11
+ }[]) => UpdateResult[];
12
+ //# sourceMappingURL=results.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"results.d.ts","sourceRoot":"","sources":["../src/results.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,6BAA6B,EAAE,kCAAkC,EAAE,KAAK,EAAE,MAAM,0BAA0B,CAAA;AACxH,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAIvE,eAAO,MAAM,aAAa,GACxB,QAAQ,6BAA6B,GAAG,kCAAkC,EAC1E,SAAS,OAAO,EAChB,aAAa,OAAO,EACpB,eAAe,QAAQ,CAAC,aAAa,CAAC,KACrC,WAuBF,CAAA;AAID,eAAO,MAAM,aAAa,GACxB,MAAM,KAAK,EAAE,EAAE,GAAG,SAAS,EAC3B,SAAS;IAAE,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAE,EAAE,GAAG,SAAS,EAC5D,SAAS,OAAO,EAChB,eAAe,QAAQ,CAAC,aAAa,CAAC,KACrC,GAAG,EAsDL,CAAA;AAsBD,eAAO,MAAM,iBAAiB,GAC5B,OAAO,GAAG,EACV,UAAU,MAAM,GAAG,SAAS,EAC5B,eAAe,QAAQ,CAAC,aAAa,CAAC,KACrC,GAmCF,CAAA;AAGD,eAAO,MAAM,mBAAmB,GAAI,KAAK;IAAE,eAAe,CAAC,EAAE,KAAK,EAAE,CAAA;CAAE,EAAE,KAAG,YAAY,EAGnF,CAAA"}
@@ -0,0 +1,93 @@
1
+ 'use strict';
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.formatUpdateResults = exports.formatRecordValue = exports.formatRecords = exports.formatResults = void 0;
4
+ const utils_1 = require("./utils");
5
+ const formatResults = (result, hydrate, includeMeta, formatOptions) => {
6
+ const { columnMetadata, numberOfRecordsUpdated, records, generatedFields, updateResults } = result;
7
+ return Object.assign(includeMeta ? { columnMetadata } : {}, numberOfRecordsUpdated !== undefined && !records ? { numberOfRecordsUpdated } : {}, records
8
+ ? {
9
+ records: (0, exports.formatRecords)(records, columnMetadata, hydrate, formatOptions)
10
+ }
11
+ : {}, updateResults ? { updateResults: (0, exports.formatUpdateResults)(updateResults) } : {}, generatedFields && generatedFields.length > 0 ? { insertId: generatedFields[0].longValue } : {});
12
+ };
13
+ exports.formatResults = formatResults;
14
+ const formatRecords = (recs, columns, hydrate, formatOptions) => {
15
+ const fmap = recs && recs[0]
16
+ ? recs[0].map((_field, i) => {
17
+ return Object.assign({}, columns ? { label: columns[i].label, typeName: columns[i].typeName } : {});
18
+ })
19
+ : [];
20
+ return recs
21
+ ? recs.map((rec) => {
22
+ return rec.reduce((acc, field, i) => {
23
+ if (field.isNull === true) {
24
+ return hydrate
25
+ ? Object.assign(acc, { [fmap[i].label]: null })
26
+ : acc.concat(null);
27
+ }
28
+ else if (fmap[i] && fmap[i].field) {
29
+ const value = (0, exports.formatRecordValue)(field[fmap[i].field], fmap[i].typeName, formatOptions);
30
+ return hydrate
31
+ ? Object.assign(acc, { [fmap[i].label]: value })
32
+ : acc.concat(value);
33
+ }
34
+ else {
35
+ Object.keys(field).map((type) => {
36
+ if (type !== 'isNull' && field[type] !== null) {
37
+ fmap[i]['field'] = type;
38
+ }
39
+ });
40
+ const value = (0, exports.formatRecordValue)(field[fmap[i].field], fmap[i].typeName, formatOptions);
41
+ return hydrate
42
+ ? Object.assign(acc, { [fmap[i].label]: value })
43
+ : acc.concat(value);
44
+ }
45
+ }, hydrate ? {} : []);
46
+ })
47
+ : [];
48
+ };
49
+ exports.formatRecords = formatRecords;
50
+ const flattenArrayValue = (arrayValue) => {
51
+ if (!arrayValue)
52
+ return [];
53
+ if (arrayValue.stringValues)
54
+ return arrayValue.stringValues.slice();
55
+ if (arrayValue.longValues)
56
+ return arrayValue.longValues.slice();
57
+ if (arrayValue.doubleValues)
58
+ return arrayValue.doubleValues.slice();
59
+ if (arrayValue.booleanValues)
60
+ return arrayValue.booleanValues.slice();
61
+ if (arrayValue.arrayValues) {
62
+ return arrayValue.arrayValues.map((nested) => flattenArrayValue(nested.arrayValue || nested));
63
+ }
64
+ return [];
65
+ };
66
+ const formatRecordValue = (value, typeName, formatOptions) => {
67
+ if (value instanceof Uint8Array) {
68
+ return Buffer.from(value);
69
+ }
70
+ if (value && typeof value === 'object' && typeName && typeName.startsWith('_')) {
71
+ return flattenArrayValue(value);
72
+ }
73
+ if (formatOptions &&
74
+ formatOptions.deserializeDate &&
75
+ typeName &&
76
+ ['DATE', 'DATETIME', 'TIMESTAMP', 'TIMESTAMPTZ', 'TIMESTAMP WITH TIME ZONE'].includes(typeName.toUpperCase())) {
77
+ return (0, utils_1.formatFromTimeStamp)(value, (formatOptions && formatOptions.treatAsLocalDate) || typeName === 'TIMESTAMP WITH TIME ZONE');
78
+ }
79
+ else if (typeName === 'JSON') {
80
+ return JSON.parse(value);
81
+ }
82
+ else if (typeName === 'YEAR') {
83
+ return typeof value === 'string' ? parseInt(value, 10) : value;
84
+ }
85
+ else {
86
+ return value;
87
+ }
88
+ };
89
+ exports.formatRecordValue = formatRecordValue;
90
+ const formatUpdateResults = (res) => res.map((x) => {
91
+ return x.generatedFields && x.generatedFields.length > 0 ? { insertId: x.generatedFields[0].longValue } : {};
92
+ });
93
+ exports.formatUpdateResults = formatUpdateResults;