@technicity/data-service-generator 0.10.0-next.0 → 0.11.0-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.
Files changed (42) hide show
  1. package/dist/generation/generate.js +2 -1
  2. package/dist/index.d.ts +2 -1
  3. package/dist/index.js +4 -3
  4. package/dist/runtime/RuntimeKSQL.d.ts +1 -1
  5. package/dist/runtime/RuntimeKSQL.js +11 -13
  6. package/dist/runtime/RuntimeMSSQL.d.ts +14 -18
  7. package/dist/runtime/RuntimeMSSQL.js +43 -48
  8. package/dist/runtime/RuntimeMySQL.d.ts +12 -10
  9. package/dist/runtime/RuntimeMySQL.js +84 -46
  10. package/dist/runtime/lib/MSSQL.d.ts +13 -0
  11. package/dist/runtime/lib/MSSQL.js +73 -0
  12. package/dist/runtime/lib/SDKBadWhereError.d.ts +4 -0
  13. package/dist/runtime/lib/SDKBadWhereError.js +10 -0
  14. package/dist/runtime/lib/SDKNotFoundError.d.ts +4 -0
  15. package/dist/runtime/lib/SDKNotFoundError.js +10 -0
  16. package/dist/runtime/lib/getDateTimeStringMySQL.d.ts +1 -0
  17. package/dist/runtime/lib/getDateTimeStringMySQL.js +8 -0
  18. package/dist/runtime/lib/getSqlAst.js +2 -2
  19. package/dist/runtime/lib/getWhere.d.ts +0 -17
  20. package/dist/runtime/lib/getWhere.js +4 -228
  21. package/dist/runtime/lib/shared.d.ts +13 -22
  22. package/dist/runtime/lib/shared.js +787 -16
  23. package/dist/runtime/lib/stringifyWhere.d.ts +18 -0
  24. package/dist/runtime/lib/stringifyWhere.js +228 -0
  25. package/dist/runtime/lib/typeCastMSSQL.js +1 -1
  26. package/package.json +4 -1
  27. package/dist/runtime/Runtime.d.ts +0 -23
  28. package/dist/runtime/Runtime.js +0 -29
  29. package/dist/runtime/lib/create.d.ts +0 -12
  30. package/dist/runtime/lib/create.js +0 -175
  31. package/dist/runtime/lib/delete.d.ts +0 -5
  32. package/dist/runtime/lib/delete.js +0 -43
  33. package/dist/runtime/lib/error.d.ts +0 -9
  34. package/dist/runtime/lib/error.js +0 -22
  35. package/dist/runtime/lib/getData.d.ts +0 -4
  36. package/dist/runtime/lib/getData.js +0 -227
  37. package/dist/runtime/lib/prepareWhere.d.ts +0 -2
  38. package/dist/runtime/lib/prepareWhere.js +0 -158
  39. package/dist/runtime/lib/resolve.d.ts +0 -10
  40. package/dist/runtime/lib/resolve.js +0 -66
  41. package/dist/runtime/lib/update.d.ts +0 -4
  42. package/dist/runtime/lib/update.js +0 -143
