@technicity/data-service-generator 0.11.6 → 0.11.7-next.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.
@@ -1,453 +0,0 @@
1
- "use strict";
2
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
- if (kind === "m") throw new TypeError("Private method is not writable");
4
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
- };
8
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
- };
13
- var _RuntimeKSQL_ksql, _RuntimeKSQL_middlewareHandler, _RuntimeKSQL_dbCall, _RuntimeKSQL_formatQuery, _RuntimeKSQL_getBaseTableName, _RuntimeKSQL_getMaterializedViewName, _RuntimeKSQL_doNotUseMaterializedViews;
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.RuntimeKSQL = void 0;
16
- const SqlString = require("sqlstring");
17
- const async_hooks_1 = require("async_hooks");
18
- const _ = require("lodash");
19
- const graphql_relay_1 = require("graphql-relay");
20
- const shared_1 = require("./lib/shared");
21
- const ksql_1 = require("../ksql");
22
- const SDKNotFoundError_1 = require("./lib/SDKNotFoundError");
23
- const stringifyWhere_1 = require("./lib/stringifyWhere");
24
- const cursor_1 = require("./lib/cursor");
25
- const escapeId = SqlString.escapeId.bind(SqlString);
26
- class RuntimeKSQL {
27
- constructor(clientOpts, otherOpts, artifacts) {
28
- _RuntimeKSQL_ksql.set(this, void 0);
29
- _RuntimeKSQL_middlewareHandler.set(this, void 0);
30
- _RuntimeKSQL_dbCall.set(this, void 0);
31
- _RuntimeKSQL_formatQuery.set(this, void 0);
32
- _RuntimeKSQL_getBaseTableName.set(this, void 0);
33
- _RuntimeKSQL_getMaterializedViewName.set(this, void 0);
34
- _RuntimeKSQL_doNotUseMaterializedViews.set(this, void 0);
35
- __classPrivateFieldSet(this, _RuntimeKSQL_ksql, new ksql_1.KSQL(clientOpts ?? {}), "f");
36
- __classPrivateFieldSet(this, _RuntimeKSQL_middlewareHandler, new shared_1.MiddlewareHandler(), "f");
37
- __classPrivateFieldSet(this, _RuntimeKSQL_dbCall, typeof otherOpts._dbCall === "function"
38
- ? (q) => otherOpts._dbCall(q).then(mapResult)
39
- : (q) => __classPrivateFieldGet(this, _RuntimeKSQL_ksql, "f").streamQuery(q).then(mapResult), "f");
40
- __classPrivateFieldSet(this, _RuntimeKSQL_getBaseTableName, otherOpts.getBaseTableName, "f");
41
- __classPrivateFieldSet(this, _RuntimeKSQL_getMaterializedViewName, otherOpts.getMaterializedViewName, "f");
42
- __classPrivateFieldSet(this, _RuntimeKSQL_doNotUseMaterializedViews, otherOpts.doNotUseMaterializedViews ?? false, "f");
43
- __classPrivateFieldSet(this, _RuntimeKSQL_formatQuery, SqlString.format.bind(SqlString), "f");
44
- }
45
- async resolve(input) {
46
- return resolve(input, __classPrivateFieldGet(this, _RuntimeKSQL_dbCall, "f").bind(this), __classPrivateFieldGet(this, _RuntimeKSQL_formatQuery, "f").bind(this), __classPrivateFieldGet(this, _RuntimeKSQL_middlewareHandler, "f"), __classPrivateFieldGet(this, _RuntimeKSQL_getBaseTableName, "f"), __classPrivateFieldGet(this, _RuntimeKSQL_getMaterializedViewName, "f"), __classPrivateFieldGet(this, _RuntimeKSQL_doNotUseMaterializedViews, "f"));
47
- }
48
- async $queryRaw(sql, values) {
49
- return __classPrivateFieldGet(this, _RuntimeKSQL_dbCall, "f").call(this, SqlString.format(sql, values ?? []));
50
- }
51
- async $use(middleware) {
52
- __classPrivateFieldGet(this, _RuntimeKSQL_middlewareHandler, "f").register(middleware);
53
- }
54
- $whereNeedsProcessing(where) {
55
- return (0, shared_1.whereNeedsProcessing)(where);
56
- }
57
- async $prepareWhere(artifacts, table, data) {
58
- return (0, shared_1._prepareWhere)(artifacts, table, data, __classPrivateFieldGet(this, _RuntimeKSQL_dbCall, "f").bind(this), __classPrivateFieldGet(this, _RuntimeKSQL_formatQuery, "f").bind(this));
59
- }
60
- async $shutdown() {
61
- // Nothing to do here, I think
62
- }
63
- async $startTransaction(input) {
64
- throw new Error("Not implemented.");
65
- return {
66
- dbCall: async (q) => "",
67
- commit: async () => { },
68
- rollback: async () => { }
69
- };
70
- }
71
- }
72
- exports.RuntimeKSQL = RuntimeKSQL;
73
- _RuntimeKSQL_ksql = new WeakMap(), _RuntimeKSQL_middlewareHandler = new WeakMap(), _RuntimeKSQL_dbCall = new WeakMap(), _RuntimeKSQL_formatQuery = new WeakMap(), _RuntimeKSQL_getBaseTableName = new WeakMap(), _RuntimeKSQL_getMaterializedViewName = new WeakMap(), _RuntimeKSQL_doNotUseMaterializedViews = new WeakMap();
74
- async function resolve(input, dbCall, formatQuery, middlewareHandler, getBaseTableName, getMaterializedViewName, doNotUseMaterializedViews) {
75
- // https://github.com/prisma/prisma/blob/822198e5ba21535364d20c86901b8c3778ebf6a3/packages/client/src/runtime/getPrismaClient.ts#L1087
76
- let index = -1;
77
- if (middlewareHandler.length() > 0) {
78
- const resource = new async_hooks_1.AsyncResource("sdk-request");
79
- const params = input;
80
- const consumer = (paramsMaybeMutated) => {
81
- const nextMiddleware = middlewareHandler.get(++index);
82
- if (nextMiddleware != null) {
83
- return nextMiddleware(paramsMaybeMutated, consumer);
84
- }
85
- const paramsChanged = { ...input, ...params };
86
- return _resolve(paramsChanged, dbCall, formatQuery, getBaseTableName, getMaterializedViewName, doNotUseMaterializedViews);
87
- };
88
- return resource.runInAsyncScope(() => consumer(params));
89
- }
90
- return _resolve(input, dbCall, formatQuery, getBaseTableName, getMaterializedViewName, doNotUseMaterializedViews);
91
- }
92
- function _resolve(input, dbCall, formatQuery, getBaseTableName, getMaterializedViewName, doNotUseMaterializedViews) {
93
- if (input.action === "findUnique") {
94
- return getData(input, dbCall, formatQuery, getBaseTableName, getMaterializedViewName, doNotUseMaterializedViews);
95
- }
96
- if (input.action === "findMany") {
97
- return getData(input, dbCall, formatQuery, getBaseTableName, getMaterializedViewName, doNotUseMaterializedViews);
98
- }
99
- if (input.action === "findManyPaginated") {
100
- return getData(input, dbCall, formatQuery, getBaseTableName, getMaterializedViewName, doNotUseMaterializedViews);
101
- }
102
- if (input.action === "create") {
103
- throw new Error("Not implemented.");
104
- }
105
- if (input.action === "update") {
106
- throw new Error("Not implemented.");
107
- }
108
- if (input.action === "updateMany") {
109
- throw new Error("Not implemented.");
110
- }
111
- if (input.action === "delete") {
112
- throw new Error("Not implemented.");
113
- }
114
- if (input.action === "deleteMany") {
115
- throw new Error("Not implemented.");
116
- }
117
- throw new Error("Invalid action: " + input.action);
118
- }
119
- async function getData(input, dbCall, formatQuery, getBaseTableName, getMaterializedViewName, doNotUseMaterializedViews) {
120
- const { action } = input;
121
- const grabMany = action === "findMany" ||
122
- action === "findManyPaginated" ||
123
- action === "updateMany" ||
124
- action === "deleteMany";
125
- const data = await _getData(input, grabMany, dbCall, formatQuery, getBaseTableName, getMaterializedViewName, doNotUseMaterializedViews);
126
- if (data == null && !grabMany) {
127
- throw new SDKNotFoundError_1.SDKNotFoundError();
128
- }
129
- const scalarFields = input.artifacts[input.resource].scalarFields;
130
- if (action === "findManyPaginated" && data?.results != null) {
131
- (0, shared_1.postProcess)(data.results, input.fields ?? scalarFields, true);
132
- }
133
- else {
134
- (0, shared_1.postProcess)(data, input.fields ?? scalarFields, true);
135
- }
136
- return data;
137
- }
138
- async function _getData(input, grabMany, dbCall, formatQuery, getBaseTableName, getMaterializedViewName, doNotUseMaterializedViews) {
139
- const { resource: table, artifacts, args, action } = input;
140
- const tableArtifacts = artifacts[table];
141
- const isInputFieldAnArray = Array.isArray(input.fields);
142
- let fields = input.fields;
143
- if (!Array.isArray(fields)) {
144
- fields = tableArtifacts.scalarFields;
145
- }
146
- let useMaterializedView = !doNotUseMaterializedViews &&
147
- // If fields isn't an array, we're only getting scalar fields,
148
- // so no point using the materialized view.
149
- isInputFieldAnArray &&
150
- // We're getting relation fields
151
- fields.some((x) => typeof x === "object") &&
152
- Object.values(tableArtifacts.relationFields).filter((x) => x.type === "one-to-many__many-to-one" && x.kind === "many-to-one").length > 0 &&
153
- !Object.values(tableArtifacts.relationFields).some((x) => x.type === "one-to-many__many-to-one" &&
154
- x.kind === "many-to-one" &&
155
- x.nullable === true);
156
- const getTableName = useMaterializedView
157
- ? getMaterializedViewName
158
- : getBaseTableName;
159
- let where = undefined;
160
- if (args?.$where != null) {
161
- let argsMapped = args;
162
- if (typeof argsMapped.$where === "object" && argsMapped.$where[table] != null) {
163
- argsMapped = _.cloneDeep(argsMapped);
164
- argsMapped.$where = argsMapped.$where[table];
165
- }
166
- const whereResult = (0, stringifyWhere_1.stringifyWhere)({
167
- where: argsMapped.$where,
168
- table: escapeId(getTableName(table)),
169
- dialect: "mysql",
170
- args: argsMapped
171
- });
172
- if (whereResult) {
173
- where = whereResult;
174
- }
175
- }
176
- let columns = [];
177
- let mappedFields = [];
178
- let relationFields = [];
179
- for (let x of fields) {
180
- if (typeof x === "string") {
181
- const mappedField = tableArtifacts.mappedFields?.[x];
182
- if (mappedField != null) {
183
- mappedFields.push(x);
184
- if (!columns.includes(mappedField.foreignKey)) {
185
- columns.push(mappedField.foreignKey);
186
- }
187
- }
188
- else {
189
- columns.push(x);
190
- }
191
- }
192
- else {
193
- const relationField = tableArtifacts.relationFields?.[x.name];
194
- if (relationField == null) {
195
- throw new Error(`Invalid relation field: ${x.name}`);
196
- }
197
- if (relationField.type === "one-to-many__many-to-one") {
198
- relationFields.push(x);
199
- if (!columns.includes(relationField.relation.foreignKey)) {
200
- columns.push(relationField.relation.foreignKey);
201
- }
202
- }
203
- else if (relationField.type === "many-to-many") {
204
- relationFields.push(x);
205
- if (!columns.includes(relationField.relations[0].referencedKey)) {
206
- columns.push(relationField.relations[0].referencedKey);
207
- }
208
- }
209
- }
210
- }
211
- if (action === "findManyPaginated") {
212
- // For cursor
213
- if (!columns.includes(tableArtifacts.primaryKey)) {
214
- columns.push(tableArtifacts.primaryKey);
215
- }
216
- }
217
- if (useMaterializedView) {
218
- relationFields = relationFields.filter((x) => {
219
- if (typeof x === "string") {
220
- return true;
221
- }
222
- const relationField = tableArtifacts.relationFields?.[x.name];
223
- if (relationField == null) {
224
- throw new Error(`Invalid relation field: ${x.name}`);
225
- }
226
- // Since we're going to use the materialized view,
227
- // filter out non-nullable many-to-one relations.
228
- return !(relationField.type === "one-to-many__many-to-one" &&
229
- relationField.kind === "many-to-one" &&
230
- relationField.nullable === false);
231
- });
232
- }
233
- let s = useMaterializedView
234
- ? formatQuery(`SELECT * FROM ??`, [getTableName(table)])
235
- : formatQuery(`SELECT ?? FROM ??`, [columns, getTableName(table)]);
236
- if (where) {
237
- s += ` WHERE ${where}`;
238
- }
239
- s += ";";
240
- return dbCall(s).then((_result) => {
241
- let result = grabMany ? _result : _result[0];
242
- if (result == null) {
243
- return null;
244
- }
245
- if (grabMany && Array.isArray(result)) {
246
- // Important: ordering must be before pagination, since pagination is done in code
247
- let orderBy;
248
- if (args == null || args.$orderBy == null) {
249
- orderBy = [{ column: tableArtifacts.primaryKey, direction: "asc" }];
250
- }
251
- else if (Array.isArray(args.$orderBy)) {
252
- orderBy = args.$orderBy.map((x) => {
253
- const [column, direction] = Object.entries(x)[0];
254
- return { column, direction };
255
- });
256
- }
257
- else {
258
- const [column, direction] = Object.entries(args.$orderBy)[0];
259
- orderBy = [{ column, direction }];
260
- }
261
- for (let x of orderBy) {
262
- if (!["asc", "desc"].includes(x.direction)) {
263
- throw new Error(`Expected \`asc\` or \`desc\` for \`direction\` but got: ${x.direction}`);
264
- }
265
- }
266
- result = _.orderBy(result, orderBy.map((x) => x.column), orderBy.map((x) => x.direction));
267
- if (action === "findManyPaginated") {
268
- result = paginate(result, args, tableArtifacts.primaryKey, action);
269
- return Promise.all(result.results.map((x) => resolveDependentFields(table, x, mappedFields, relationFields, artifacts, dbCall, formatQuery, getBaseTableName, getMaterializedViewName, doNotUseMaterializedViews).then((xx) => mergeSubResults(x, xx)))).then((xx) => {
270
- result.results = xx;
271
- return result;
272
- });
273
- }
274
- const limit = args?.$limit;
275
- if (typeof limit === "number") {
276
- result = result.slice(0, limit);
277
- }
278
- return Promise.all(result.map((x) => resolveDependentFields(table, x, mappedFields, relationFields, artifacts, dbCall, formatQuery, getBaseTableName, getMaterializedViewName, doNotUseMaterializedViews).then((xx) => mergeSubResults(x, xx))));
279
- }
280
- return resolveDependentFields(table, result, mappedFields, relationFields, artifacts, dbCall, formatQuery, getBaseTableName, getMaterializedViewName, doNotUseMaterializedViews).then((xx) => mergeSubResults(result, xx));
281
- });
282
- }
283
- async function resolveDependentFields(table, parentData, mappedFields, relationFields, artifacts, dbCall, formatQuery, getBaseTableName, getMaterializedViewName, doNotUseMaterializedViews) {
284
- const tableArtifacts = artifacts[table];
285
- return Promise.all([]
286
- .concat(mappedFields.map((x) => {
287
- const mappedField = tableArtifacts.mappedFields?.[x];
288
- if (mappedField == null) {
289
- throw new Error(`Invalid mappedField: ${x}`);
290
- }
291
- if (parentData?.[mappedField.foreignKey] == null) {
292
- return { [x]: null };
293
- }
294
- const s = formatQuery(`SELECT ?? FROM ?? WHERE ?? = ?;`, [
295
- mappedField.name,
296
- getBaseTableName(mappedField.referencedTable),
297
- mappedField.referencedKey,
298
- parentData?.[mappedField.foreignKey]
299
- ]);
300
- return dbCall(s).then((xs) => ({
301
- [x]: xs?.[0]?.[mappedField.name] ?? null
302
- }));
303
- }))
304
- .concat(relationFields.map((x) => {
305
- if (typeof x === "string") {
306
- throw new Error(`Invalid field: ${x}`);
307
- }
308
- const relationField = tableArtifacts.relationFields?.[x.name];
309
- if (relationField == null) {
310
- throw new Error("Invalid field: " + table + "." + x.name);
311
- }
312
- if (relationField.type === "many-to-many") {
313
- const junctionReferencedKey = relationField.relations[0].referencedKey;
314
- const junctionKeyValue = parentData?.[junctionReferencedKey];
315
- if (junctionKeyValue == null) {
316
- return { [x.as ?? x.name]: [] };
317
- }
318
- let whereJunction = typeof x?.args?.$where === "object" &&
319
- x.args.$where != null &&
320
- x.args.$where[relationField.junctionTable] != null
321
- ? _.cloneDeep(x.args.$where[relationField.junctionTable])
322
- : {};
323
- whereJunction = {
324
- $and: [
325
- { [relationField.relations[0].foreignKey]: junctionKeyValue },
326
- whereJunction
327
- ]
328
- };
329
- const key = relationField.relations[1].foreignKey;
330
- const s = formatQuery(`SELECT ?? FROM ?? WHERE ${(0, stringifyWhere_1.stringifyWhere)({
331
- where: whereJunction,
332
- table: escapeId(getBaseTableName(relationField.junctionTable)),
333
- dialect: "mysql",
334
- // Since we're paginating, empty is fine
335
- args: {}
336
- })};`, [key, getBaseTableName(relationField.junctionTable)]);
337
- return dbCall(s)
338
- .then((xs) => xs.map((x) => x?.[key]))
339
- .then((keys) => {
340
- const whereDest = {
341
- [relationField.relations[1].referencedKey]: { $in: keys }
342
- };
343
- const argsMapped = x.args == null ? {} : _.cloneDeep(x.args);
344
- if (typeof argsMapped?.$where === "object" &&
345
- argsMapped.$where != null &&
346
- argsMapped.$where[relationField.table] != null) {
347
- argsMapped.$where = {
348
- $and: [whereDest, argsMapped.$where[relationField.table]]
349
- };
350
- }
351
- else if (argsMapped.$where != null) {
352
- argsMapped.$where = { $and: [whereDest, argsMapped.$where] };
353
- }
354
- else {
355
- argsMapped.$where = whereDest;
356
- }
357
- return _getData({
358
- resource: relationField.table,
359
- args: argsMapped,
360
- fields: x.fields,
361
- artifacts,
362
- action: relationField.grabMany ? "findMany" : "findUnique"
363
- }, relationField.grabMany, dbCall, formatQuery, getBaseTableName, getMaterializedViewName, doNotUseMaterializedViews).then((xx) => ({ [x.as ?? x.name]: xx }));
364
- });
365
- }
366
- if (relationField.type === "one-to-many__many-to-one") {
367
- const referencedKey = relationField.relation.referencedKey;
368
- const foreignKeyValue = parentData?.[relationField.relation.foreignKey];
369
- if (foreignKeyValue == null) {
370
- return { [x.as ?? x.name]: relationField.grabMany ? [] : null };
371
- }
372
- const whereRef = { [referencedKey]: foreignKeyValue };
373
- const argsMapped = x.args == null ? {} : _.cloneDeep(x.args);
374
- if (argsMapped.$where == null) {
375
- argsMapped.$where = whereRef;
376
- }
377
- else {
378
- argsMapped.$where = { $and: [whereRef, argsMapped.$where] };
379
- }
380
- return _getData({
381
- resource: relationField.table,
382
- args: argsMapped,
383
- fields: x.fields,
384
- artifacts,
385
- action: relationField.grabMany ? "findMany" : "findUnique"
386
- }, relationField.grabMany, dbCall, formatQuery, getBaseTableName, getMaterializedViewName, doNotUseMaterializedViews).then((xx) => ({ [x.as ?? x.name]: xx }));
387
- }
388
- throw new Error(`Invalid relationField.type`);
389
- })));
390
- }
391
- function mergeSubResults(result, subResults) {
392
- for (let x of subResults) {
393
- result = { ...result, ...x };
394
- }
395
- return result;
396
- }
397
- function paginate(data, args, primaryKey, action) {
398
- if (action === "findManyPaginated") {
399
- if (typeof args?.$paginate?.limit === "number") {
400
- const totalCount = data.length;
401
- const limit = args.$paginate.limit;
402
- const offset = args.$paginate.offset ?? 0;
403
- data = data.slice(offset, offset + limit);
404
- return {
405
- results: data,
406
- paginationInfo: { totalCount }
407
- };
408
- }
409
- if (typeof args?.$paginate?.first === "number" ||
410
- typeof args?.$paginate?.last === "number") {
411
- const totalCount = data.length;
412
- let argsMapped = args;
413
- // Convert cursor(s) for graphql-relay
414
- for (let k of ["after", "before"]) {
415
- if (args?.$paginate?.[k] != null) {
416
- argsMapped = _.cloneDeep(argsMapped);
417
- const offset = data.findIndex((x) => x[primaryKey] === (0, cursor_1.decodeCursor)(args.$paginate[k]));
418
- if (offset === -1) {
419
- throw new Error(`Invalid cursor: ${args.$paginate[k]}`);
420
- }
421
- argsMapped.$paginate[k] = (0, graphql_relay_1.offsetToCursor)(offset);
422
- }
423
- }
424
- const connection = (0, graphql_relay_1.connectionFromArray)(data, argsMapped.$paginate);
425
- const results = connection.edges.map((x) => x.node);
426
- // Convert cursors back
427
- const startKey = results[0]?.[primaryKey];
428
- const endKey = results[results.length - 1]?.[primaryKey];
429
- const startCursor = startKey == null ? null : (0, cursor_1.encodeCursor)(startKey);
430
- const endCursor = endKey == null ? null : (0, cursor_1.encodeCursor)(endKey);
431
- return {
432
- results,
433
- paginationInfo: {
434
- ...connection.pageInfo,
435
- startCursor,
436
- endCursor,
437
- totalCount
438
- }
439
- };
440
- }
441
- }
442
- throw new Error(`Invalid pagination action: ${action}`);
443
- }
444
- function mapResult(data) {
445
- return data.map((x) => {
446
- for (let k of Object.keys(x)) {
447
- if (typeof x[k] === "string" && (k === "uuid" || k.endsWith("Uuid"))) {
448
- x[k] = x[k].toLocaleLowerCase();
449
- }
450
- }
451
- return x;
452
- });
453
- }
@@ -1,25 +0,0 @@
1
- import * as mssql from "mssql";
2
- import type { IRuntime, TMiddleware, TResolveParams, IArtifacts, ISupplementClientOpts } from "./IRuntime";
3
- import { typeCastMSSQL } from "./lib/typeCastMSSQL";
4
- export declare class RuntimeMSSQL implements IRuntime {
5
- #private;
6
- constructor(clientOpts: mssql.config, otherOpts: {
7
- supplementClientOpts?: ISupplementClientOpts;
8
- typeCast?: Parameters<typeof typeCastMSSQL>[0];
9
- }, artifacts: IArtifacts);
10
- resolve(input: TResolveParams): Promise<any>;
11
- $queryRaw(sql: string, values?: any[]): Promise<any>;
12
- $use(middleware: TMiddleware): Promise<void>;
13
- $whereNeedsProcessing(where: any): boolean;
14
- $prepareWhere(artifacts: IArtifacts, table: string, data: any): Promise<{}>;
15
- $shutdown(): Promise<void>;
16
- $startTransaction(input?: {
17
- isolationLevel?: "READ UNCOMMITTED" | "READ COMMITTED" | "REPEATABLE READ" | "SERIALIZABLE";
18
- }): Promise<{
19
- commit: () => Promise<void>;
20
- rollback: () => Promise<void>;
21
- dbCall: (q: string) => Promise<any>;
22
- }>;
23
- private dbCall;
24
- private formatQuery;
25
- }
@@ -1,58 +0,0 @@
1
- "use strict";
2
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
- if (kind === "m") throw new TypeError("Private method is not writable");
4
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
- };
8
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
- };
13
- var _RuntimeMSSQL_dialect, _RuntimeMSSQL_mssqlClient, _RuntimeMSSQL_middlewareHandler;
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.RuntimeMSSQL = void 0;
16
- const shared_1 = require("./lib/shared");
17
- const MSSQL_1 = require("./lib/MSSQL");
18
- const typeCastMSSQL_1 = require("./lib/typeCastMSSQL");
19
- class RuntimeMSSQL {
20
- constructor(clientOpts, otherOpts, artifacts) {
21
- _RuntimeMSSQL_dialect.set(this, "mssql");
22
- _RuntimeMSSQL_mssqlClient.set(this, void 0);
23
- _RuntimeMSSQL_middlewareHandler.set(this, void 0);
24
- __classPrivateFieldSet(this, _RuntimeMSSQL_mssqlClient, new MSSQL_1.MSSQL(clientOpts, otherOpts?.supplementClientOpts
25
- ? (0, typeCastMSSQL_1.typeCastMSSQL)(otherOpts?.typeCast)
26
- : undefined), "f");
27
- __classPrivateFieldSet(this, _RuntimeMSSQL_middlewareHandler, new shared_1.MiddlewareHandler(), "f");
28
- }
29
- async resolve(input) {
30
- return (0, shared_1.resolve)(input, input.dbCall ?? this.dbCall.bind(this), this.formatQuery.bind(this), this.$startTransaction.bind(this), __classPrivateFieldGet(this, _RuntimeMSSQL_dialect, "f"), __classPrivateFieldGet(this, _RuntimeMSSQL_middlewareHandler, "f"), input.context ?? {});
31
- }
32
- async $queryRaw(sql, values) {
33
- return this.dbCall(this.formatQuery(sql, values ?? []));
34
- }
35
- async $use(middleware) {
36
- __classPrivateFieldGet(this, _RuntimeMSSQL_middlewareHandler, "f").register(middleware);
37
- }
38
- $whereNeedsProcessing(where) {
39
- return (0, shared_1.whereNeedsProcessing)(where);
40
- }
41
- async $prepareWhere(artifacts, table, data) {
42
- return (0, shared_1._prepareWhere)(artifacts, table, data, this.dbCall.bind(this), this.formatQuery.bind(this));
43
- }
44
- async $shutdown() {
45
- await __classPrivateFieldGet(this, _RuntimeMSSQL_mssqlClient, "f").closePool();
46
- }
47
- async $startTransaction(input) {
48
- return __classPrivateFieldGet(this, _RuntimeMSSQL_mssqlClient, "f").beginTransaction(input?.isolationLevel);
49
- }
50
- async dbCall(q) {
51
- return __classPrivateFieldGet(this, _RuntimeMSSQL_mssqlClient, "f").dbCall(q);
52
- }
53
- formatQuery(q, values) {
54
- return __classPrivateFieldGet(this, _RuntimeMSSQL_mssqlClient, "f").formatQuery(q, values);
55
- }
56
- }
57
- exports.RuntimeMSSQL = RuntimeMSSQL;
58
- _RuntimeMSSQL_dialect = new WeakMap(), _RuntimeMSSQL_mssqlClient = new WeakMap(), _RuntimeMSSQL_middlewareHandler = new WeakMap();
@@ -1,14 +0,0 @@
1
- import * as mssql from "mssql";
2
- export declare class MSSQL {
3
- #private;
4
- constructor(clientOpts: mssql.config, typeCast?: Function);
5
- dbCall(q: string): Promise<any>;
6
- private mapResult;
7
- formatQuery(q: string, values: any[]): any;
8
- beginTransaction(isolationLevel?: "READ UNCOMMITTED" | "READ COMMITTED" | "REPEATABLE READ" | "SERIALIZABLE"): Promise<{
9
- commit: () => Promise<void>;
10
- rollback: () => Promise<void>;
11
- dbCall: (q: string) => Promise<any>;
12
- }>;
13
- closePool(): Promise<void>;
14
- }
@@ -1,78 +0,0 @@
1
- "use strict";
2
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
- if (kind === "m") throw new TypeError("Private method is not writable");
4
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
- };
8
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
- };
13
- var _MSSQL_pool, _MSSQL_poolConnect, _MSSQL_typeCast;
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.MSSQL = void 0;
16
- const mssql = require("mssql");
17
- // @ts-ignore
18
- const TSqlString = require("tsqlstring");
19
- class MSSQL {
20
- constructor(clientOpts, typeCast) {
21
- _MSSQL_pool.set(this, void 0);
22
- _MSSQL_poolConnect.set(this, void 0);
23
- _MSSQL_typeCast.set(this, void 0);
24
- __classPrivateFieldSet(this, _MSSQL_typeCast, typeCast, "f");
25
- __classPrivateFieldSet(this, _MSSQL_pool, new mssql.ConnectionPool(clientOpts), "f");
26
- __classPrivateFieldSet(this, _MSSQL_poolConnect, __classPrivateFieldGet(this, _MSSQL_pool, "f").connect(), "f");
27
- }
28
- async dbCall(q) {
29
- await __classPrivateFieldGet(this, _MSSQL_poolConnect, "f");
30
- const request = __classPrivateFieldGet(this, _MSSQL_pool, "f").request();
31
- const result = await request.query(q);
32
- return this.mapResult(result);
33
- }
34
- mapResult(result) {
35
- // TODO: see https://github.com/tediousjs/node-mssql/pull/1171
36
- const meta = result.recordset?.columns;
37
- if (meta != null && typeof __classPrivateFieldGet(this, _MSSQL_typeCast, "f") === "function") {
38
- return __classPrivateFieldGet(this, _MSSQL_typeCast, "f").call(this, result, meta);
39
- }
40
- return result.recordset;
41
- }
42
- formatQuery(q, values) {
43
- return TSqlString.format(q, values);
44
- }
45
- async beginTransaction(isolationLevel) {
46
- const transaction = new mssql.Transaction(__classPrivateFieldGet(this, _MSSQL_pool, "f"));
47
- let rolledBack = false;
48
- transaction.on("rollback", (aborted) => {
49
- // emited with aborted === true
50
- rolledBack = true;
51
- });
52
- async function handleError(err) {
53
- if (!rolledBack) {
54
- await transaction.rollback();
55
- }
56
- throw err;
57
- }
58
- const mapResult = this.mapResult.bind(this);
59
- let isolationLevelNumber;
60
- if (isolationLevel) {
61
- isolationLevelNumber = mssql.ISOLATION_LEVEL[isolationLevel.replace(" ", "_")];
62
- if (isolationLevelNumber == null) {
63
- throw new Error(`Invalid isolationLevel: ${isolationLevel}`);
64
- }
65
- }
66
- await transaction.begin(isolationLevelNumber);
67
- return {
68
- commit: () => transaction.commit().catch(handleError),
69
- rollback: () => transaction.rollback(),
70
- dbCall: (q) => new mssql.Request(transaction).query(q).then(mapResult).catch(handleError)
71
- };
72
- }
73
- async closePool() {
74
- await __classPrivateFieldGet(this, _MSSQL_pool, "f").close();
75
- }
76
- }
77
- exports.MSSQL = MSSQL;
78
- _MSSQL_pool = new WeakMap(), _MSSQL_poolConnect = new WeakMap(), _MSSQL_typeCast = new WeakMap();
@@ -1,3 +0,0 @@
1
- declare type TValueCast = (value: any) => any;
2
- export declare function typeCastMSSQL(customTypeCast?: (meta: any, mssql: any) => TValueCast): (result: any, meta: any) => any;
3
- export {};