@zenstackhq/runtime 2.15.1 → 3.0.0-alpha.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 (215) hide show
  1. package/LICENSE +1 -1
  2. package/dist/client.cjs +6094 -0
  3. package/dist/client.cjs.map +1 -0
  4. package/dist/client.d.cts +19 -0
  5. package/dist/client.d.ts +19 -0
  6. package/dist/client.js +6060 -0
  7. package/dist/client.js.map +1 -0
  8. package/dist/contract-DguafRNB.d.cts +1272 -0
  9. package/dist/contract-DguafRNB.d.ts +1272 -0
  10. package/dist/index.cjs +6088 -0
  11. package/dist/index.cjs.map +1 -0
  12. package/dist/index.d.cts +14 -0
  13. package/dist/index.d.ts +14 -0
  14. package/dist/index.js +6057 -0
  15. package/dist/index.js.map +1 -0
  16. package/dist/plugins/policy.cjs +2343 -0
  17. package/dist/plugins/policy.cjs.map +1 -0
  18. package/dist/plugins/policy.d.cts +24 -0
  19. package/dist/plugins/policy.d.ts +24 -0
  20. package/dist/plugins/policy.js +2307 -0
  21. package/dist/plugins/policy.js.map +1 -0
  22. package/dist/schema.cjs +110 -0
  23. package/dist/schema.cjs.map +1 -0
  24. package/dist/schema.d.cts +29 -0
  25. package/dist/schema.d.ts +29 -0
  26. package/dist/schema.js +85 -0
  27. package/dist/schema.js.map +1 -0
  28. package/dist/utils/pg-utils.cjs +39 -0
  29. package/dist/utils/pg-utils.cjs.map +1 -0
  30. package/dist/utils/pg-utils.d.cts +8 -0
  31. package/dist/utils/pg-utils.d.ts +8 -0
  32. package/dist/utils/pg-utils.js +16 -0
  33. package/dist/utils/pg-utils.js.map +1 -0
  34. package/{browser/index.js → dist/utils/sqlite-utils.cjs} +21 -37
  35. package/dist/utils/sqlite-utils.cjs.map +1 -0
  36. package/dist/utils/sqlite-utils.d.cts +8 -0
  37. package/dist/utils/sqlite-utils.d.ts +8 -0
  38. package/dist/utils/sqlite-utils.js +22 -0
  39. package/dist/utils/sqlite-utils.js.map +1 -0
  40. package/package.json +105 -114
  41. package/README.md +0 -5
  42. package/browser/index.d.mts +0 -13
  43. package/browser/index.d.ts +0 -13
  44. package/browser/index.js.map +0 -1
  45. package/browser/index.mjs +0 -33
  46. package/browser/index.mjs.map +0 -1
  47. package/constants.d.ts +0 -62
  48. package/constants.js +0 -76
  49. package/constants.js.map +0 -1
  50. package/cross/index.d.mts +0 -379
  51. package/cross/index.d.ts +0 -379
  52. package/cross/index.js +0 -903
  53. package/cross/index.js.map +0 -1
  54. package/cross/index.mjs +0 -861
  55. package/cross/index.mjs.map +0 -1
  56. package/edge.d.ts +0 -1
  57. package/edge.js +0 -18
  58. package/edge.js.map +0 -1
  59. package/encryption/index.d.ts +0 -25
  60. package/encryption/index.js +0 -74
  61. package/encryption/index.js.map +0 -1
  62. package/encryption/utils.d.ts +0 -9
  63. package/encryption/utils.js +0 -99
  64. package/encryption/utils.js.map +0 -1
  65. package/enhance-edge.d.ts +0 -1
  66. package/enhance-edge.js +0 -10
  67. package/enhance.d.ts +0 -1
  68. package/enhance.js +0 -10
  69. package/enhancements/edge/create-enhancement.d.ts +0 -42
  70. package/enhancements/edge/create-enhancement.js +0 -102
  71. package/enhancements/edge/create-enhancement.js.map +0 -1
  72. package/enhancements/edge/default-auth.d.ts +0 -8
  73. package/enhancements/edge/default-auth.js +0 -180
  74. package/enhancements/edge/default-auth.js.map +0 -1
  75. package/enhancements/edge/delegate.d.ts +0 -77
  76. package/enhancements/edge/delegate.js +0 -1294
  77. package/enhancements/edge/delegate.js.map +0 -1
  78. package/enhancements/edge/encryption.d.ts +0 -7
  79. package/enhancements/edge/encryption.js +0 -150
  80. package/enhancements/edge/encryption.js.map +0 -1
  81. package/enhancements/edge/index.d.ts +0 -4
  82. package/enhancements/edge/index.js +0 -21
  83. package/enhancements/edge/index.js.map +0 -1
  84. package/enhancements/edge/json-processor.d.ts +0 -7
  85. package/enhancements/edge/json-processor.js +0 -89
  86. package/enhancements/edge/json-processor.js.map +0 -1
  87. package/enhancements/edge/logger.d.ts +0 -29
  88. package/enhancements/edge/logger.js +0 -65
  89. package/enhancements/edge/logger.js.map +0 -1
  90. package/enhancements/edge/omit.d.ts +0 -7
  91. package/enhancements/edge/omit.js +0 -96
  92. package/enhancements/edge/omit.js.map +0 -1
  93. package/enhancements/edge/password.d.ts +0 -7
  94. package/enhancements/edge/password.js +0 -64
  95. package/enhancements/edge/password.js.map +0 -1
  96. package/enhancements/edge/policy/check-utils.d.ts +0 -5
  97. package/enhancements/edge/policy/check-utils.js +0 -20
  98. package/enhancements/edge/policy/check-utils.js.map +0 -1
  99. package/enhancements/edge/policy/handler.d.ts +0 -100
  100. package/enhancements/edge/policy/handler.js +0 -1442
  101. package/enhancements/edge/policy/handler.js.map +0 -1
  102. package/enhancements/edge/policy/index.d.ts +0 -19
  103. package/enhancements/edge/policy/index.js +0 -65
  104. package/enhancements/edge/policy/index.js.map +0 -1
  105. package/enhancements/edge/policy/policy-utils.d.ts +0 -181
  106. package/enhancements/edge/policy/policy-utils.js +0 -1357
  107. package/enhancements/edge/policy/policy-utils.js.map +0 -1
  108. package/enhancements/edge/promise.d.ts +0 -15
  109. package/enhancements/edge/promise.js +0 -99
  110. package/enhancements/edge/promise.js.map +0 -1
  111. package/enhancements/edge/proxy.d.ts +0 -120
  112. package/enhancements/edge/proxy.js +0 -287
  113. package/enhancements/edge/proxy.js.map +0 -1
  114. package/enhancements/edge/query-utils.d.ts +0 -53
  115. package/enhancements/edge/query-utils.js +0 -256
  116. package/enhancements/edge/query-utils.js.map +0 -1
  117. package/enhancements/edge/types.d.ts +0 -238
  118. package/enhancements/edge/types.js +0 -3
  119. package/enhancements/edge/types.js.map +0 -1
  120. package/enhancements/edge/utils.d.ts +0 -11
  121. package/enhancements/edge/utils.js +0 -49
  122. package/enhancements/edge/utils.js.map +0 -1
  123. package/enhancements/edge/where-visitor.d.ts +0 -32
  124. package/enhancements/edge/where-visitor.js +0 -86
  125. package/enhancements/edge/where-visitor.js.map +0 -1
  126. package/enhancements/node/create-enhancement.d.ts +0 -42
  127. package/enhancements/node/create-enhancement.js +0 -102
  128. package/enhancements/node/create-enhancement.js.map +0 -1
  129. package/enhancements/node/default-auth.d.ts +0 -8
  130. package/enhancements/node/default-auth.js +0 -180
  131. package/enhancements/node/default-auth.js.map +0 -1
  132. package/enhancements/node/delegate.d.ts +0 -77
  133. package/enhancements/node/delegate.js +0 -1294
  134. package/enhancements/node/delegate.js.map +0 -1
  135. package/enhancements/node/encryption.d.ts +0 -7
  136. package/enhancements/node/encryption.js +0 -150
  137. package/enhancements/node/encryption.js.map +0 -1
  138. package/enhancements/node/index.d.ts +0 -4
  139. package/enhancements/node/index.js +0 -21
  140. package/enhancements/node/index.js.map +0 -1
  141. package/enhancements/node/json-processor.d.ts +0 -7
  142. package/enhancements/node/json-processor.js +0 -89
  143. package/enhancements/node/json-processor.js.map +0 -1
  144. package/enhancements/node/logger.d.ts +0 -29
  145. package/enhancements/node/logger.js +0 -65
  146. package/enhancements/node/logger.js.map +0 -1
  147. package/enhancements/node/omit.d.ts +0 -7
  148. package/enhancements/node/omit.js +0 -96
  149. package/enhancements/node/omit.js.map +0 -1
  150. package/enhancements/node/password.d.ts +0 -7
  151. package/enhancements/node/password.js +0 -64
  152. package/enhancements/node/password.js.map +0 -1
  153. package/enhancements/node/policy/check-utils.d.ts +0 -5
  154. package/enhancements/node/policy/check-utils.js +0 -87
  155. package/enhancements/node/policy/check-utils.js.map +0 -1
  156. package/enhancements/node/policy/constraint-solver.d.ts +0 -27
  157. package/enhancements/node/policy/constraint-solver.js +0 -164
  158. package/enhancements/node/policy/constraint-solver.js.map +0 -1
  159. package/enhancements/node/policy/handler.d.ts +0 -100
  160. package/enhancements/node/policy/handler.js +0 -1442
  161. package/enhancements/node/policy/handler.js.map +0 -1
  162. package/enhancements/node/policy/index.d.ts +0 -19
  163. package/enhancements/node/policy/index.js +0 -65
  164. package/enhancements/node/policy/index.js.map +0 -1
  165. package/enhancements/node/policy/policy-utils.d.ts +0 -181
  166. package/enhancements/node/policy/policy-utils.js +0 -1357
  167. package/enhancements/node/policy/policy-utils.js.map +0 -1
  168. package/enhancements/node/promise.d.ts +0 -15
  169. package/enhancements/node/promise.js +0 -99
  170. package/enhancements/node/promise.js.map +0 -1
  171. package/enhancements/node/proxy.d.ts +0 -120
  172. package/enhancements/node/proxy.js +0 -287
  173. package/enhancements/node/proxy.js.map +0 -1
  174. package/enhancements/node/query-utils.d.ts +0 -53
  175. package/enhancements/node/query-utils.js +0 -256
  176. package/enhancements/node/query-utils.js.map +0 -1
  177. package/enhancements/node/types.d.ts +0 -238
  178. package/enhancements/node/types.js +0 -3
  179. package/enhancements/node/types.js.map +0 -1
  180. package/enhancements/node/utils.d.ts +0 -11
  181. package/enhancements/node/utils.js +0 -49
  182. package/enhancements/node/utils.js.map +0 -1
  183. package/enhancements/node/where-visitor.d.ts +0 -32
  184. package/enhancements/node/where-visitor.js +0 -86
  185. package/enhancements/node/where-visitor.js.map +0 -1
  186. package/error.d.ts +0 -11
  187. package/error.js +0 -22
  188. package/error.js.map +0 -1
  189. package/index.d.ts +0 -7
  190. package/index.js +0 -24
  191. package/index.js.map +0 -1
  192. package/model-meta.d.ts +0 -1
  193. package/model-meta.js +0 -10
  194. package/models.d.ts +0 -1
  195. package/models.js +0 -1
  196. package/types.d.ts +0 -180
  197. package/types.js +0 -4
  198. package/types.js.map +0 -1
  199. package/validation.d.ts +0 -24
  200. package/validation.js +0 -52
  201. package/validation.js.map +0 -1
  202. package/version.d.ts +0 -5
  203. package/version.js +0 -35
  204. package/version.js.map +0 -1
  205. package/zod/index.d.ts +0 -3
  206. package/zod/index.js +0 -5
  207. package/zod/input.d.ts +0 -1
  208. package/zod/input.js +0 -8
  209. package/zod/models.d.ts +0 -1
  210. package/zod/models.js +0 -8
  211. package/zod/objects.d.ts +0 -1
  212. package/zod/objects.js +0 -8
  213. package/zod-utils.d.ts +0 -12
  214. package/zod-utils.js +0 -97
  215. package/zod-utils.js.map +0 -1