@@ -1,227 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getData = exports.getCacheableData = void 0;
4
- // @ts-ignore
5
- const batch_planner_1 = require("join-monster/dist/batch-planner");
6
- // @ts-ignore
7
- const util_1 = require("join-monster/dist/util");
8
- const _ = require("lodash/fp");
9
- const error_1 = require("./error");
10
- const addNullFallbacks_1 = require("./addNullFallbacks");
11
- const cursor_1 = require("./cursor");
12
- const getOrderBy_1 = require("./getOrderBy");
13
- const getSqlAst_1 = require("./getSqlAst");
14
- const getWhere_1 = require("./getWhere");
15
- const shared_1 = require("./shared");
16
- async function getCacheableData(input, dbCall, formatQuery, dialect, cache) {
17
- const { request, cached } = await cache.from(input);
18
- if (cached)
19
- return cached;
20
- ensureUuidSelect(input);
21
- const results = await getData(input, dbCall, formatQuery, dialect);
22
- cache.insert(request, results);
23
- return results;
24
- }
25
- exports.getCacheableData = getCacheableData;
26
- async function getData(input, dbCall, formatQuery, dialect) {
27
- const context = {};
28
- const { action } = input;
29
- const { primaryKey } = input.artifacts[input.resource];
30
- let paginationType;
31
- let limit = undefined;
32
- let offset = undefined;
33
- let rowWithMatchingCursor = undefined;
34
- if (action === "findManyPaginated") {
35
- if (input.args?.$paginate == null) {
36
- throw new Error("$paginate required but not supplied");
37
- }
38
- if (typeof input?.args?.$paginate?.limit === "number") {
39
- paginationType = "limit-offset";
40
- limit = input.args.$paginate.limit;
41
- offset = input.args.$paginate.offset;
42
- }
43
- else if (typeof input?.args?.$paginate?.first === "number" ||
44
- typeof input?.args?.$paginate?.last === "number") {
45
- paginationType = "cursor";
46
- limit = (typeof input?.args?.$paginate?.first === "number"
47
- ? input?.args?.$paginate?.first
48
- : input?.args?.$paginate?.last);
49
- // + 1 to peek if there is more data
50
- limit += 1;
51
- if (input.args.$paginate.after != null ||
52
- input.args.$paginate.before != null) {
53
- const cursor = input.args.$paginate.after != null
54
- ? input.args.$paginate.after
55
- : input.args.$paginate.before;
56
- rowWithMatchingCursor = await dbCall(formatQuery("SELECT * FROM ?? WHERE ?? = ?", [
57
- input.resource,
58
- primaryKey,
59
- (0, cursor_1.decodeCursor)(cursor),
60
- ])).then((xs) => xs[0]);
61
- if (rowWithMatchingCursor == null) {
62
- throw new Error(`Invalid cursor: ${cursor}`);
63
- }
64
- }
65
- }
66
- else {
67
- throw new Error(`Invalid $paginate: ${input?.args?.$paginate}`);
68
- }
69
- }
70
- else if (action === "findMany") {
71
- if (typeof input?.args?.$limit === "number") {
72
- limit = input?.args?.$limit;
73
- }
74
- }
75
- // we need to read the query AST and build a new "SQL AST" from which the SQL and
76
- // const sqlAST = queryAST.queryASTToSqlAST(resolveInfo, options, context);
77
- const fields = input.fields ?? (0, shared_1.getScalarFields)(input.resource, input.artifacts);
78
- const orderByListPaginatedRootResult =
79
- // MSSQL's OFFSET and FETCH requires ORDER BY, so we need to provide a fallback
80
- dialect === "mssql" && paginationType === "limit-offset"
81
- ? {
82
- orderBy: (0, getOrderBy_1.getOrderBy)(input.args, primaryKey)?.orderBy ?? [
83
- { column: primaryKey, direction: "asc" },
84
- ],
85
- flip: false,
86
- }
87
- : action === "findManyPaginated"
88
- ? (0, getOrderBy_1.getOrderBy)(input.args, primaryKey)
89
- : undefined;
90
- const grabMany = action === "findMany" ||
91
- action === "findManyPaginated" ||
92
- action === "updateMany" ||
93
- action === "deleteMany";
94
- const sqlAST = (0, getSqlAst_1.getSqlAst)({
95
- ...input,
96
- table: input.resource,
97
- fieldName: "data",
98
- fields,
99
- getWhere: getWhere_1.getWhere,
100
- orderBy: orderByListPaginatedRootResult?.orderBy,
101
- rowWithMatchingCursor,
102
- dialect,
103
- grabMany,
104
- });
105
- const options = { dialect };
106
- let { sql, shapeDefinition } = await (0, util_1.compileSqlAST)(sqlAST, context, options);
107
- if (!sql) {
108
- // return {};
109
- throw new Error("No SQL");
110
- }
111
- // TODO - remove if limit support added for mysql dialect
112
- if (action === "findMany" || action === "findManyPaginated") {
113
- if (typeof limit === "number") {
114
- const escape = (0, getWhere_1.getEscape)(dialect);
115
- if (dialect === "mssql") {
116
- if (typeof offset === "number") {
117
- sql += ` OFFSET ${escape(offset)} ROWS FETCH NEXT ${escape(limit)} ROWS ONLY`;
118
- }
119
- else {
120
- sql = sql.replace("SELECT", `SELECT TOP ${escape(limit)}`);
121
- }
122
- }
123
- else {
124
- sql += ` LIMIT ${escape(limit)}`;
125
- if (typeof offset === "number") {
126
- sql += ` OFFSET ${escape(offset)}`;
127
- }
128
- }
129
- }
130
- }
131
- // call their function for querying the DB, handle the different cases, do some validation, return a promise of the object
132
- let data = await (0, util_1.handleUserDbCall)(dbCall, sql, sqlAST, shapeDefinition);
133
- // if they are paginating, we'll get back an array which is essentially a "slice" of the whole data.
134
- // this function goes through the data tree and converts the arrays to Connection Objects
135
- // data = arrToConnection(data, sqlAST);
136
- // so far we handled the first "batch". up until now, additional batches were ignored
137
- // this function recursively scanss the sqlAST and runs remaining batches
138
- await (0, batch_planner_1.default)(sqlAST, data, dbCall, context, options);
139
- (0, addNullFallbacks_1.addNullFallbacks)(sqlAST, data);
140
- // We only need to remove extra keys if input.fields isn't
141
- // specified, since otherwise there wouldn't be extra keys
142
- const shouldRemoveExtraKeys = input.fields != null;
143
- if (action !== "findManyPaginated") {
144
- // Remove additional keys that are added for batches and joins
145
- // Do later for `listPaginated`, since the `id` is needed for
146
- // creating the cursor
147
- (0, shared_1.postProcess)(data, fields, shouldRemoveExtraKeys);
148
- }
149
- // check for batch data
150
- if (Array.isArray(data)) {
151
- // TODO - not sure why this code exists in original
152
- // source code of join-monster; doesn't make sense to me.
153
- // const childrenToCheck = sqlAST.children.filter(
154
- // (child: any) => child.sqlBatch
155
- // );
156
- // data = data.filter((d) => {
157
- // for (const child of childrenToCheck) {
158
- // if (d[child.fieldName] == null) {
159
- // return false;
160
- // }
161
- // }
162
- // return true;
163
- // });
164
- if (action === "findManyPaginated") {
165
- const argsTotalCount = input.args && _.cloneDeep(input.args);
166
- if (argsTotalCount != null) {
167
- if (argsTotalCount.$paginate != null) {
168
- // We don't want the where clause to include cursor-related stuff
169
- delete argsTotalCount.$paginate.after;
170
- delete argsTotalCount.$paginate.before;
171
- // We don't need offset
172
- delete argsTotalCount.$paginate.offset;
173
- }
174
- }
175
- const sqlASTTotalCount = (0, getSqlAst_1.getSqlAst)({
176
- ...input,
177
- table: input.resource,
178
- fieldName: "data",
179
- args: argsTotalCount,
180
- // Because we're going to manually set children anyway
181
- fields: [],
182
- getWhere: getWhere_1.getWhere,
183
- // We don't want the where clause to include cursor-related stuff
184
- rowWithMatchingCursor: null,
185
- dialect,
186
- grabMany: true,
187
- });
188
- // Because orderBy doesn't matter for total count.
189
- // getOrderBy adds an element if paginating, so deleting args.$orderBy
190
- // isn't sufficient.
191
- delete sqlASTTotalCount.orderBy;
192
- const totalCount = await (0, shared_1.getTotalCount)(sqlASTTotalCount, dbCall, context, options);
193
- if (paginationType === "cursor") {
194
- data = (0, shared_1.wrapListPaginationCursor)(data, input.args, orderByListPaginatedRootResult.flip, (xs) => {
195
- (0, shared_1.postProcess)(xs, fields, shouldRemoveExtraKeys);
196
- }, input.artifacts[input.resource].primaryKey, totalCount);
197
- }
198
- else {
199
- (0, shared_1.postProcess)(data, fields, shouldRemoveExtraKeys);
200
- data = (0, shared_1.wrapListPaginationLimitOffset)(data, totalCount);
201
- }
202
- }
203
- return data;
204
- }
205
- if (data == null && !grabMany) {
206
- throw new error_1.SDKNotFoundError();
207
- }
208
- return data;
209
- }
210
- exports.getData = getData;
211
- function ensureUuidSelect(input) {
212
- const { resource, artifacts } = input;
213
- ensure(resource, input);
214
- function ensure(type, input) {
215
- const { scalarFields, relationFields } = artifacts[type];
216
- if (!scalarFields.includes("uuid"))
217
- return;
218
- const fields = input.fields;
219
- if (!fields.includes("uuid"))
220
- fields.unshift("uuid");
221
- for (const field of fields)
222
- if (typeof field == "object") {
223
- const { table } = relationFields[field.name];
224
- ensure(table, field);
225
- }
226
- }
227
- }
@@ -1,2 +0,0 @@
1
- import { IArtifacts, TDbCall, TFormatQuery } from '../IRuntime';
2
- export declare function prepareWhere(artifacts: IArtifacts, table: string, data: any, dbCall: TDbCall, formatQuery: TFormatQuery): Promise<{}>;
@@ -1,158 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.prepareWhere = void 0;
4
- const _ = require("lodash/fp");
5
- const error_1 = require("./error");
6
- const OPERATIONS = [
7
- "$eq",
8
- "$neq",
9
- "$gt",
10
- "$gte",
11
- "$lt",
12
- "$lte",
13
- "$in",
14
- "$nin",
15
- "$like",
16
- "$nlike",
17
- "$btwn",
18
- "$nbtwn",
19
- ];
20
- async function prepareWhere(artifacts, table, data, dbCall, formatQuery) {
21
- const { mappedFields } = artifacts[table];
22
- let out = {};
23
- await traverseWhere(data, async (where, ptr, parentPtr, root) => {
24
- const path = ptr.split("/").slice(1);
25
- const opIndex = path.length - 1;
26
- if (OPERATIONS.includes(path[opIndex])) {
27
- const newPath = path.slice();
28
- const index = newPath.length - 2;
29
- const key = newPath[index];
30
- const mappedField = mappedFields?.[key];
31
- if (mappedField != null) {
32
- newPath[index] = mappedField.foreignKey;
33
- if (Array.isArray(where)) {
34
- const newVal = await Promise.all(where.map((v) => dbCall(formatQuery("SELECT ?? FROM ?? WHERE ?? = ?", [
35
- mappedField.referencedKey,
36
- mappedField.referencedTable,
37
- mappedField.name,
38
- v,
39
- ])).then((xs) => xs[0]?.[mappedField.referencedKey])));
40
- if (newVal.some((x) => x == null)) {
41
- const index = newVal.findIndex((x) => x == null);
42
- if (index === -1) {
43
- throw new error_1.SDKBadWhereError();
44
- }
45
- else {
46
- const v = where[index];
47
- throw new error_1.SDKBadWhereError(getPrepareWhereNotFoundMessage(mappedField, v));
48
- }
49
- }
50
- out = _.set(newPath, newVal, out);
51
- }
52
- else {
53
- const newVal = await dbCall(formatQuery("SELECT ?? FROM ?? WHERE ?? = ?", [
54
- mappedField.referencedKey,
55
- mappedField.referencedTable,
56
- mappedField.name,
57
- where,
58
- ])).then((xs) => xs[0]?.[mappedField.referencedKey]);
59
- if (newVal == null) {
60
- throw new error_1.SDKBadWhereError(getPrepareWhereNotFoundMessage(mappedField, where));
61
- }
62
- out = _.set(newPath, newVal, out);
63
- }
64
- out = _.unset(path.slice(0, path.length - 1), out);
65
- return;
66
- }
67
- }
68
- else {
69
- const key = path[path.length - 1];
70
- const mappedField = mappedFields?.[key];
71
- if (mappedField != null) {
72
- const newPath = path
73
- .slice(0, path.length - 1)
74
- .concat(mappedField.foreignKey);
75
- if (Array.isArray(where)) {
76
- const newVal = await Promise.all(where.map((v) => dbCall(formatQuery("SELECT ?? FROM ?? WHERE ?? = ?", [
77
- mappedField.referencedKey,
78
- mappedField.referencedTable,
79
- mappedField.name,
80
- v,
81
- ])).then((xs) => xs[0]?.[mappedField.referencedKey])));
82
- if (newVal.some((x) => x == null)) {
83
- const index = newVal.findIndex((x) => x == null);
84
- if (index === -1) {
85
- throw new error_1.SDKBadWhereError();
86
- }
87
- else {
88
- const v = where[index];
89
- throw new error_1.SDKBadWhereError(getPrepareWhereNotFoundMessage(mappedField, v));
90
- }
91
- }
92
- out = _.set(newPath, newVal, out);
93
- }
94
- else {
95
- const newVal = await dbCall(formatQuery("SELECT ?? FROM ?? WHERE ?? = ?", [
96
- mappedField.referencedKey,
97
- mappedField.referencedTable,
98
- mappedField.name,
99
- where,
100
- ])).then((xs) => xs[0]?.[mappedField.referencedKey]);
101
- if (newVal == null) {
102
- throw new error_1.SDKBadWhereError(getPrepareWhereNotFoundMessage(mappedField, where));
103
- }
104
- out = _.set(newPath, newVal, out);
105
- }
106
- out = _.unset(path, out);
107
- }
108
- else {
109
- out = path.length > 0 ? _.set(path, where, out) : where;
110
- }
111
- }
112
- });
113
- return out;
114
- }
115
- exports.prepareWhere = prepareWhere;
116
- function getPrepareWhereNotFoundMessage(mappedField, value) {
117
- return `Not found: unable to map \`${mappedField.referencedTable}\`.\`${mappedField.name}\` to \`${mappedField.referencedTable}\`.\`${mappedField.referencedKey}\` for the value \`${value}\`.`;
118
- }
119
- async function traverseWhere(where, cb) {
120
- return await _traverseWhere(cb, where, "", where);
121
- }
122
- async function _traverseWhere(cb, where, ptr, root, parentPtr) {
123
- await cb(where, ptr, parentPtr, root);
124
- if (where && typeof where == "object" && !Array.isArray(where)) {
125
- for (let key in where) {
126
- const sch = where[key];
127
- if (key === "$and" || key == "$or") {
128
- await Promise.all(sch.map(async (s, i) => {
129
- await _traverseWhere(cb, s, ptr + "/" + key + "/" + i, root, ptr
130
- // key,
131
- // where,
132
- // parentPtr,
133
- // i
134
- );
135
- }));
136
- }
137
- else if (typeof sch === "object") {
138
- for (let prop in sch) {
139
- await _traverseWhere(cb, sch[prop], ptr + "/" + key + "/" + escapePtr(prop), root, ptr
140
- // key,
141
- // where,
142
- // prop
143
- );
144
- }
145
- }
146
- else {
147
- await _traverseWhere(cb, sch, ptr + "/" + key, root, ptr
148
- // key,
149
- // where
150
- );
151
- }
152
- }
153
- }
154
- }
155
- ;
156
- function escapePtr(str) {
157
- return str.replace(/~/g, "~0").replace(/\//g, "~1");
158
- }
@@ -1,10 +0,0 @@
1
- import Cache from '../Cache';
2
- import { IDialect, TBeginTransaction, TContext, TDbCall, TFormatQuery, TMiddleware, TResolveParams } from '../IRuntime';
3
- export declare function resolve(input: TResolveParams, dbCall: TDbCall, formatQuery: TFormatQuery, beginTransaction: TBeginTransaction, dialect: IDialect, middlewareHandler: MiddlewareHandler<TMiddleware>, context: TContext, cache?: Cache): Promise<any>;
4
- export declare class MiddlewareHandler<M extends Function> {
5
- private _middlewares;
6
- register(middleware: M): void;
7
- get(id: number): M | undefined;
8
- has(id: number): boolean;
9
- length(): number;
10
- }
@@ -1,66 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MiddlewareHandler = exports.resolve = void 0;
4
- const async_hooks_1 = require("async_hooks");
5
- const create_1 = require("./create");
6
- const delete_1 = require("./delete");
7
- const getData_1 = require("./getData");
8
- const update_1 = require("./update");
9
- async function resolve(input, dbCall, formatQuery, beginTransaction, dialect, middlewareHandler, context, cache) {
10
- // https://github.com/prisma/prisma/blob/822198e5ba21535364d20c86901b8c3778ebf6a3/packages/client/src/runtime/getPrismaClient.ts#L1087
11
- let index = -1;
12
- const resolve = (extra) => {
13
- const inputs = { ...input, ...extra };
14
- switch (inputs.action) {
15
- case "findUnique":
16
- case "findMany":
17
- case "findManyPaginated":
18
- return cache ?
19
- (0, getData_1.getCacheableData)(inputs, dbCall, formatQuery, dialect, cache) :
20
- (0, getData_1.getData)(inputs, dbCall, formatQuery, dialect);
21
- case "create":
22
- return (0, create_1.create)(inputs, dbCall, formatQuery, beginTransaction, dialect, context);
23
- case "update":
24
- return (0, update_1.update)(inputs, dbCall, formatQuery, dialect, cache);
25
- case "updateMany":
26
- return (0, update_1.updateMany)(inputs, dbCall, formatQuery, dialect, cache);
27
- case "delete":
28
- return (0, delete_1.deleteOne)(inputs, dbCall, formatQuery, dialect, cache);
29
- case "deleteMany":
30
- return (0, delete_1.deleteMany)(inputs, dbCall, formatQuery, dialect, cache);
31
- default:
32
- throw new Error("Invalid action: " + inputs.action);
33
- }
34
- };
35
- if (middlewareHandler.length() > 0) {
36
- const resource = new async_hooks_1.AsyncResource("sdk-request");
37
- const params = input;
38
- const consumer = (paramsMaybeMutated) => {
39
- const nextMiddleware = middlewareHandler.get(++index);
40
- if (nextMiddleware != null)
41
- return nextMiddleware(paramsMaybeMutated, consumer);
42
- return resolve(params);
43
- };
44
- return resource.runInAsyncScope(() => consumer(params));
45
- }
46
- return resolve();
47
- }
48
- exports.resolve = resolve;
49
- class MiddlewareHandler {
50
- constructor() {
51
- this._middlewares = [];
52
- }
53
- register(middleware) {
54
- this._middlewares.push(middleware);
55
- }
56
- get(id) {
57
- return this._middlewares[id];
58
- }
59
- has(id) {
60
- return !!this._middlewares[id];
61
- }
62
- length() {
63
- return this._middlewares.length;
64
- }
65
- }
66
- exports.MiddlewareHandler = MiddlewareHandler;
@@ -1,4 +0,0 @@
1
- import Cache from '../Cache';
2
- import { IDialect, TDbCall, TFormatQuery, TResolveParams } from '../IRuntime';
3
- export declare function update(input: TResolveParams, dbCall: TDbCall, formatQuery: TFormatQuery, dialect: IDialect, cache?: Cache): Promise<any>;
4
- export declare function updateMany(input: TResolveParams, dbCall: TDbCall, formatQuery: TFormatQuery, dialect: IDialect, cache?: Cache): Promise<any>;
@@ -1,143 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.updateMany = exports.update = void 0;
4
- const error_1 = require("./error");
5
- const getData_1 = require("./getData");
6
- const getWhere_1 = require("./getWhere");
7
- const shared_1 = require("./shared");
8
- async function update(input, dbCall, formatQuery, dialect, cache) {
9
- async function _update() {
10
- const escapeId = (0, getWhere_1.getEscapeId)(dialect);
11
- const tableArtifacts = input.artifacts[input.resource];
12
- const where = (0, getWhere_1.getWhere)(escapeId(input.resource), input.args, dialect);
13
- if (where == null) {
14
- throw new Error("Null where");
15
- }
16
- const current = await dbCall(formatQuery("SELECT * FROM ?? WHERE " + where, [input.resource])).then((xs) => xs[0]);
17
- if (current == null) {
18
- throw new error_1.SDKNotFoundError();
19
- }
20
- if (cache && current.uuid)
21
- cache.purge(current.uuid);
22
- // Shallow clone, as we're going to mutate later
23
- const data = { ...input.data };
24
- if ((0, shared_1.hasMappedFields)(input.artifacts, input.resource, data)) {
25
- await (0, shared_1.mapMappedFields)(tableArtifacts, data, dbCall, formatQuery);
26
- }
27
- if (dialect === "mysql" && tableArtifacts.dateTimeFieldsCount > 0) {
28
- for (let k in tableArtifacts.dateTimeFields) {
29
- if (data[k] != null) {
30
- data[k] = (0, shared_1.getDateTimeStringMySQL)(data[k]);
31
- }
32
- }
33
- }
34
- // Delete keys with value of undefined
35
- for (let k in data) {
36
- if (data[k] === void 0) {
37
- delete data[k];
38
- }
39
- }
40
- // Nothing to update
41
- if (Object.keys(data).length === 0) {
42
- return true;
43
- }
44
- await dbCall(getUpdateQuery(input.resource, data, where, dialect, formatQuery));
45
- return true;
46
- }
47
- await _update();
48
- return (0, getData_1.getData)(input, dbCall, formatQuery, dialect);
49
- }
50
- exports.update = update;
51
- async function updateMany(input, dbCall, formatQuery, dialect, cache) {
52
- async function _updateMany() {
53
- const escapeId = (0, getWhere_1.getEscapeId)(dialect);
54
- const tableArtifacts = input.artifacts[input.resource];
55
- const where = (0, getWhere_1.getWhere)(escapeId(input.resource), input.args, dialect);
56
- if (where == null)
57
- throw new Error("Null where");
58
- if (cache)
59
- try {
60
- const query = formatQuery(`SELECT uuid FROM ?? WHERE ${where}`, [input.resource]);
61
- const matches = await dbCall(query);
62
- const uuids = matches.map((x) => x.uuid);
63
- cache.purge(...uuids);
64
- }
65
- catch (err) { }
66
- // Shallow clone, as we're going to mutate later
67
- const data = { ...input.data };
68
- if ((0, shared_1.hasMappedFields)(input.artifacts, input.resource, data)) {
69
- await (0, shared_1.mapMappedFields)(tableArtifacts, data, dbCall, formatQuery);
70
- }
71
- if (dialect === "mysql" && tableArtifacts.dateTimeFieldsCount > 0) {
72
- for (let k in tableArtifacts.dateTimeFields) {
73
- if (data[k] != null) {
74
- data[k] = (0, shared_1.getDateTimeStringMySQL)(data[k]);
75
- }
76
- }
77
- }
78
- // Delete keys with value of undefined
79
- for (let k in data) {
80
- if (data[k] === void 0) {
81
- delete data[k];
82
- }
83
- }
84
- // Nothing to update
85
- if (Object.keys(data).length === 0) {
86
- return [];
87
- }
88
- await dbCall(getUpdateQuery(input.resource, data, where, dialect, formatQuery));
89
- return true;
90
- }
91
- await _updateMany();
92
- return (0, getData_1.getData)(input, dbCall, formatQuery, dialect);
93
- }
94
- exports.updateMany = updateMany;
95
- function getUpdateQuery(table, data, where, dialect, formatQuery) {
96
- // Assumes `data` is not empty
97
- const escapeId = (0, getWhere_1.getEscapeId)(dialect);
98
- const escape = (0, getWhere_1.getEscape)(dialect);
99
- let q = "UPDATE ?? ";
100
- const values = [table];
101
- const opsStrs = [];
102
- const dataRegular = {};
103
- for (let k in data) {
104
- const v = data[k];
105
- if (typeof v === "object" && v != null && Object.keys(v).length === 1) {
106
- const _entries = Object.entries(v)?.[0];
107
- const op = _entries?.[0];
108
- const vv = _entries?.[1];
109
- if (op === "$prepend") {
110
- opsStrs.push(`${table}.${escapeId(k)} = CASE WHEN ${table}.${escapeId(k)} IS NULL THEN NULL ELSE CONCAT(${escape(vv)}, ${table}.${escapeId(k)}) END`);
111
- continue;
112
- }
113
- if (op === "$append") {
114
- opsStrs.push(`${table}.${escapeId(k)} = CASE WHEN ${table}.${escapeId(k)} IS NULL THEN NULL ELSE CONCAT(${table}.${escapeId(k)}, ${escape(vv)}) END`);
115
- continue;
116
- }
117
- if (op === "$increment") {
118
- opsStrs.push(`${table}.${escapeId(k)} = ${table}.${escapeId(k)} + ${escape(vv)}`);
119
- continue;
120
- }
121
- if (op === "$decrement") {
122
- opsStrs.push(`${table}.${escapeId(k)} = ${table}.${escapeId(k)} - ${escape(vv)}`);
123
- continue;
124
- }
125
- dataRegular[k] = v;
126
- }
127
- dataRegular[k] = v;
128
- }
129
- if (opsStrs.length > 0) {
130
- q += `SET ${opsStrs.join(", ")}`;
131
- }
132
- if (Object.keys(dataRegular).length > 0) {
133
- if (opsStrs.length > 0) {
134
- q += ", ?";
135
- }
136
- else {
137
- q += "SET ?";
138
- }
139
- values.push(dataRegular);
140
- }
141
- q += ` WHERE ${where}`;
142
- return formatQuery(q, values);
143
- }