@@ -1,1294 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.DelegateProxyHandler = void 0;
16
- exports.withDelegate = withDelegate;
17
- /* eslint-disable @typescript-eslint/no-explicit-any */
18
- const deepmerge_1 = __importDefault(require("deepmerge"));
19
- const is_plain_object_1 = require("is-plain-object");
20
- const lower_case_first_1 = require("lower-case-first");
21
- const traverse_1 = __importDefault(require("traverse"));
22
- const constants_1 = require("../../constants");
23
- const cross_1 = require("../../cross");
24
- const logger_1 = require("./logger");
25
- const proxy_1 = require("./proxy");
26
- const query_utils_1 = require("./query-utils");
27
- const utils_1 = require("./utils");
28
- function withDelegate(prisma, options, context) {
29
- return (0, proxy_1.makeProxy)(prisma, options.modelMeta, (_prisma, model) => new DelegateProxyHandler(_prisma, model, options, context), 'delegate');
30
- }
31
- class DelegateProxyHandler extends proxy_1.DefaultPrismaProxyHandler {
32
- constructor(prisma, model, options, context) {
33
- super(prisma, model, options);
34
- this.context = context;
35
- this.logger = new logger_1.Logger(prisma);
36
- this.queryUtils = new query_utils_1.QueryUtils(prisma, this.options);
37
- }
38
- // #region find
39
- findFirst(args) {
40
- return this.doFind(this.prisma, this.model, 'findFirst', args);
41
- }
42
- findFirstOrThrow(args) {
43
- return this.doFind(this.prisma, this.model, 'findFirstOrThrow', args);
44
- }
45
- findUnique(args) {
46
- return this.doFind(this.prisma, this.model, 'findUnique', args);
47
- }
48
- findUniqueOrThrow(args) {
49
- return this.doFind(this.prisma, this.model, 'findUniqueOrThrow', args);
50
- }
51
- findMany(args) {
52
- return __awaiter(this, void 0, void 0, function* () {
53
- return this.doFind(this.prisma, this.model, 'findMany', args);
54
- });
55
- }
56
- doFind(db, model, method, args) {
57
- const _superIndex = name => super[name];
58
- return __awaiter(this, void 0, void 0, function* () {
59
- if (!this.involvesDelegateModel(model)) {
60
- return _superIndex(method).call(this, args);
61
- }
62
- args = args ? (0, cross_1.clone)(args) : {};
63
- this.injectWhereHierarchy(model, args === null || args === void 0 ? void 0 : args.where);
64
- yield this.injectSelectIncludeHierarchy(model, args);
65
- // discriminator field is needed during post process to determine the
66
- // actual concrete model type
67
- this.ensureDiscriminatorSelection(model, args);
68
- if (args.orderBy) {
69
- // `orderBy` may contain fields from base types
70
- (0, cross_1.enumerate)(args.orderBy).forEach((item) => this.injectWhereHierarchy(model, item));
71
- }
72
- if (this.options.logPrismaQuery) {
73
- this.logger.info(`[delegate] \`${method}\` ${this.getModelName(model)}: ${(0, utils_1.formatObject)(args)}`);
74
- }
75
- const entity = yield db[model][method](args);
76
- if (Array.isArray(entity)) {
77
- return entity.map((item) => this.assembleHierarchy(model, item));
78
- }
79
- else {
80
- return this.assembleHierarchy(model, entity);
81
- }
82
- });
83
- }
84
- ensureDiscriminatorSelection(model, args) {
85
- const modelInfo = (0, cross_1.getModelInfo)(this.options.modelMeta, model);
86
- if (!(modelInfo === null || modelInfo === void 0 ? void 0 : modelInfo.discriminator)) {
87
- return;
88
- }
89
- if (args.select && typeof args.select === 'object') {
90
- args.select[modelInfo.discriminator] = true;
91
- return;
92
- }
93
- if (args.omit && typeof args.omit === 'object') {
94
- args.omit[modelInfo.discriminator] = false;
95
- return;
96
- }
97
- }
98
- injectWhereHierarchy(model, where) {
99
- if (!where || !(0, is_plain_object_1.isPlainObject)(where)) {
100
- return;
101
- }
102
- Object.entries(where).forEach(([field, value]) => {
103
- if (['AND', 'OR', 'NOT'].includes(field)) {
104
- // recurse into logical group
105
- (0, cross_1.enumerate)(value).forEach((item) => this.injectWhereHierarchy(model, item));
106
- return;
107
- }
108
- const fieldInfo = (0, cross_1.resolveField)(this.options.modelMeta, model, field);
109
- if (!(fieldInfo === null || fieldInfo === void 0 ? void 0 : fieldInfo.inheritedFrom)) {
110
- // not an inherited field, inject and continue
111
- if (fieldInfo === null || fieldInfo === void 0 ? void 0 : fieldInfo.isDataModel) {
112
- this.injectWhereHierarchy(fieldInfo.type, value);
113
- }
114
- return;
115
- }
116
- let base = this.getBaseModel(model);
117
- let target = where;
118
- while (base) {
119
- const baseRelationName = this.makeAuxRelationName(base);
120
- // prepare base layer where
121
- let thisLayer;
122
- if (target[baseRelationName]) {
123
- thisLayer = target[baseRelationName];
124
- }
125
- else {
126
- thisLayer = target[baseRelationName] = {};
127
- }
128
- if (base.name === fieldInfo.inheritedFrom) {
129
- if (fieldInfo.isDataModel) {
130
- this.injectWhereHierarchy(base.name, value);
131
- }
132
- thisLayer[field] = value;
133
- delete where[field];
134
- break;
135
- }
136
- else {
137
- target = thisLayer;
138
- base = this.getBaseModel(base.name);
139
- }
140
- }
141
- });
142
- }
143
- injectSelectIncludeHierarchy(model, args) {
144
- return __awaiter(this, void 0, void 0, function* () {
145
- if (!args || typeof args !== 'object') {
146
- return;
147
- }
148
- // there're two cases where we need to inject polymorphic base hierarchy for fields
149
- // defined in base models
150
- // 1. base fields mentioned in select/include clause
151
- // { select: { fieldFromBase: true } } => { select: { delegate_aux_[Base]: { fieldFromBase: true } } }
152
- // 2. base fields mentioned in _count select/include clause
153
- // { select: { _count: { select: { fieldFromBase: true } } } } => { select: { delegate_aux_[Base]: { select: { _count: { select: { fieldFromBase: true } } } } } }
154
- //
155
- // Note that although structurally similar, we need to correctly deal with different injection location of the "delegate_aux" hierarchy
156
- // selectors for the above two cases
157
- const selectors = [
158
- // regular select: { select: { field: true } }
159
- (payload) => ({ data: payload.select, kind: 'select', isCount: false }),
160
- // regular include: { include: { field: true } }
161
- (payload) => ({ data: payload.include, kind: 'include', isCount: false }),
162
- // select _count: { select: { _count: { select: { field: true } } } }
163
- (payload) => {
164
- var _a, _b;
165
- return ({
166
- data: (_b = (_a = payload.select) === null || _a === void 0 ? void 0 : _a._count) === null || _b === void 0 ? void 0 : _b.select,
167
- kind: 'select',
168
- isCount: true,
169
- });
170
- },
171
- // include _count: { include: { _count: { select: { field: true } } } }
172
- (payload) => {
173
- var _a, _b;
174
- return ({
175
- data: (_b = (_a = payload.include) === null || _a === void 0 ? void 0 : _a._count) === null || _b === void 0 ? void 0 : _b.select,
176
- kind: 'include',
177
- isCount: true,
178
- });
179
- },
180
- ];
181
- for (const selector of selectors) {
182
- const { data, kind, isCount } = selector(args);
183
- if (!data || typeof data !== 'object') {
184
- continue;
185
- }
186
- for (const [field, value] of Object.entries(data)) {
187
- const fieldInfo = (0, cross_1.resolveField)(this.options.modelMeta, model, field);
188
- if (!fieldInfo) {
189
- continue;
190
- }
191
- if (this.isDelegateOrDescendantOfDelegate(fieldInfo === null || fieldInfo === void 0 ? void 0 : fieldInfo.type) && value) {
192
- // delegate model, recursively inject hierarchy
193
- if (data[field]) {
194
- if (data[field] === true) {
195
- // make sure the payload is an object
196
- data[field] = {};
197
- }
198
- yield this.injectSelectIncludeHierarchy(fieldInfo.type, data[field]);
199
- }
200
- }
201
- // refetch the field select/include value because it may have been
202
- // updated during injection
203
- const fieldValue = data[field];
204
- if (fieldValue !== undefined) {
205
- if (fieldValue.orderBy) {
206
- // `orderBy` may contain fields from base types
207
- (0, cross_1.enumerate)(fieldValue.orderBy).forEach((item) => this.injectWhereHierarchy(fieldInfo.type, item));
208
- }
209
- let injected = false;
210
- if (!isCount) {
211
- // regular select/include injection
212
- injected = yield this.injectBaseFieldSelect(model, field, fieldValue, args, kind);
213
- if (injected) {
214
- // if injected, remove the field from the original payload
215
- delete data[field];
216
- }
217
- }
218
- else {
219
- // _count select/include injection, inject into an empty payload and then merge to the proper location
220
- const injectTarget = { [kind]: {} };
221
- injected = yield this.injectBaseFieldSelect(model, field, fieldValue, injectTarget, kind, true);
222
- if (injected) {
223
- // if injected, remove the field from the original payload
224
- delete data[field];
225
- if (Object.keys(data).length === 0) {
226
- // if the original "_count" payload becomes empty, remove it
227
- delete args[kind]['_count'];
228
- }
229
- // finally merge the injection into the original payload
230
- const merged = (0, deepmerge_1.default)(args[kind], injectTarget[kind]);
231
- args[kind] = merged;
232
- }
233
- }
234
- if (!injected && fieldInfo.isDataModel) {
235
- let nextValue = fieldValue;
236
- if (nextValue === true) {
237
- // make sure the payload is an object
238
- data[field] = nextValue = {};
239
- }
240
- yield this.injectSelectIncludeHierarchy(fieldInfo.type, nextValue);
241
- }
242
- }
243
- }
244
- }
245
- if (!args.select) {
246
- // include base models upwards
247
- this.injectBaseIncludeRecursively(model, args);
248
- // include sub models downwards
249
- yield this.injectConcreteIncludeRecursively(model, args);
250
- }
251
- });
252
- }
253
- buildSelectIncludeHierarchy(model_1, args_1) {
254
- return __awaiter(this, arguments, void 0, function* (model, args, includeConcreteFields = true) {
255
- args = (0, cross_1.clone)(args);
256
- const selectInclude = this.extractSelectInclude(args) || {};
257
- if (selectInclude.select && typeof selectInclude.select === 'object') {
258
- Object.entries(selectInclude.select).forEach(([field, value]) => {
259
- if (value) {
260
- if (this.injectBaseFieldSelect(model, field, value, selectInclude, 'select')) {
261
- delete selectInclude.select[field];
262
- }
263
- }
264
- });
265
- }
266
- else if (selectInclude.include && typeof selectInclude.include === 'object') {
267
- Object.entries(selectInclude.include).forEach(([field, value]) => {
268
- if (value) {
269
- if (this.injectBaseFieldSelect(model, field, value, selectInclude, 'include')) {
270
- delete selectInclude.include[field];
271
- }
272
- }
273
- });
274
- }
275
- if (!selectInclude.select) {
276
- this.injectBaseIncludeRecursively(model, selectInclude);
277
- if (includeConcreteFields) {
278
- yield this.injectConcreteIncludeRecursively(model, selectInclude);
279
- }
280
- }
281
- return selectInclude;
282
- });
283
- }
284
- injectBaseFieldSelect(model, field, value, selectInclude, context, forCount = false // if the injection is for a "{ _count: { select: { field: true } } }" payload
285
- ) {
286
- const fieldInfo = (0, cross_1.resolveField)(this.options.modelMeta, model, field);
287
- if (!(fieldInfo === null || fieldInfo === void 0 ? void 0 : fieldInfo.inheritedFrom)) {
288
- return false;
289
- }
290
- let base = this.getBaseModel(model);
291
- let target = selectInclude;
292
- while (base) {
293
- const baseRelationName = this.makeAuxRelationName(base);
294
- // prepare base layer select/include
295
- let thisLayer;
296
- if (target.include) {
297
- thisLayer = target.include;
298
- }
299
- else if (target.select) {
300
- thisLayer = target.select;
301
- }
302
- else {
303
- thisLayer = target.select = {};
304
- }
305
- if (base.name === fieldInfo.inheritedFrom) {
306
- if (!thisLayer[baseRelationName]) {
307
- thisLayer[baseRelationName] = { [context]: {} };
308
- }
309
- if (forCount) {
310
- // { _count: { select: { field: true } } } => { delegate_aux_[Base]: { select: { _count: { select: { field: true } } } } }
311
- if (!thisLayer[baseRelationName][context]['_count'] ||
312
- typeof thisLayer[baseRelationName][context] !== 'object') {
313
- thisLayer[baseRelationName][context]['_count'] = {};
314
- }
315
- thisLayer[baseRelationName][context]['_count'] = (0, deepmerge_1.default)(thisLayer[baseRelationName][context]['_count'], { select: { [field]: value } });
316
- }
317
- else {
318
- // { select: { field: true } } => { delegate_aux_[Base]: { select: { field: true } } }
319
- thisLayer[baseRelationName][context][field] = value;
320
- }
321
- break;
322
- }
323
- else {
324
- if (!thisLayer[baseRelationName]) {
325
- thisLayer[baseRelationName] = { select: {} };
326
- }
327
- target = thisLayer[baseRelationName];
328
- base = this.getBaseModel(base.name);
329
- }
330
- }
331
- return true;
332
- }
333
- injectBaseIncludeRecursively(model, selectInclude) {
334
- const base = this.getBaseModel(model);
335
- if (!base) {
336
- return;
337
- }
338
- const baseRelationName = this.makeAuxRelationName(base);
339
- if (selectInclude.select) {
340
- selectInclude.include = Object.assign({ [baseRelationName]: {} }, selectInclude.select);
341
- delete selectInclude.select;
342
- }
343
- else {
344
- selectInclude.include = Object.assign({ [baseRelationName]: {} }, selectInclude.include);
345
- }
346
- this.injectBaseIncludeRecursively(base.name, selectInclude.include[baseRelationName]);
347
- }
348
- injectConcreteIncludeRecursively(model, selectInclude) {
349
- return __awaiter(this, void 0, void 0, function* () {
350
- const modelInfo = (0, cross_1.getModelInfo)(this.options.modelMeta, model);
351
- if (!modelInfo) {
352
- return;
353
- }
354
- // get sub models of this model
355
- const subModels = Object.values(this.options.modelMeta.models).filter((m) => { var _a; return (_a = m.baseTypes) === null || _a === void 0 ? void 0 : _a.includes(modelInfo.name); });
356
- for (const subModel of subModels) {
357
- // include sub model relation field
358
- const subRelationName = this.makeAuxRelationName(subModel);
359
- // create a payload to include the sub model relation
360
- const includePayload = yield this.createConcreteRelationIncludePayload(subModel.name);
361
- if (selectInclude.select) {
362
- selectInclude.include = Object.assign({ [subRelationName]: includePayload }, selectInclude.select);
363
- delete selectInclude.select;
364
- }
365
- else {
366
- selectInclude.include = Object.assign({ [subRelationName]: includePayload }, selectInclude.include);
367
- }
368
- yield this.injectConcreteIncludeRecursively(subModel.name, selectInclude.include[subRelationName]);
369
- }
370
- });
371
- }
372
- createConcreteRelationIncludePayload(model) {
373
- return __awaiter(this, void 0, void 0, function* () {
374
- let result = {};
375
- if (this.options.processIncludeRelationPayload) {
376
- // use the callback in options to process the include payload, so enhancements
377
- // like 'policy' can do extra work (e.g., inject policy rules)
378
- // TODO: this causes both delegate base's policy rules and concrete model's rules to be injected,
379
- // which is not wrong but redundant
380
- yield this.options.processIncludeRelationPayload(this.prisma, model, result, this.options, this.context);
381
- const properSelectIncludeHierarchy = yield this.buildSelectIncludeHierarchy(model, result, false);
382
- result = Object.assign(Object.assign({}, result), properSelectIncludeHierarchy);
383
- }
384
- return result;
385
- });
386
- }
387
- // #endregion
388
- // #region create
389
- create(args) {
390
- const _super = Object.create(null, {
391
- create: { get: () => super.create }
392
- });
393
- return __awaiter(this, void 0, void 0, function* () {
394
- if (!args) {
395
- throw (0, utils_1.prismaClientValidationError)(this.prisma, this.options.prismaModule, 'query argument is required');
396
- }
397
- if (!args.data) {
398
- throw (0, utils_1.prismaClientValidationError)(this.prisma, this.options.prismaModule, 'data field is required in query argument');
399
- }
400
- this.sanitizeMutationPayload(args.data);
401
- if ((0, cross_1.isDelegateModel)(this.options.modelMeta, this.model)) {
402
- throw (0, utils_1.prismaClientValidationError)(this.prisma, this.options.prismaModule, `Model "${this.model}" is a delegate and cannot be created directly`);
403
- }
404
- if (!this.involvesDelegateModel(this.model)) {
405
- return _super.create.call(this, args);
406
- }
407
- return this.doCreate(this.prisma, this.model, args);
408
- });
409
- }
410
- sanitizeMutationPayload(data) {
411
- if (!data) {
412
- return;
413
- }
414
- const prisma = this.prisma;
415
- const prismaModule = this.options.prismaModule;
416
- (0, traverse_1.default)(data).forEach(function () {
417
- var _a;
418
- if ((_a = this.key) === null || _a === void 0 ? void 0 : _a.startsWith(constants_1.DELEGATE_AUX_RELATION_PREFIX)) {
419
- throw (0, utils_1.prismaClientValidationError)(prisma, prismaModule, `Auxiliary relation field "${this.key}" cannot be set directly`);
420
- }
421
- });
422
- }
423
- createMany(args) {
424
- if (!args) {
425
- throw (0, utils_1.prismaClientValidationError)(this.prisma, this.options.prismaModule, 'query argument is required');
426
- }
427
- if (!args.data) {
428
- throw (0, utils_1.prismaClientValidationError)(this.prisma, this.options.prismaModule, 'data field is required in query argument');
429
- }
430
- this.sanitizeMutationPayload(args.data);
431
- if (!this.involvesDelegateModel(this.model)) {
432
- return super.createMany(args);
433
- }
434
- if (this.isDelegateOrDescendantOfDelegate(this.model) && args.skipDuplicates) {
435
- throw (0, utils_1.prismaClientValidationError)(this.prisma, this.options.prismaModule, '`createMany` with `skipDuplicates` set to true is not supported for delegated models');
436
- }
437
- // `createMany` doesn't support nested create, which is needed for creating entities
438
- // inheriting a delegate base, so we need to convert it to a regular `create` here.
439
- // Note that the main difference is `create` doesn't support `skipDuplicates` as
440
- // `createMany` does.
441
- return this.queryUtils.transaction(this.prisma, (tx) => __awaiter(this, void 0, void 0, function* () {
442
- const r = yield Promise.all((0, cross_1.enumerate)(args.data).map((item) => __awaiter(this, void 0, void 0, function* () {
443
- return this.doCreate(tx, this.model, { data: item });
444
- })));
445
- return { count: r.length };
446
- }));
447
- }
448
- createManyAndReturn(args) {
449
- if (!args) {
450
- throw (0, utils_1.prismaClientValidationError)(this.prisma, this.options.prismaModule, 'query argument is required');
451
- }
452
- if (!args.data) {
453
- throw (0, utils_1.prismaClientValidationError)(this.prisma, this.options.prismaModule, 'data field is required in query argument');
454
- }
455
- this.sanitizeMutationPayload(args.data);
456
- if (!this.involvesDelegateModel(this.model)) {
457
- return super.createManyAndReturn(args);
458
- }
459
- if (this.isDelegateOrDescendantOfDelegate(this.model) && args.skipDuplicates) {
460
- throw (0, utils_1.prismaClientValidationError)(this.prisma, this.options.prismaModule, '`createManyAndReturn` with `skipDuplicates` set to true is not supported for delegated models');
461
- }
462
- // `createManyAndReturn` doesn't support nested create, which is needed for creating entities
463
- // inheriting a delegate base, so we need to convert it to a regular `create` here.
464
- // Note that the main difference is `create` doesn't support `skipDuplicates` as
465
- // `createManyAndReturn` does.
466
- return this.queryUtils.transaction(this.prisma, (tx) => __awaiter(this, void 0, void 0, function* () {
467
- const r = yield Promise.all((0, cross_1.enumerate)(args.data).map((item) => __awaiter(this, void 0, void 0, function* () {
468
- return this.doCreate(tx, this.model, { data: item, select: args.select });
469
- })));
470
- return r;
471
- }));
472
- }
473
- doCreate(db, model, args) {
474
- return __awaiter(this, void 0, void 0, function* () {
475
- args = (0, cross_1.clone)(args);
476
- yield this.injectCreateHierarchy(model, args);
477
- yield this.injectSelectIncludeHierarchy(model, args);
478
- if (this.options.logPrismaQuery) {
479
- this.logger.info(`[delegate] \`create\` ${this.getModelName(model)}: ${(0, utils_1.formatObject)(args)}`);
480
- }
481
- const result = yield db[model].create(args);
482
- return this.assembleHierarchy(model, result);
483
- });
484
- }
485
- injectCreateHierarchy(model, args) {
486
- return __awaiter(this, void 0, void 0, function* () {
487
- const visitor = new cross_1.NestedWriteVisitor(this.options.modelMeta, {
488
- create: (model, args, _context) => {
489
- this.doProcessCreatePayload(model, args);
490
- },
491
- createMany: (model, args, context) => {
492
- // `createMany` doesn't support nested create, which is needed for creating entities
493
- // inheriting a delegate base, so we need to convert it to a regular `create` here.
494
- // Note that the main difference is `create` doesn't support `skipDuplicates` as
495
- // `createMany` does.
496
- var _a;
497
- if (this.isDelegateOrDescendantOfDelegate(model)) {
498
- if (args.skipDuplicates) {
499
- throw (0, utils_1.prismaClientValidationError)(this.prisma, this.options.prismaModule, '`createMany` with `skipDuplicates` set to true is not supported for delegated models');
500
- }
501
- // convert to regular `create`
502
- let createPayload = (_a = context.parent.create) !== null && _a !== void 0 ? _a : [];
503
- if (!Array.isArray(createPayload)) {
504
- createPayload = [createPayload];
505
- }
506
- for (const item of (0, cross_1.enumerate)(args.data)) {
507
- this.doProcessCreatePayload(model, item);
508
- createPayload.push(item);
509
- }
510
- context.parent.create = createPayload;
511
- delete context.parent['createMany'];
512
- }
513
- },
514
- });
515
- yield visitor.visit(model, 'create', args);
516
- });
517
- }
518
- doProcessCreatePayload(model, args) {
519
- if (!args) {
520
- return;
521
- }
522
- this.ensureBaseCreateHierarchy(model, args);
523
- for (const [field, value] of Object.entries(args)) {
524
- const fieldInfo = (0, cross_1.resolveField)(this.options.modelMeta, model, field);
525
- if (fieldInfo === null || fieldInfo === void 0 ? void 0 : fieldInfo.inheritedFrom) {
526
- this.injectBaseFieldData(model, fieldInfo, value, args, 'create');
527
- delete args[field];
528
- }
529
- }
530
- }
531
- // ensure the full nested "create" structure is created for base types
532
- ensureBaseCreateHierarchy(model, args) {
533
- let curr = args;
534
- let base = this.getBaseModel(model);
535
- let sub = this.getModelInfo(model);
536
- const hasDelegateBase = !!base;
537
- while (base) {
538
- const baseRelationName = this.makeAuxRelationName(base);
539
- if (!curr[baseRelationName]) {
540
- curr[baseRelationName] = {};
541
- }
542
- if (!curr[baseRelationName].create) {
543
- curr[baseRelationName].create = {};
544
- if (base.discriminator) {
545
- // set discriminator field
546
- curr[baseRelationName].create[base.discriminator] = sub.name;
547
- }
548
- }
549
- // Look for base id field assignments in the current level, and push
550
- // them down to the base level
551
- for (const idField of (0, cross_1.getIdFields)(this.options.modelMeta, base.name)) {
552
- if (curr[idField.name] !== undefined) {
553
- curr[baseRelationName].create[idField.name] = curr[idField.name];
554
- delete curr[idField.name];
555
- }
556
- }
557
- curr = curr[baseRelationName].create;
558
- sub = base;
559
- base = this.getBaseModel(base.name);
560
- }
561
- if (hasDelegateBase) {
562
- // A delegate base model creation is added, this can be incompatible if
563
- // the user-provided payload assigns foreign keys directly, because Prisma
564
- // doesn't permit mixed "checked" and "unchecked" fields in a payload.
565
- //
566
- // {
567
- // delegate_aux_base: { ... },
568
- // [fkField]: value // <- this is not compatible
569
- // }
570
- //
571
- // We need to convert foreign key assignments to `connect`.
572
- this.fkAssignmentToConnect(model, args);
573
- }
574
- }
575
- // convert foreign key assignments to `connect` payload
576
- // e.g.: { authorId: value } -> { author: { connect: { id: value } } }
577
- fkAssignmentToConnect(model, args) {
578
- const keysToDelete = [];
579
- for (const [key, value] of Object.entries(args)) {
580
- if (value === undefined) {
581
- continue;
582
- }
583
- const fieldInfo = this.queryUtils.getModelField(model, key);
584
- if (!(fieldInfo === null || fieldInfo === void 0 ? void 0 : fieldInfo.inheritedFrom) && // fields from delegate base are handled outside
585
- (fieldInfo === null || fieldInfo === void 0 ? void 0 : fieldInfo.isForeignKey)) {
586
- const relationInfo = this.queryUtils.getRelationForForeignKey(model, key);
587
- if (relationInfo) {
588
- // turn { [fk]: value } into { [relation]: { connect: { [id]: value } } }
589
- const relationName = relationInfo.relation.name;
590
- if (!args[relationName]) {
591
- args[relationName] = {};
592
- }
593
- if (!args[relationName].connect) {
594
- args[relationName].connect = {};
595
- }
596
- if (!(relationInfo.idField in args[relationName].connect)) {
597
- args[relationName].connect[relationInfo.idField] = value;
598
- keysToDelete.push(key);
599
- }
600
- }
601
- }
602
- }
603
- keysToDelete.forEach((key) => delete args[key]);
604
- }
605
- // inject field data that belongs to base type into proper nesting structure
606
- injectBaseFieldData(model, fieldInfo, value, args, mode) {
607
- let base = this.getBaseModel(model);
608
- let curr = args;
609
- while (base) {
610
- if (base.discriminator === fieldInfo.name) {
611
- throw (0, utils_1.prismaClientValidationError)(this.prisma, this.options.prismaModule, `fields "${fieldInfo.name}" is a discriminator and cannot be set directly`);
612
- }
613
- const baseRelationName = this.makeAuxRelationName(base);
614
- if (!curr[baseRelationName]) {
615
- curr[baseRelationName] = {};
616
- }
617
- if (!curr[baseRelationName][mode]) {
618
- curr[baseRelationName][mode] = {};
619
- }
620
- curr = curr[baseRelationName][mode];
621
- if (fieldInfo.inheritedFrom === base.name) {
622
- curr[fieldInfo.name] = value;
623
- break;
624
- }
625
- base = this.getBaseModel(base.name);
626
- }
627
- }
628
- // #endregion
629
- // #region update
630
- update(args) {
631
- if (!args) {
632
- throw (0, utils_1.prismaClientValidationError)(this.prisma, this.options.prismaModule, 'query argument is required');
633
- }
634
- if (!args.data) {
635
- throw (0, utils_1.prismaClientValidationError)(this.prisma, this.options.prismaModule, 'data field is required in query argument');
636
- }
637
- this.sanitizeMutationPayload(args.data);
638
- if (!this.involvesDelegateModel(this.model)) {
639
- return super.update(args);
640
- }
641
- return this.queryUtils.transaction(this.prisma, (tx) => this.doUpdate(tx, this.model, args));
642
- }
643
- updateMany(args) {
644
- const _super = Object.create(null, {
645
- updateMany: { get: () => super.updateMany }
646
- });
647
- return __awaiter(this, void 0, void 0, function* () {
648
- if (!args) {
649
- throw (0, utils_1.prismaClientValidationError)(this.prisma, this.options.prismaModule, 'query argument is required');
650
- }
651
- if (!args.data) {
652
- throw (0, utils_1.prismaClientValidationError)(this.prisma, this.options.prismaModule, 'data field is required in query argument');
653
- }
654
- this.sanitizeMutationPayload(args.data);
655
- if (!this.involvesDelegateModel(this.model)) {
656
- return _super.updateMany.call(this, args);
657
- }
658
- let simpleUpdateMany = Object.keys(args.data).every((key) => {
659
- // check if the `data` clause involves base fields
660
- const fieldInfo = (0, cross_1.resolveField)(this.options.modelMeta, this.model, key);
661
- return !(fieldInfo === null || fieldInfo === void 0 ? void 0 : fieldInfo.inheritedFrom);
662
- });
663
- // check if there are any `@updatedAt` fields from delegate base models
664
- if (simpleUpdateMany) {
665
- if (this.getUpdatedAtFromDelegateBases(this.model).length > 0) {
666
- simpleUpdateMany = false;
667
- }
668
- }
669
- return this.queryUtils.transaction(this.prisma, (tx) => this.doUpdateMany(tx, this.model, args, simpleUpdateMany));
670
- });
671
- }
672
- upsert(args) {
673
- const _super = Object.create(null, {
674
- upsert: { get: () => super.upsert }
675
- });
676
- return __awaiter(this, void 0, void 0, function* () {
677
- if (!args) {
678
- throw (0, utils_1.prismaClientValidationError)(this.prisma, this.options.prismaModule, 'query argument is required');
679
- }
680
- if (!args.where) {
681
- throw (0, utils_1.prismaClientValidationError)(this.prisma, this.options.prismaModule, 'where field is required in query argument');
682
- }
683
- this.sanitizeMutationPayload(args.update);
684
- this.sanitizeMutationPayload(args.create);
685
- if ((0, cross_1.isDelegateModel)(this.options.modelMeta, this.model)) {
686
- throw (0, utils_1.prismaClientValidationError)(this.prisma, this.options.prismaModule, `Model "${this.model}" is a delegate and doesn't support upsert`);
687
- }
688
- if (!this.involvesDelegateModel(this.model)) {
689
- return _super.upsert.call(this, args);
690
- }
691
- args = (0, cross_1.clone)(args);
692
- this.injectWhereHierarchy(this.model, args === null || args === void 0 ? void 0 : args.where);
693
- yield this.injectSelectIncludeHierarchy(this.model, args);
694
- if (args.create) {
695
- this.doProcessCreatePayload(this.model, args.create);
696
- }
697
- if (args.update) {
698
- this.doProcessUpdatePayload(this.model, args.update);
699
- }
700
- if (this.options.logPrismaQuery) {
701
- this.logger.info(`[delegate] \`upsert\` ${this.getModelName(this.model)}: ${(0, utils_1.formatObject)(args)}`);
702
- }
703
- const result = yield this.prisma[this.model].upsert(args);
704
- return this.assembleHierarchy(this.model, result);
705
- });
706
- }
707
- doUpdate(db, model, args) {
708
- return __awaiter(this, void 0, void 0, function* () {
709
- args = (0, cross_1.clone)(args);
710
- yield this.injectUpdateHierarchy(db, model, args);
711
- yield this.injectSelectIncludeHierarchy(model, args);
712
- if (this.options.logPrismaQuery) {
713
- this.logger.info(`[delegate] \`update\` ${this.getModelName(model)}: ${(0, utils_1.formatObject)(args)}`);
714
- }
715
- const result = yield db[model].update(args);
716
- return this.assembleHierarchy(model, result);
717
- });
718
- }
719
- doUpdateMany(db, model, args, simpleUpdateMany) {
720
- return __awaiter(this, void 0, void 0, function* () {
721
- var _a;
722
- if (simpleUpdateMany) {
723
- // do a direct `updateMany`
724
- args = (0, cross_1.clone)(args);
725
- yield this.injectUpdateHierarchy(db, model, args);
726
- if (this.options.logPrismaQuery) {
727
- this.logger.info(`[delegate] \`updateMany\` ${this.getModelName(model)}: ${(0, utils_1.formatObject)(args)}`);
728
- }
729
- return db[model].updateMany(args);
730
- }
731
- else {
732
- // translate to plain `update` for nested write into base fields
733
- const findArgs = {
734
- where: (0, cross_1.clone)((_a = args.where) !== null && _a !== void 0 ? _a : {}),
735
- select: this.queryUtils.makeIdSelection(model),
736
- };
737
- yield this.injectUpdateHierarchy(db, model, findArgs);
738
- if (this.options.logPrismaQuery) {
739
- this.logger.info(`[delegate] \`updateMany\` find candidates: ${this.getModelName(model)}: ${(0, utils_1.formatObject)(findArgs)}`);
740
- }
741
- const entities = yield db[model].findMany(findArgs);
742
- const updatePayload = { data: (0, cross_1.clone)(args.data), select: this.queryUtils.makeIdSelection(model) };
743
- yield this.injectUpdateHierarchy(db, model, updatePayload);
744
- const result = yield Promise.all(entities.map((entity) => {
745
- const updateArgs = Object.assign({ where: entity }, updatePayload);
746
- if (this.options.logPrismaQuery) {
747
- this.logger.info(`[delegate] \`updateMany\` update: ${this.getModelName(model)}: ${(0, utils_1.formatObject)(updateArgs)}`);
748
- }
749
- return db[model].update(updateArgs);
750
- }));
751
- return { count: result.length };
752
- }
753
- });
754
- }
755
- injectUpdateHierarchy(db, model, args) {
756
- return __awaiter(this, void 0, void 0, function* () {
757
- const visitor = new cross_1.NestedWriteVisitor(this.options.modelMeta, {
758
- update: (model, args, _context) => {
759
- this.injectWhereHierarchy(model, args === null || args === void 0 ? void 0 : args.where);
760
- this.doProcessUpdatePayload(model, args === null || args === void 0 ? void 0 : args.data);
761
- },
762
- updateMany: (model, args, context) => __awaiter(this, void 0, void 0, function* () {
763
- let simpleUpdateMany = Object.keys(args.data).every((key) => {
764
- // check if the `data` clause involves base fields
765
- const fieldInfo = (0, cross_1.resolveField)(this.options.modelMeta, model, key);
766
- return !(fieldInfo === null || fieldInfo === void 0 ? void 0 : fieldInfo.inheritedFrom);
767
- });
768
- // check if there are any `@updatedAt` fields from delegate base models
769
- if (simpleUpdateMany) {
770
- if (this.getUpdatedAtFromDelegateBases(model).length > 0) {
771
- simpleUpdateMany = false;
772
- }
773
- }
774
- if (simpleUpdateMany) {
775
- // check if the `where` clause involves base fields
776
- simpleUpdateMany = Object.keys(args.where || {}).every((key) => {
777
- const fieldInfo = (0, cross_1.resolveField)(this.options.modelMeta, model, key);
778
- return !(fieldInfo === null || fieldInfo === void 0 ? void 0 : fieldInfo.inheritedFrom);
779
- });
780
- }
781
- if (simpleUpdateMany) {
782
- this.injectWhereHierarchy(model, args === null || args === void 0 ? void 0 : args.where);
783
- this.doProcessUpdatePayload(model, args === null || args === void 0 ? void 0 : args.data);
784
- }
785
- else {
786
- const where = yield this.queryUtils.buildReversedQuery(db, context, false, false);
787
- yield this.queryUtils.transaction(db, (tx) => __awaiter(this, void 0, void 0, function* () {
788
- yield this.doUpdateMany(tx, model, Object.assign(Object.assign({}, args), { where }), simpleUpdateMany);
789
- }));
790
- delete context.parent['updateMany'];
791
- }
792
- }),
793
- upsert: (model, args, _context) => {
794
- this.injectWhereHierarchy(model, args === null || args === void 0 ? void 0 : args.where);
795
- if (args.create) {
796
- this.doProcessCreatePayload(model, args === null || args === void 0 ? void 0 : args.create);
797
- }
798
- if (args.update) {
799
- this.doProcessUpdatePayload(model, args === null || args === void 0 ? void 0 : args.update);
800
- }
801
- },
802
- create: (model, args, _context) => {
803
- if ((0, cross_1.isDelegateModel)(this.options.modelMeta, model)) {
804
- throw (0, utils_1.prismaClientValidationError)(this.prisma, this.options.prismaModule, `Model "${model}" is a delegate and cannot be created directly`);
805
- }
806
- this.doProcessCreatePayload(model, args);
807
- },
808
- createMany: (model, args, _context) => {
809
- if (args.skipDuplicates) {
810
- throw (0, utils_1.prismaClientValidationError)(this.prisma, this.options.prismaModule, '`createMany` with `skipDuplicates` set to true is not supported for delegated models');
811
- }
812
- for (const item of (0, cross_1.enumerate)(args === null || args === void 0 ? void 0 : args.data)) {
813
- this.doProcessCreatePayload(model, item);
814
- }
815
- },
816
- connect: (model, args, _context) => {
817
- this.injectWhereHierarchy(model, args);
818
- },
819
- connectOrCreate: (model, args, _context) => {
820
- this.injectWhereHierarchy(model, args.where);
821
- if (args.create) {
822
- this.doProcessCreatePayload(model, args.create);
823
- }
824
- },
825
- disconnect: (model, args, _context) => {
826
- this.injectWhereHierarchy(model, args);
827
- },
828
- set: (model, args, _context) => {
829
- this.injectWhereHierarchy(model, args);
830
- },
831
- delete: (model, _args, context) => __awaiter(this, void 0, void 0, function* () {
832
- const where = yield this.queryUtils.buildReversedQuery(db, context, false, false);
833
- yield this.queryUtils.transaction(db, (tx) => __awaiter(this, void 0, void 0, function* () {
834
- yield this.doDelete(tx, model, { where });
835
- }));
836
- delete context.parent['delete'];
837
- }),
838
- deleteMany: (model, _args, context) => __awaiter(this, void 0, void 0, function* () {
839
- const where = yield this.queryUtils.buildReversedQuery(db, context, false, false);
840
- yield this.queryUtils.transaction(db, (tx) => __awaiter(this, void 0, void 0, function* () {
841
- yield this.doDeleteMany(tx, model, where);
842
- }));
843
- delete context.parent['deleteMany'];
844
- }),
845
- });
846
- yield visitor.visit(model, 'update', args);
847
- });
848
- }
849
- doProcessUpdatePayload(model, data) {
850
- if (!data) {
851
- return;
852
- }
853
- for (const [field, value] of Object.entries(data)) {
854
- const fieldInfo = (0, cross_1.resolveField)(this.options.modelMeta, model, field);
855
- if (fieldInfo === null || fieldInfo === void 0 ? void 0 : fieldInfo.inheritedFrom) {
856
- this.injectBaseFieldData(model, fieldInfo, value, data, 'update');
857
- delete data[field];
858
- }
859
- }
860
- // if we're updating any field, we need to take care of updating `@updatedAt`
861
- // fields inherited from delegate base models
862
- if (Object.keys(data).length > 0) {
863
- const updatedAtFields = this.getUpdatedAtFromDelegateBases(model);
864
- for (const fieldInfo of updatedAtFields) {
865
- this.injectBaseFieldData(model, fieldInfo, new Date(), data, 'update');
866
- }
867
- }
868
- }
869
- // #endregion
870
- // #region delete
871
- delete(args) {
872
- if (!args) {
873
- throw (0, utils_1.prismaClientValidationError)(this.prisma, this.options.prismaModule, 'query argument is required');
874
- }
875
- if (!this.involvesDelegateModel(this.model)) {
876
- return super.delete(args);
877
- }
878
- return this.queryUtils.transaction(this.prisma, (tx) => __awaiter(this, void 0, void 0, function* () {
879
- const selectInclude = yield this.buildSelectIncludeHierarchy(this.model, args);
880
- // make sure id fields are selected
881
- const idFields = this.getIdFields(this.model);
882
- for (const idField of idFields) {
883
- if ((selectInclude === null || selectInclude === void 0 ? void 0 : selectInclude.select) && !(idField.name in selectInclude.select)) {
884
- selectInclude.select[idField.name] = true;
885
- }
886
- }
887
- const deleteArgs = Object.assign(Object.assign({}, (0, cross_1.clone)(args)), selectInclude);
888
- return this.doDelete(tx, this.model, deleteArgs);
889
- }));
890
- }
891
- deleteMany(args) {
892
- if (!this.involvesDelegateModel(this.model)) {
893
- return super.deleteMany(args);
894
- }
895
- return this.queryUtils.transaction(this.prisma, (tx) => this.doDeleteMany(tx, this.model, args === null || args === void 0 ? void 0 : args.where));
896
- }
897
- doDeleteMany(db, model, where) {
898
- return __awaiter(this, void 0, void 0, function* () {
899
- // query existing entities with id
900
- const idSelection = this.queryUtils.makeIdSelection(model);
901
- const findArgs = { where: (0, cross_1.clone)(where !== null && where !== void 0 ? where : {}), select: idSelection };
902
- this.injectWhereHierarchy(model, findArgs.where);
903
- if (this.options.logPrismaQuery) {
904
- this.logger.info(`[delegate] \`deleteMany\` find candidates: ${this.getModelName(model)}: ${(0, utils_1.formatObject)(findArgs)}`);
905
- }
906
- const entities = yield db[model].findMany(findArgs);
907
- // recursively delete base entities (they all have the same id values)
908
- yield Promise.all(entities.map((entity) => {
909
- let deleteFilter = entity;
910
- if (Object.keys(deleteFilter).length > 1) {
911
- // if the model has compound id fields, we need to compose a compound key filter,
912
- // otherwise calling Prisma's `delete` won't work
913
- deleteFilter = this.queryUtils.composeCompoundUniqueField(model, deleteFilter);
914
- }
915
- return this.doDelete(db, model, { where: deleteFilter });
916
- }));
917
- return { count: entities.length };
918
- });
919
- }
920
- deleteBaseRecursively(db, model, idValues) {
921
- return __awaiter(this, void 0, void 0, function* () {
922
- let base = this.getBaseModel(model);
923
- while (base) {
924
- let deleteFilter = idValues;
925
- if (Object.keys(idValues).length > 1) {
926
- // if the model has compound id fields, we need to compose a compound key filter,
927
- // otherwise calling Prisma's `delete` won't work
928
- deleteFilter = this.queryUtils.composeCompoundUniqueField(base.name, deleteFilter);
929
- }
930
- yield db[base.name].delete({ where: deleteFilter });
931
- base = this.getBaseModel(base.name);
932
- }
933
- });
934
- }
935
- doDelete(db_1, model_1, args_1) {
936
- return __awaiter(this, arguments, void 0, function* (db, model, args, readBack = true) {
937
- this.injectWhereHierarchy(model, args.where);
938
- yield this.injectSelectIncludeHierarchy(model, args);
939
- // read relation entities that need to be cascade deleted before deleting the main entity
940
- const cascadeDeletes = yield this.getRelationDelegateEntitiesForCascadeDelete(db, model, args.where);
941
- let result = undefined;
942
- if (cascadeDeletes.length > 0) {
943
- // we'll need to do cascade deletes of relations, so first
944
- // read the current entity before anything changes
945
- if (readBack) {
946
- result = yield this.doFind(db, model, 'findUnique', args);
947
- }
948
- // process cascade deletes of relations, this ensure their delegate base
949
- // entities are deleted as well
950
- yield Promise.all(cascadeDeletes.map(({ model, entity }) => this.doDelete(db, model, { where: entity }, false)));
951
- }
952
- if (this.options.logPrismaQuery) {
953
- this.logger.info(`[delegate] \`delete\` ${this.getModelName(model)}: ${(0, utils_1.formatObject)(args)}`);
954
- }
955
- const deleteResult = yield db[model].delete(args);
956
- if (!result) {
957
- result = this.assembleHierarchy(model, deleteResult);
958
- }
959
- // recursively delete base entities (they all have the same id values)
960
- const idValues = this.queryUtils.getEntityIds(model, deleteResult);
961
- yield this.deleteBaseRecursively(db, model, idValues);
962
- return result;
963
- });
964
- }
965
- getRelationDelegateEntitiesForCascadeDelete(db, model, where) {
966
- return __awaiter(this, void 0, void 0, function* () {
967
- if (!where || Object.keys(where).length === 0) {
968
- throw new Error('where clause is required for cascade delete');
969
- }
970
- const cascadeDeletes = [];
971
- const fields = (0, cross_1.getFields)(this.options.modelMeta, model);
972
- if (fields) {
973
- for (const fieldInfo of Object.values(fields)) {
974
- if (!fieldInfo.isDataModel) {
975
- continue;
976
- }
977
- if (fieldInfo.isRelationOwner) {
978
- // this side of the relation owns the foreign key,
979
- // so it won't cause cascade delete to the other side
980
- continue;
981
- }
982
- if (fieldInfo.backLink) {
983
- // get the opposite side of the relation
984
- const backLinkField = this.queryUtils.getModelField(fieldInfo.type, fieldInfo.backLink);
985
- if ((backLinkField === null || backLinkField === void 0 ? void 0 : backLinkField.isRelationOwner) && this.isFieldCascadeDelete(backLinkField)) {
986
- // if the opposite side of the relation is to be cascade deleted,
987
- // recursively delete the delegate base entities
988
- const relationModel = (0, cross_1.getModelInfo)(this.options.modelMeta, fieldInfo.type);
989
- if ((relationModel === null || relationModel === void 0 ? void 0 : relationModel.baseTypes) && relationModel.baseTypes.length > 0) {
990
- // the relation model has delegate base, cascade the delete to the base
991
- const relationEntities = yield db[relationModel.name].findMany({
992
- where: { [backLinkField.name]: where },
993
- select: this.queryUtils.makeIdSelection(relationModel.name),
994
- });
995
- relationEntities.forEach((entity) => {
996
- cascadeDeletes.push({ model: fieldInfo.type, entity });
997
- });
998
- }
999
- }
1000
- }
1001
- }
1002
- }
1003
- return cascadeDeletes;
1004
- });
1005
- }
1006
- isFieldCascadeDelete(fieldInfo) {
1007
- return fieldInfo.onDeleteAction === 'Cascade';
1008
- }
1009
- // #endregion
1010
- // #region aggregation
1011
- aggregate(args) {
1012
- if (!args) {
1013
- throw (0, utils_1.prismaClientValidationError)(this.prisma, this.options.prismaModule, 'query argument is required');
1014
- }
1015
- if (!this.involvesDelegateModel(this.model)) {
1016
- return super.aggregate(args);
1017
- }
1018
- // check if any aggregation operator is using fields from base
1019
- this.checkAggregationArgs('aggregate', args);
1020
- args = (0, cross_1.clone)(args);
1021
- if (args.cursor) {
1022
- this.injectWhereHierarchy(this.model, args.cursor);
1023
- }
1024
- if (args.orderBy) {
1025
- (0, cross_1.enumerate)(args.orderBy).forEach((item) => this.injectWhereHierarchy(this.model, item));
1026
- }
1027
- if (args.where) {
1028
- this.injectWhereHierarchy(this.model, args.where);
1029
- }
1030
- if (this.options.logPrismaQuery) {
1031
- this.logger.info(`[delegate] \`aggregate\` ${this.getModelName(this.model)}: ${(0, utils_1.formatObject)(args)}`);
1032
- }
1033
- return super.aggregate(args);
1034
- }
1035
- count(args) {
1036
- if (!this.involvesDelegateModel(this.model)) {
1037
- return super.count(args);
1038
- }
1039
- // check if count select is using fields from base
1040
- this.checkAggregationArgs('count', args);
1041
- args = (0, cross_1.clone)(args);
1042
- if (args === null || args === void 0 ? void 0 : args.cursor) {
1043
- this.injectWhereHierarchy(this.model, args.cursor);
1044
- }
1045
- if (args === null || args === void 0 ? void 0 : args.where) {
1046
- this.injectWhereHierarchy(this.model, args.where);
1047
- }
1048
- if (this.options.logPrismaQuery) {
1049
- this.logger.info(`[delegate] \`count\` ${this.getModelName(this.model)}: ${(0, utils_1.formatObject)(args)}`);
1050
- }
1051
- return super.count(args);
1052
- }
1053
- groupBy(args) {
1054
- if (!args) {
1055
- throw (0, utils_1.prismaClientValidationError)(this.prisma, this.options.prismaModule, 'query argument is required');
1056
- }
1057
- if (!this.involvesDelegateModel(this.model)) {
1058
- return super.groupBy(args);
1059
- }
1060
- // check if count select is using fields from base
1061
- this.checkAggregationArgs('groupBy', args);
1062
- if (args.by) {
1063
- for (const by of (0, cross_1.enumerate)(args.by)) {
1064
- const fieldInfo = (0, cross_1.resolveField)(this.options.modelMeta, this.model, by);
1065
- if (fieldInfo && fieldInfo.inheritedFrom) {
1066
- throw (0, utils_1.prismaClientValidationError)(this.prisma, this.options.prismaModule, `groupBy with fields from base type is not supported yet: "${by}"`);
1067
- }
1068
- }
1069
- }
1070
- args = (0, cross_1.clone)(args);
1071
- if (args.where) {
1072
- this.injectWhereHierarchy(this.model, args.where);
1073
- }
1074
- if (this.options.logPrismaQuery) {
1075
- this.logger.info(`[delegate] \`groupBy\` ${this.getModelName(this.model)}: ${(0, utils_1.formatObject)(args)}`);
1076
- }
1077
- return super.groupBy(args);
1078
- }
1079
- checkAggregationArgs(operation, args) {
1080
- if (!args) {
1081
- return;
1082
- }
1083
- for (const op of ['_count', '_sum', '_avg', '_min', '_max', 'select', 'having']) {
1084
- if (args[op] && typeof args[op] === 'object') {
1085
- for (const field of Object.keys(args[op])) {
1086
- const fieldInfo = (0, cross_1.resolveField)(this.options.modelMeta, this.model, field);
1087
- if (fieldInfo === null || fieldInfo === void 0 ? void 0 : fieldInfo.inheritedFrom) {
1088
- throw (0, utils_1.prismaClientValidationError)(this.prisma, this.options.prismaModule, `${operation} with fields from base type is not supported yet: "${field}"`);
1089
- }
1090
- }
1091
- }
1092
- }
1093
- }
1094
- // #endregion
1095
- // #region utils
1096
- extractSelectInclude(args) {
1097
- if (!args) {
1098
- return undefined;
1099
- }
1100
- args = (0, cross_1.clone)(args);
1101
- return 'select' in args
1102
- ? { select: args['select'] }
1103
- : 'include' in args
1104
- ? { include: args['include'] }
1105
- : undefined;
1106
- }
1107
- makeAuxRelationName(model) {
1108
- var _a;
1109
- const name = `${constants_1.DELEGATE_AUX_RELATION_PREFIX}_${(0, lower_case_first_1.lowerCaseFirst)(model.name)}`;
1110
- // make sure we look up into short name map to see if it's truncated
1111
- const shortName = (_a = this.options.modelMeta.shortNameMap) === null || _a === void 0 ? void 0 : _a[name];
1112
- return shortName !== null && shortName !== void 0 ? shortName : name;
1113
- }
1114
- getModelName(model) {
1115
- const info = (0, cross_1.getModelInfo)(this.options.modelMeta, model, true);
1116
- return info.name;
1117
- }
1118
- getIdFields(model) {
1119
- const idFields = (0, cross_1.getIdFields)(this.options.modelMeta, model);
1120
- if (idFields && idFields.length > 0) {
1121
- return idFields;
1122
- }
1123
- const base = this.getBaseModel(model);
1124
- return base ? this.getIdFields(base.name) : [];
1125
- }
1126
- getModelInfo(model) {
1127
- return (0, cross_1.getModelInfo)(this.options.modelMeta, model, true);
1128
- }
1129
- getBaseModel(model) {
1130
- const baseNames = (0, cross_1.getModelInfo)(this.options.modelMeta, model, true).baseTypes;
1131
- if (!baseNames) {
1132
- return undefined;
1133
- }
1134
- if (baseNames.length > 1) {
1135
- throw new Error('Multi-inheritance is not supported');
1136
- }
1137
- return this.options.modelMeta.models[(0, lower_case_first_1.lowerCaseFirst)(baseNames[0])];
1138
- }
1139
- involvesDelegateModel(model, visited) {
1140
- if (this.isDelegateOrDescendantOfDelegate(model)) {
1141
- return true;
1142
- }
1143
- visited = visited !== null && visited !== void 0 ? visited : new Set();
1144
- if (visited.has(model)) {
1145
- return false;
1146
- }
1147
- visited.add(model);
1148
- const modelInfo = (0, cross_1.getModelInfo)(this.options.modelMeta, model, true);
1149
- return Object.values(modelInfo.fields).some((field) => field.isDataModel && this.involvesDelegateModel(field.type, visited));
1150
- }
1151
- isDelegateOrDescendantOfDelegate(model) {
1152
- var _a;
1153
- if ((0, cross_1.isDelegateModel)(this.options.modelMeta, model)) {
1154
- return true;
1155
- }
1156
- const baseTypes = (_a = (0, cross_1.getModelInfo)(this.options.modelMeta, model)) === null || _a === void 0 ? void 0 : _a.baseTypes;
1157
- return !!(baseTypes &&
1158
- baseTypes.length > 0 &&
1159
- baseTypes.some((base) => this.isDelegateOrDescendantOfDelegate(base)));
1160
- }
1161
- assembleHierarchy(model, entity) {
1162
- if (!entity || typeof entity !== 'object') {
1163
- return entity;
1164
- }
1165
- const upMerged = this.assembleUp(model, entity);
1166
- const downMerged = this.assembleDown(model, entity);
1167
- // https://www.npmjs.com/package/deepmerge#arraymerge-example-combine-arrays
1168
- const combineMerge = (target, source, options) => {
1169
- const destination = target.slice();
1170
- source.forEach((item, index) => {
1171
- if (typeof destination[index] === 'undefined') {
1172
- destination[index] = options.cloneUnlessOtherwiseSpecified(item, options);
1173
- }
1174
- else if (options.isMergeableObject(item)) {
1175
- destination[index] = (0, deepmerge_1.default)(target[index], item, options);
1176
- }
1177
- else if (target.indexOf(item) === -1) {
1178
- destination.push(item);
1179
- }
1180
- });
1181
- return destination;
1182
- };
1183
- const result = (0, deepmerge_1.default)(upMerged, downMerged, {
1184
- arrayMerge: combineMerge,
1185
- isMergeableObject: (v) => (0, is_plain_object_1.isPlainObject)(v) || Array.isArray(v), // avoid messing with Decimal, Date, etc.
1186
- });
1187
- return result;
1188
- }
1189
- assembleUp(model, entity) {
1190
- if (!entity) {
1191
- return entity;
1192
- }
1193
- const result = {};
1194
- const base = this.getBaseModel(model);
1195
- if (base) {
1196
- // fully merge base fields
1197
- const baseRelationName = this.makeAuxRelationName(base);
1198
- const baseData = entity[baseRelationName];
1199
- if (baseData && typeof baseData === 'object') {
1200
- const baseAssembled = this.assembleHierarchy(base.name, baseData);
1201
- Object.assign(result, baseAssembled);
1202
- }
1203
- }
1204
- const modelInfo = (0, cross_1.getModelInfo)(this.options.modelMeta, model, true);
1205
- for (const [key, value] of Object.entries(entity)) {
1206
- if (key.startsWith(constants_1.DELEGATE_AUX_RELATION_PREFIX)) {
1207
- continue;
1208
- }
1209
- const field = modelInfo.fields[key];
1210
- if (!field) {
1211
- // not a field, could be `_count`, `_sum`, etc.
1212
- result[key] = value;
1213
- continue;
1214
- }
1215
- if (field.inheritedFrom) {
1216
- // already merged from base
1217
- continue;
1218
- }
1219
- if (field.isDataModel) {
1220
- if (Array.isArray(value)) {
1221
- result[field.name] = value.map((item) => this.assembleUp(field.type, item));
1222
- }
1223
- else {
1224
- result[field.name] = this.assembleUp(field.type, value);
1225
- }
1226
- }
1227
- else {
1228
- result[field.name] = value;
1229
- }
1230
- }
1231
- return result;
1232
- }
1233
- assembleDown(model, entity) {
1234
- if (!entity) {
1235
- return entity;
1236
- }
1237
- const result = {};
1238
- const modelInfo = (0, cross_1.getModelInfo)(this.options.modelMeta, model, true);
1239
- if (modelInfo.discriminator) {
1240
- // model is a delegate, fully merge concrete model fields
1241
- const subModelName = entity[modelInfo.discriminator];
1242
- if (subModelName) {
1243
- const subModel = (0, cross_1.getModelInfo)(this.options.modelMeta, subModelName, true);
1244
- const subRelationName = this.makeAuxRelationName(subModel);
1245
- const subData = entity[subRelationName];
1246
- if (subData && typeof subData === 'object') {
1247
- const subAssembled = this.assembleHierarchy(subModel.name, subData);
1248
- Object.assign(result, subAssembled);
1249
- }
1250
- }
1251
- }
1252
- for (const [key, value] of Object.entries(entity)) {
1253
- if (key.startsWith(constants_1.DELEGATE_AUX_RELATION_PREFIX)) {
1254
- continue;
1255
- }
1256
- const field = modelInfo.fields[key];
1257
- if (!field) {
1258
- // not a field, could be `_count`, `_sum`, etc.
1259
- result[key] = value;
1260
- continue;
1261
- }
1262
- if (field.isDataModel) {
1263
- if (Array.isArray(value)) {
1264
- result[field.name] = value.map((item) => this.assembleDown(field.type, item));
1265
- }
1266
- else {
1267
- result[field.name] = this.assembleDown(field.type, value);
1268
- }
1269
- }
1270
- else {
1271
- result[field.name] = value;
1272
- }
1273
- }
1274
- return result;
1275
- }
1276
- getUpdatedAtFromDelegateBases(model) {
1277
- var _a;
1278
- const result = [];
1279
- const modelFields = (0, cross_1.getFields)(this.options.modelMeta, model);
1280
- if (!modelFields) {
1281
- return result;
1282
- }
1283
- for (const fieldInfo of Object.values(modelFields)) {
1284
- if (((_a = fieldInfo.attributes) === null || _a === void 0 ? void 0 : _a.some((attr) => attr.name === '@updatedAt')) &&
1285
- fieldInfo.inheritedFrom &&
1286
- (0, cross_1.isDelegateModel)(this.options.modelMeta, fieldInfo.inheritedFrom)) {
1287
- result.push(fieldInfo);
1288
- }
1289
- }
1290
- return result;
1291
- }
1292
- }
1293
- exports.DelegateProxyHandler = DelegateProxyHandler;
1294
- //# sourceMappingURL=delegate.js.map