@yandjin-mikro-orm/core 6.1.4-rc-sti-changes-1

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 (264) hide show
  1. package/EntityManager.d.ts +553 -0
  2. package/EntityManager.js +1736 -0
  3. package/LICENSE +21 -0
  4. package/MikroORM.d.ts +102 -0
  5. package/MikroORM.js +258 -0
  6. package/README.md +383 -0
  7. package/cache/CacheAdapter.d.ts +40 -0
  8. package/cache/CacheAdapter.js +2 -0
  9. package/cache/FileCacheAdapter.d.ts +31 -0
  10. package/cache/FileCacheAdapter.js +90 -0
  11. package/cache/GeneratedCacheAdapter.d.ts +25 -0
  12. package/cache/GeneratedCacheAdapter.js +38 -0
  13. package/cache/MemoryCacheAdapter.d.ts +24 -0
  14. package/cache/MemoryCacheAdapter.js +44 -0
  15. package/cache/NullCacheAdapter.d.ts +19 -0
  16. package/cache/NullCacheAdapter.js +30 -0
  17. package/cache/index.d.ts +5 -0
  18. package/cache/index.js +21 -0
  19. package/connections/Connection.d.ts +85 -0
  20. package/connections/Connection.js +128 -0
  21. package/connections/index.d.ts +1 -0
  22. package/connections/index.js +17 -0
  23. package/decorators/Check.d.ts +3 -0
  24. package/decorators/Check.js +17 -0
  25. package/decorators/CreateRequestContext.d.ts +2 -0
  26. package/decorators/CreateRequestContext.js +31 -0
  27. package/decorators/Embeddable.d.ts +8 -0
  28. package/decorators/Embeddable.js +15 -0
  29. package/decorators/Embedded.d.ts +13 -0
  30. package/decorators/Embedded.js +21 -0
  31. package/decorators/EnsureRequestContext.d.ts +2 -0
  32. package/decorators/EnsureRequestContext.js +26 -0
  33. package/decorators/Entity.d.ts +18 -0
  34. package/decorators/Entity.js +17 -0
  35. package/decorators/Enum.d.ts +9 -0
  36. package/decorators/Enum.js +20 -0
  37. package/decorators/Filter.d.ts +2 -0
  38. package/decorators/Filter.js +12 -0
  39. package/decorators/Formula.d.ts +5 -0
  40. package/decorators/Formula.js +19 -0
  41. package/decorators/Indexed.d.ts +12 -0
  42. package/decorators/Indexed.js +25 -0
  43. package/decorators/ManyToMany.d.ts +21 -0
  44. package/decorators/ManyToMany.js +17 -0
  45. package/decorators/ManyToOne.d.ts +15 -0
  46. package/decorators/ManyToOne.js +17 -0
  47. package/decorators/OneToMany.d.ts +18 -0
  48. package/decorators/OneToMany.js +21 -0
  49. package/decorators/OneToOne.d.ts +12 -0
  50. package/decorators/OneToOne.js +11 -0
  51. package/decorators/PrimaryKey.d.ts +8 -0
  52. package/decorators/PrimaryKey.js +24 -0
  53. package/decorators/Property.d.ts +218 -0
  54. package/decorators/Property.js +35 -0
  55. package/decorators/Subscriber.d.ts +1 -0
  56. package/decorators/Subscriber.js +2 -0
  57. package/decorators/hooks.d.ts +16 -0
  58. package/decorators/hooks.js +60 -0
  59. package/decorators/index.d.ts +17 -0
  60. package/decorators/index.js +36 -0
  61. package/drivers/DatabaseDriver.d.ts +72 -0
  62. package/drivers/DatabaseDriver.js +358 -0
  63. package/drivers/IDatabaseDriver.d.ts +193 -0
  64. package/drivers/IDatabaseDriver.js +4 -0
  65. package/drivers/index.d.ts +2 -0
  66. package/drivers/index.js +18 -0
  67. package/entity/ArrayCollection.d.ts +113 -0
  68. package/entity/ArrayCollection.js +386 -0
  69. package/entity/BaseEntity.d.ts +22 -0
  70. package/entity/BaseEntity.js +47 -0
  71. package/entity/Collection.d.ts +104 -0
  72. package/entity/Collection.js +373 -0
  73. package/entity/EntityAssigner.d.ts +28 -0
  74. package/entity/EntityAssigner.js +226 -0
  75. package/entity/EntityFactory.d.ts +41 -0
  76. package/entity/EntityFactory.js +302 -0
  77. package/entity/EntityHelper.d.ts +29 -0
  78. package/entity/EntityHelper.js +250 -0
  79. package/entity/EntityIdentifier.d.ts +10 -0
  80. package/entity/EntityIdentifier.js +19 -0
  81. package/entity/EntityLoader.d.ts +65 -0
  82. package/entity/EntityLoader.js +579 -0
  83. package/entity/EntityRepository.d.ts +161 -0
  84. package/entity/EntityRepository.js +207 -0
  85. package/entity/EntityValidator.d.ts +19 -0
  86. package/entity/EntityValidator.js +152 -0
  87. package/entity/Reference.d.ts +89 -0
  88. package/entity/Reference.js +242 -0
  89. package/entity/WrappedEntity.d.ts +67 -0
  90. package/entity/WrappedEntity.js +146 -0
  91. package/entity/index.d.ts +13 -0
  92. package/entity/index.js +29 -0
  93. package/entity/wrap.d.ts +15 -0
  94. package/entity/wrap.js +26 -0
  95. package/enums.d.ts +160 -0
  96. package/enums.js +169 -0
  97. package/errors.d.ts +65 -0
  98. package/errors.js +222 -0
  99. package/events/EventManager.d.ts +17 -0
  100. package/events/EventManager.js +77 -0
  101. package/events/EventSubscriber.d.ts +39 -0
  102. package/events/EventSubscriber.js +2 -0
  103. package/events/TransactionEventBroadcaster.d.ts +11 -0
  104. package/events/TransactionEventBroadcaster.js +17 -0
  105. package/events/index.d.ts +3 -0
  106. package/events/index.js +19 -0
  107. package/exceptions.d.ts +104 -0
  108. package/exceptions.js +130 -0
  109. package/hydration/Hydrator.d.ts +23 -0
  110. package/hydration/Hydrator.js +51 -0
  111. package/hydration/ObjectHydrator.d.ts +24 -0
  112. package/hydration/ObjectHydrator.js +332 -0
  113. package/hydration/index.d.ts +2 -0
  114. package/hydration/index.js +18 -0
  115. package/index.d.ts +25 -0
  116. package/index.js +50 -0
  117. package/index.mjs +192 -0
  118. package/logging/DefaultLogger.d.ts +32 -0
  119. package/logging/DefaultLogger.js +90 -0
  120. package/logging/Logger.d.ts +56 -0
  121. package/logging/Logger.js +2 -0
  122. package/logging/SimpleLogger.d.ts +17 -0
  123. package/logging/SimpleLogger.js +31 -0
  124. package/logging/colors.d.ts +9 -0
  125. package/logging/colors.js +20 -0
  126. package/logging/index.d.ts +4 -0
  127. package/logging/index.js +20 -0
  128. package/metadata/EntitySchema.d.ts +74 -0
  129. package/metadata/EntitySchema.js +293 -0
  130. package/metadata/MetadataDiscovery.d.ts +71 -0
  131. package/metadata/MetadataDiscovery.js +1244 -0
  132. package/metadata/MetadataProvider.d.ts +11 -0
  133. package/metadata/MetadataProvider.js +23 -0
  134. package/metadata/MetadataStorage.d.ts +22 -0
  135. package/metadata/MetadataStorage.js +87 -0
  136. package/metadata/MetadataValidator.d.ts +24 -0
  137. package/metadata/MetadataValidator.js +213 -0
  138. package/metadata/ReflectMetadataProvider.d.ts +8 -0
  139. package/metadata/ReflectMetadataProvider.js +48 -0
  140. package/metadata/index.d.ts +6 -0
  141. package/metadata/index.js +22 -0
  142. package/naming-strategy/AbstractNamingStrategy.d.ts +18 -0
  143. package/naming-strategy/AbstractNamingStrategy.js +48 -0
  144. package/naming-strategy/EntityCaseNamingStrategy.d.ts +12 -0
  145. package/naming-strategy/EntityCaseNamingStrategy.js +32 -0
  146. package/naming-strategy/MongoNamingStrategy.d.ts +9 -0
  147. package/naming-strategy/MongoNamingStrategy.js +25 -0
  148. package/naming-strategy/NamingStrategy.d.ts +52 -0
  149. package/naming-strategy/NamingStrategy.js +2 -0
  150. package/naming-strategy/UnderscoreNamingStrategy.d.ts +10 -0
  151. package/naming-strategy/UnderscoreNamingStrategy.js +28 -0
  152. package/naming-strategy/index.d.ts +5 -0
  153. package/naming-strategy/index.js +21 -0
  154. package/package.json +70 -0
  155. package/platforms/ExceptionConverter.d.ts +5 -0
  156. package/platforms/ExceptionConverter.js +11 -0
  157. package/platforms/Platform.d.ts +201 -0
  158. package/platforms/Platform.js +452 -0
  159. package/platforms/index.d.ts +2 -0
  160. package/platforms/index.js +18 -0
  161. package/serialization/EntitySerializer.d.ts +34 -0
  162. package/serialization/EntitySerializer.js +206 -0
  163. package/serialization/EntityTransformer.d.ts +8 -0
  164. package/serialization/EntityTransformer.js +192 -0
  165. package/serialization/SerializationContext.d.ts +30 -0
  166. package/serialization/SerializationContext.js +111 -0
  167. package/serialization/index.d.ts +3 -0
  168. package/serialization/index.js +19 -0
  169. package/types/ArrayType.d.ts +13 -0
  170. package/types/ArrayType.js +47 -0
  171. package/types/BigIntType.d.ts +16 -0
  172. package/types/BigIntType.js +45 -0
  173. package/types/BlobType.d.ts +10 -0
  174. package/types/BlobType.js +27 -0
  175. package/types/BooleanType.d.ts +8 -0
  176. package/types/BooleanType.js +16 -0
  177. package/types/DateTimeType.d.ts +8 -0
  178. package/types/DateTimeType.js +16 -0
  179. package/types/DateType.d.ts +8 -0
  180. package/types/DateType.js +16 -0
  181. package/types/DecimalType.d.ts +11 -0
  182. package/types/DecimalType.js +22 -0
  183. package/types/DoubleType.d.ts +11 -0
  184. package/types/DoubleType.js +22 -0
  185. package/types/EnumArrayType.d.ts +9 -0
  186. package/types/EnumArrayType.js +32 -0
  187. package/types/EnumType.d.ts +8 -0
  188. package/types/EnumType.js +16 -0
  189. package/types/FloatType.d.ts +8 -0
  190. package/types/FloatType.js +16 -0
  191. package/types/IntegerType.d.ts +8 -0
  192. package/types/IntegerType.js +16 -0
  193. package/types/IntervalType.d.ts +8 -0
  194. package/types/IntervalType.js +16 -0
  195. package/types/JsonType.d.ts +13 -0
  196. package/types/JsonType.js +34 -0
  197. package/types/MediumIntType.d.ts +6 -0
  198. package/types/MediumIntType.js +10 -0
  199. package/types/SmallIntType.d.ts +8 -0
  200. package/types/SmallIntType.js +16 -0
  201. package/types/StringType.d.ts +8 -0
  202. package/types/StringType.js +16 -0
  203. package/types/TextType.d.ts +8 -0
  204. package/types/TextType.js +16 -0
  205. package/types/TimeType.d.ts +9 -0
  206. package/types/TimeType.js +23 -0
  207. package/types/TinyIntType.d.ts +8 -0
  208. package/types/TinyIntType.js +16 -0
  209. package/types/Type.d.ts +64 -0
  210. package/types/Type.js +84 -0
  211. package/types/Uint8ArrayType.d.ts +11 -0
  212. package/types/Uint8ArrayType.js +37 -0
  213. package/types/UnknownType.d.ts +7 -0
  214. package/types/UnknownType.js +13 -0
  215. package/types/UuidType.d.ts +7 -0
  216. package/types/UuidType.js +13 -0
  217. package/types/index.d.ts +75 -0
  218. package/types/index.js +77 -0
  219. package/typings.d.ts +767 -0
  220. package/typings.js +198 -0
  221. package/unit-of-work/ChangeSet.d.ts +34 -0
  222. package/unit-of-work/ChangeSet.js +62 -0
  223. package/unit-of-work/ChangeSetComputer.d.ts +26 -0
  224. package/unit-of-work/ChangeSetComputer.js +153 -0
  225. package/unit-of-work/ChangeSetPersister.d.ts +50 -0
  226. package/unit-of-work/ChangeSetPersister.js +361 -0
  227. package/unit-of-work/CommitOrderCalculator.d.ts +62 -0
  228. package/unit-of-work/CommitOrderCalculator.js +113 -0
  229. package/unit-of-work/IdentityMap.d.ts +17 -0
  230. package/unit-of-work/IdentityMap.js +84 -0
  231. package/unit-of-work/UnitOfWork.d.ts +124 -0
  232. package/unit-of-work/UnitOfWork.js +1013 -0
  233. package/unit-of-work/index.d.ts +6 -0
  234. package/unit-of-work/index.js +22 -0
  235. package/utils/AbstractSchemaGenerator.d.ts +38 -0
  236. package/utils/AbstractSchemaGenerator.js +101 -0
  237. package/utils/Configuration.d.ts +390 -0
  238. package/utils/Configuration.js +357 -0
  239. package/utils/ConfigurationLoader.d.ts +29 -0
  240. package/utils/ConfigurationLoader.js +282 -0
  241. package/utils/Cursor.d.ts +77 -0
  242. package/utils/Cursor.js +169 -0
  243. package/utils/DataloaderUtils.d.ts +43 -0
  244. package/utils/DataloaderUtils.js +194 -0
  245. package/utils/EntityComparator.d.ts +73 -0
  246. package/utils/EntityComparator.js +568 -0
  247. package/utils/NullHighlighter.d.ts +4 -0
  248. package/utils/NullHighlighter.js +9 -0
  249. package/utils/QueryHelper.d.ts +28 -0
  250. package/utils/QueryHelper.js +228 -0
  251. package/utils/RawQueryFragment.d.ts +96 -0
  252. package/utils/RawQueryFragment.js +188 -0
  253. package/utils/RequestContext.d.ts +34 -0
  254. package/utils/RequestContext.js +54 -0
  255. package/utils/TransactionContext.d.ts +19 -0
  256. package/utils/TransactionContext.js +34 -0
  257. package/utils/Utils.d.ts +274 -0
  258. package/utils/Utils.js +1073 -0
  259. package/utils/clone.d.ts +6 -0
  260. package/utils/clone.js +127 -0
  261. package/utils/index.d.ts +13 -0
  262. package/utils/index.js +29 -0
  263. package/utils/upsert-utils.d.ts +6 -0
  264. package/utils/upsert-utils.js +33 -0
@@ -0,0 +1,228 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.QueryHelper = void 0;
4
+ const Reference_1 = require("../entity/Reference");
5
+ const Utils_1 = require("./Utils");
6
+ const enums_1 = require("../enums");
7
+ const JsonType_1 = require("../types/JsonType");
8
+ const wrap_1 = require("../entity/wrap");
9
+ class QueryHelper {
10
+ static SUPPORTED_OPERATORS = ['>', '<', '<=', '>=', '!', '!='];
11
+ static processParams(params) {
12
+ if (Reference_1.Reference.isReference(params)) {
13
+ params = params.unwrap();
14
+ }
15
+ if (Utils_1.Utils.isEntity(params)) {
16
+ if ((0, wrap_1.helper)(params).__meta.compositePK) {
17
+ return (0, wrap_1.helper)(params).__primaryKeys;
18
+ }
19
+ return (0, wrap_1.helper)(params).getPrimaryKey();
20
+ }
21
+ if (params === undefined) {
22
+ return null;
23
+ }
24
+ if (Array.isArray(params)) {
25
+ return params.map(item => QueryHelper.processParams(item));
26
+ }
27
+ if (Utils_1.Utils.isPlainObject(params)) {
28
+ QueryHelper.processObjectParams(params);
29
+ }
30
+ return params;
31
+ }
32
+ static processObjectParams(params = {}) {
33
+ Utils_1.Utils.keys(params).forEach(k => {
34
+ params[k] = QueryHelper.processParams(params[k]);
35
+ });
36
+ return params;
37
+ }
38
+ static inlinePrimaryKeyObjects(where, meta, metadata, key) {
39
+ if (Array.isArray(where)) {
40
+ where.forEach((item, i) => {
41
+ if (this.inlinePrimaryKeyObjects(item, meta, metadata, key)) {
42
+ where[i] = Utils_1.Utils.getPrimaryKeyValues(item, meta.primaryKeys, false);
43
+ }
44
+ });
45
+ }
46
+ if (!Utils_1.Utils.isPlainObject(where) || (key && meta.properties[key]?.customType instanceof JsonType_1.JsonType)) {
47
+ return false;
48
+ }
49
+ if (meta.primaryKeys.every(pk => pk in where) && Utils_1.Utils.getObjectKeysSize(where) === meta.primaryKeys.length) {
50
+ return !!key && !enums_1.GroupOperator[key] && Object.keys(where).every(k => !Utils_1.Utils.isPlainObject(where[k]) || Object.keys(where[k]).every(v => {
51
+ if (Utils_1.Utils.isOperator(v, false)) {
52
+ return false;
53
+ }
54
+ if (meta.properties[k].primary && [enums_1.ReferenceKind.ONE_TO_ONE, enums_1.ReferenceKind.MANY_TO_ONE].includes(meta.properties[k].kind)) {
55
+ return this.inlinePrimaryKeyObjects(where[k], meta.properties[k].targetMeta, metadata, v);
56
+ }
57
+ return true;
58
+ }));
59
+ }
60
+ Object.keys(where).forEach(k => {
61
+ const meta2 = metadata.find(meta.properties[k]?.type) || meta;
62
+ if (this.inlinePrimaryKeyObjects(where[k], meta2, metadata, k)) {
63
+ where[k] = Utils_1.Utils.getPrimaryKeyValues(where[k], meta2.primaryKeys, true);
64
+ }
65
+ });
66
+ return false;
67
+ }
68
+ static processWhere(options) {
69
+ // eslint-disable-next-line prefer-const
70
+ let { where, entityName, metadata, platform, aliased = true, convertCustomTypes = true, root = true } = options;
71
+ const meta = metadata.find(entityName);
72
+ // inline PK-only objects in M:N queries, so we don't join the target entity when not needed
73
+ if (meta && root) {
74
+ QueryHelper.inlinePrimaryKeyObjects(where, meta, metadata);
75
+ }
76
+ if (options.platform.getConfig().get('ignoreUndefinedInQuery') && where && typeof where === 'object') {
77
+ Utils_1.Utils.dropUndefinedProperties(where);
78
+ }
79
+ where = QueryHelper.processParams(where) ?? {};
80
+ /* istanbul ignore next */
81
+ if (!root && Utils_1.Utils.isPrimaryKey(where)) {
82
+ return where;
83
+ }
84
+ if (meta && Utils_1.Utils.isPrimaryKey(where, meta.compositePK)) {
85
+ where = { [Utils_1.Utils.getPrimaryKeyHash(meta.primaryKeys)]: where };
86
+ }
87
+ if (Array.isArray(where) && root) {
88
+ const rootPrimaryKey = meta ? Utils_1.Utils.getPrimaryKeyHash(meta.primaryKeys) : entityName;
89
+ let cond = { [rootPrimaryKey]: { $in: where } };
90
+ // @ts-ignore
91
+ // detect tuple comparison, use `$or` in case the number of constituents don't match
92
+ if (meta && !where.every(c => Utils_1.Utils.isPrimaryKey(c) || (Array.isArray(c) && c.length === meta.primaryKeys.length && c.every(i => Utils_1.Utils.isPrimaryKey(i))))) {
93
+ cond = { $or: where };
94
+ }
95
+ return QueryHelper.processWhere({ ...options, where: cond, root: false });
96
+ }
97
+ if (!Utils_1.Utils.isPlainObject(where)) {
98
+ return where;
99
+ }
100
+ return Object.keys(where).reduce((o, key) => {
101
+ let value = where[key];
102
+ const prop = this.findProperty(key, options);
103
+ const keys = prop?.joinColumns?.length ?? 0;
104
+ const composite = keys > 1;
105
+ if (key in enums_1.GroupOperator) {
106
+ o[key] = value.map((sub) => QueryHelper.processWhere({ ...options, where: sub, root }));
107
+ return o;
108
+ }
109
+ // wrap top level operators (except platform allowed operators) with PK
110
+ if (Utils_1.Utils.isOperator(key) && root && meta && !options.platform.isAllowedTopLevelOperator(key)) {
111
+ const rootPrimaryKey = Utils_1.Utils.getPrimaryKeyHash(meta.primaryKeys);
112
+ o[rootPrimaryKey] = { [key]: QueryHelper.processWhere({ ...options, where: value, root: false }) };
113
+ return o;
114
+ }
115
+ if (prop?.customType && convertCustomTypes && !platform.isRaw(value)) {
116
+ value = QueryHelper.processCustomType(prop, value, platform, undefined, true);
117
+ }
118
+ const isJsonProperty = prop?.customType instanceof JsonType_1.JsonType && Utils_1.Utils.isPlainObject(value) && !platform.isRaw(value) && Object.keys(value)[0] !== '$eq';
119
+ if (isJsonProperty) {
120
+ return this.processJsonCondition(o, value, [prop.fieldNames[0]], platform, aliased);
121
+ }
122
+ if (Array.isArray(value) && !Utils_1.Utils.isOperator(key) && !QueryHelper.isSupportedOperator(key) && !key.includes('?') && options.type !== 'orderBy') {
123
+ if (platform.allowsComparingTuples()) {
124
+ // comparing single composite key - use $eq instead of $in
125
+ const op = !value.every(v => Array.isArray(v)) && composite ? '$eq' : '$in';
126
+ o[key] = { [op]: value };
127
+ }
128
+ else {
129
+ if (!value.every(v => Array.isArray(v)) && composite) {
130
+ o[key] = { $in: [value] };
131
+ }
132
+ else {
133
+ o[key] = { $in: value };
134
+ }
135
+ }
136
+ return o;
137
+ }
138
+ if (Utils_1.Utils.isPlainObject(value)) {
139
+ o[key] = QueryHelper.processWhere({
140
+ ...options,
141
+ where: value,
142
+ entityName: prop?.type ?? entityName,
143
+ root: false,
144
+ });
145
+ }
146
+ else {
147
+ o[key] = value;
148
+ }
149
+ return o;
150
+ }, {});
151
+ }
152
+ static getActiveFilters(entityName, options, filters) {
153
+ if (options === false) {
154
+ return [];
155
+ }
156
+ const opts = {};
157
+ if (Array.isArray(options)) {
158
+ options.forEach(filter => opts[filter] = true);
159
+ }
160
+ else if (Utils_1.Utils.isPlainObject(options)) {
161
+ Object.keys(options).forEach(filter => opts[filter] = options[filter]);
162
+ }
163
+ return Object.keys(filters)
164
+ .filter(f => QueryHelper.isFilterActive(entityName, f, filters[f], opts))
165
+ .map(f => {
166
+ filters[f].name = f;
167
+ return filters[f];
168
+ });
169
+ }
170
+ static isFilterActive(entityName, filterName, filter, options) {
171
+ if (filter.entity && !filter.entity.includes(entityName)) {
172
+ return false;
173
+ }
174
+ if (options[filterName] === false) {
175
+ return false;
176
+ }
177
+ return filter.default || filterName in options;
178
+ }
179
+ static processCustomType(prop, cond, platform, key, fromQuery) {
180
+ if (Utils_1.Utils.isPlainObject(cond)) {
181
+ return Utils_1.Utils.keys(cond).reduce((o, k) => {
182
+ if (Utils_1.Utils.isOperator(k, true) || prop.referencedPKs?.includes(k)) {
183
+ o[k] = QueryHelper.processCustomType(prop, cond[k], platform, k, fromQuery);
184
+ }
185
+ else {
186
+ o[k] = cond[k];
187
+ }
188
+ return o;
189
+ }, {});
190
+ }
191
+ if (Array.isArray(cond) && !(key && Utils_1.Utils.isArrayOperator(key))) {
192
+ return cond.map(v => QueryHelper.processCustomType(prop, v, platform, key, fromQuery));
193
+ }
194
+ if (platform.isRaw(cond)) {
195
+ return cond;
196
+ }
197
+ return prop.customType.convertToDatabaseValue(cond, platform, { fromQuery, key, mode: 'query' });
198
+ }
199
+ static isSupportedOperator(key) {
200
+ return !!QueryHelper.SUPPORTED_OPERATORS.find(op => key.includes(op));
201
+ }
202
+ static processJsonCondition(o, value, path, platform, alias) {
203
+ if (Utils_1.Utils.isPlainObject(value) && !Object.keys(value).some(k => Utils_1.Utils.isOperator(k))) {
204
+ Utils_1.Utils.keys(value).forEach(k => {
205
+ this.processJsonCondition(o, value[k], [...path, k], platform, alias);
206
+ });
207
+ return o;
208
+ }
209
+ if (path.length === 1) {
210
+ o[path[0]] = value;
211
+ return o;
212
+ }
213
+ const operatorObject = Utils_1.Utils.isPlainObject(value) && Object.keys(value).every(k => Utils_1.Utils.isOperator(k));
214
+ const type = operatorObject ? typeof Object.values(value)[0] : typeof value;
215
+ const k = platform.getSearchJsonPropertyKey(path, type, alias, value);
216
+ o[k] = value;
217
+ return o;
218
+ }
219
+ static findProperty(fieldName, options) {
220
+ const parts = fieldName.split('.');
221
+ const propName = parts.pop();
222
+ const alias = parts.length > 0 ? parts.join('.') : undefined;
223
+ const entityName = alias ? options.aliasMap?.[alias] : options.entityName;
224
+ const meta = entityName ? options.metadata.find(entityName) : undefined;
225
+ return meta?.properties[propName];
226
+ }
227
+ }
228
+ exports.QueryHelper = QueryHelper;
@@ -0,0 +1,96 @@
1
+ /// <reference types="node" />
2
+ import { inspect } from 'util';
3
+ import type { AnyString, Dictionary, EntityKey } from '../typings';
4
+ export declare class RawQueryFragment {
5
+ #private;
6
+ readonly sql: string;
7
+ readonly params: unknown[];
8
+ static cloneRegistry?: Set<string>;
9
+ constructor(sql: string, params?: unknown[]);
10
+ as(alias: string): RawQueryFragment;
11
+ valueOf(): string;
12
+ toJSON(): void;
13
+ toString(): string;
14
+ /** @internal */
15
+ assign(): void;
16
+ clone(): RawQueryFragment;
17
+ /**
18
+ * @internal allows testing we don't leak memory, as the raw fragments cache needs to be cleared automatically
19
+ */
20
+ static checkCacheSize(): number;
21
+ static isKnownFragment(key: string | RawQueryFragment): boolean;
22
+ static getKnownFragment(key: string | RawQueryFragment, cleanup?: boolean): RawQueryFragment | undefined;
23
+ static remove(key: string): void;
24
+ /** @ignore */
25
+ [inspect.custom](): {
26
+ sql: string;
27
+ params: unknown[];
28
+ } | {
29
+ sql: string;
30
+ params?: undefined;
31
+ };
32
+ }
33
+ /** @internal */
34
+ export declare const ALIAS_REPLACEMENT = "[::alias::]";
35
+ /** @internal */
36
+ export declare const ALIAS_REPLACEMENT_RE = "\\[::alias::\\]";
37
+ /**
38
+ * Creates raw SQL query fragment that can be assigned to a property or part of a filter. This fragment is represented
39
+ * by `RawQueryFragment` class instance that can be serialized to a string, so it can be used both as an object value
40
+ * and key. When serialized, the fragment key gets cached and only such cached key will be recognized by the ORM.
41
+ * This adds a runtime safety to the raw query fragments.
42
+ *
43
+ * > **`raw()` helper is required since v6 to use a raw fragment in your query, both through EntityManager and QueryBuilder.**
44
+ *
45
+ * ```ts
46
+ * // as a value
47
+ * await em.find(User, { time: raw('now()') });
48
+ *
49
+ * // as a key
50
+ * await em.find(User, { [raw('lower(name)')]: name.toLowerCase() });
51
+ *
52
+ * // value can be empty array
53
+ * await em.find(User, { [raw('(select 1 = 1)')]: [] });
54
+ * ```
55
+ *
56
+ * The `raw` helper supports several signatures, you can pass in a callback that receives the current property alias:
57
+ *
58
+ * ```ts
59
+ * await em.find(User, { [raw(alias => `lower(${alias}.name)`)]: name.toLowerCase() });
60
+ * ```
61
+ *
62
+ * You can also use the `sql` tagged template function, which works the same, but supports only the simple string signature:
63
+ *
64
+ * ```ts
65
+ * await em.find(User, { [sql`lower(name)`]: name.toLowerCase() });
66
+ * ```
67
+ *
68
+ * When using inside filters, you might have to use a callback signature to create new raw instance for every filter usage.
69
+ *
70
+ * ```ts
71
+ * @Filter({ name: 'long', cond: () => ({ [raw('length(perex)')]: { $gt: 10000 } }) })
72
+ * ```
73
+ */
74
+ export declare function raw<T extends object = any, R = any>(sql: EntityKey<T> | EntityKey<T>[] | AnyString | ((alias: string) => string) | RawQueryFragment, params?: unknown[] | Dictionary<unknown>): R;
75
+ /**
76
+ * Alternative to the `raw()` helper allowing to use it as a tagged template function for the simple cases.
77
+ *
78
+ * ```ts
79
+ * // as a value
80
+ * await em.find(User, { time: sql`now()` });
81
+ *
82
+ * // as a key
83
+ * await em.find(User, { [sql`lower(name)`]: name.toLowerCase() });
84
+ *
85
+ * // value can be empty array
86
+ * await em.find(User, { [sql`(select 1 = 1)`]: [] });
87
+ * ```
88
+ */
89
+ export declare function sql(sql: readonly string[], ...values: unknown[]): any;
90
+ export declare namespace sql {
91
+ var ref: <T extends object>(...keys: string[]) => RawQueryFragment;
92
+ var now: (length?: number | undefined) => string;
93
+ var lower: <T extends object>(key: string | ((alias: string) => string)) => string;
94
+ var upper: <T extends object>(key: string | ((alias: string) => string)) => string;
95
+ }
96
+ export declare function createSqlFunction<T extends object, R = string>(func: string, key: string | ((alias: string) => string)): R;
@@ -0,0 +1,188 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createSqlFunction = exports.sql = exports.raw = exports.ALIAS_REPLACEMENT_RE = exports.ALIAS_REPLACEMENT = exports.RawQueryFragment = void 0;
4
+ const util_1 = require("util");
5
+ const Utils_1 = require("./Utils");
6
+ class RawQueryFragment {
7
+ sql;
8
+ params;
9
+ static #rawQueryCache = new Map();
10
+ static #index = 0;
11
+ static cloneRegistry;
12
+ #assigned = false;
13
+ #used = 0;
14
+ #key;
15
+ constructor(sql, params = []) {
16
+ this.sql = sql;
17
+ this.params = params;
18
+ this.#key = `[raw]: ${this.sql}${this.params ? ` (#${RawQueryFragment.#index++})` : ''}`;
19
+ }
20
+ as(alias) {
21
+ return new RawQueryFragment(`${this.sql} as ${alias}`, this.params);
22
+ }
23
+ valueOf() {
24
+ throw new Error(`Trying to modify raw SQL fragment: '${this.sql}'`);
25
+ }
26
+ toJSON() {
27
+ throw new Error(`Trying to serialize raw SQL fragment: '${this.sql}'`);
28
+ }
29
+ toString() {
30
+ RawQueryFragment.#rawQueryCache.set(this.#key, this);
31
+ this.#used++;
32
+ return this.#key;
33
+ }
34
+ /** @internal */
35
+ assign() {
36
+ if (this.#assigned) {
37
+ throw new Error(`Cannot reassign already used RawQueryFragment: '${this.sql}'`);
38
+ }
39
+ this.#assigned = true;
40
+ }
41
+ clone() {
42
+ RawQueryFragment.cloneRegistry?.add(this.#key);
43
+ return new RawQueryFragment(this.sql, this.params);
44
+ }
45
+ /**
46
+ * @internal allows testing we don't leak memory, as the raw fragments cache needs to be cleared automatically
47
+ */
48
+ static checkCacheSize() {
49
+ return this.#rawQueryCache.size;
50
+ }
51
+ static isKnownFragment(key) {
52
+ if (key instanceof RawQueryFragment) {
53
+ return true;
54
+ }
55
+ return this.#rawQueryCache.has(key);
56
+ }
57
+ static getKnownFragment(key, cleanup = true) {
58
+ if (key instanceof RawQueryFragment) {
59
+ return key;
60
+ }
61
+ const raw = this.#rawQueryCache.get(key);
62
+ if (raw && cleanup) {
63
+ this.remove(key);
64
+ }
65
+ return raw;
66
+ }
67
+ static remove(key) {
68
+ const raw = this.#rawQueryCache.get(key);
69
+ if (!raw) {
70
+ return;
71
+ }
72
+ raw.#used--;
73
+ if (raw.#used <= 0) {
74
+ this.#rawQueryCache.delete(key);
75
+ }
76
+ }
77
+ /* istanbul ignore next */
78
+ /** @ignore */
79
+ [util_1.inspect.custom]() {
80
+ if (this.params) {
81
+ return { sql: this.sql, params: this.params };
82
+ }
83
+ return { sql: this.sql };
84
+ }
85
+ }
86
+ exports.RawQueryFragment = RawQueryFragment;
87
+ Object.defineProperties(RawQueryFragment.prototype, {
88
+ __raw: { value: true, enumerable: false },
89
+ });
90
+ /** @internal */
91
+ exports.ALIAS_REPLACEMENT = '[::alias::]';
92
+ /** @internal */
93
+ exports.ALIAS_REPLACEMENT_RE = '\\[::alias::\\]';
94
+ /**
95
+ * Creates raw SQL query fragment that can be assigned to a property or part of a filter. This fragment is represented
96
+ * by `RawQueryFragment` class instance that can be serialized to a string, so it can be used both as an object value
97
+ * and key. When serialized, the fragment key gets cached and only such cached key will be recognized by the ORM.
98
+ * This adds a runtime safety to the raw query fragments.
99
+ *
100
+ * > **`raw()` helper is required since v6 to use a raw fragment in your query, both through EntityManager and QueryBuilder.**
101
+ *
102
+ * ```ts
103
+ * // as a value
104
+ * await em.find(User, { time: raw('now()') });
105
+ *
106
+ * // as a key
107
+ * await em.find(User, { [raw('lower(name)')]: name.toLowerCase() });
108
+ *
109
+ * // value can be empty array
110
+ * await em.find(User, { [raw('(select 1 = 1)')]: [] });
111
+ * ```
112
+ *
113
+ * The `raw` helper supports several signatures, you can pass in a callback that receives the current property alias:
114
+ *
115
+ * ```ts
116
+ * await em.find(User, { [raw(alias => `lower(${alias}.name)`)]: name.toLowerCase() });
117
+ * ```
118
+ *
119
+ * You can also use the `sql` tagged template function, which works the same, but supports only the simple string signature:
120
+ *
121
+ * ```ts
122
+ * await em.find(User, { [sql`lower(name)`]: name.toLowerCase() });
123
+ * ```
124
+ *
125
+ * When using inside filters, you might have to use a callback signature to create new raw instance for every filter usage.
126
+ *
127
+ * ```ts
128
+ * @Filter({ name: 'long', cond: () => ({ [raw('length(perex)')]: { $gt: 10000 } }) })
129
+ * ```
130
+ */
131
+ function raw(sql, params) {
132
+ if (sql instanceof RawQueryFragment) {
133
+ return sql;
134
+ }
135
+ if (sql instanceof Function) {
136
+ sql = sql(exports.ALIAS_REPLACEMENT);
137
+ }
138
+ if (sql === '??' && Array.isArray(params)) {
139
+ return new RawQueryFragment(sql, params);
140
+ }
141
+ if (Array.isArray(sql)) {
142
+ // for composite FK we return just a simple string
143
+ return Utils_1.Utils.getPrimaryKeyHash(sql);
144
+ }
145
+ if (typeof params === 'object' && !Array.isArray(params)) {
146
+ const pairs = Object.entries(params);
147
+ params = [];
148
+ for (const [key, value] of pairs) {
149
+ sql = sql.replace(':' + key, '?');
150
+ params.push(value);
151
+ }
152
+ }
153
+ return new RawQueryFragment(sql, params);
154
+ }
155
+ exports.raw = raw;
156
+ /**
157
+ * Alternative to the `raw()` helper allowing to use it as a tagged template function for the simple cases.
158
+ *
159
+ * ```ts
160
+ * // as a value
161
+ * await em.find(User, { time: sql`now()` });
162
+ *
163
+ * // as a key
164
+ * await em.find(User, { [sql`lower(name)`]: name.toLowerCase() });
165
+ *
166
+ * // value can be empty array
167
+ * await em.find(User, { [sql`(select 1 = 1)`]: [] });
168
+ * ```
169
+ */
170
+ function sql(sql, ...values) {
171
+ return raw(sql.reduce((query, queryPart, i) => {
172
+ const valueExists = i < values.length;
173
+ const text = query + queryPart;
174
+ return valueExists ? text + '?' : text;
175
+ }, ''), values);
176
+ }
177
+ exports.sql = sql;
178
+ function createSqlFunction(func, key) {
179
+ if (typeof key === 'string') {
180
+ return raw(`${func}(${key})`);
181
+ }
182
+ return raw(a => `${func}(${(key(a))})`);
183
+ }
184
+ exports.createSqlFunction = createSqlFunction;
185
+ sql.ref = (...keys) => raw('??', [keys.join('.')]);
186
+ sql.now = (length) => raw('current_timestamp' + (length == null ? '' : `(${length})`));
187
+ sql.lower = (key) => createSqlFunction('lower', key);
188
+ sql.upper = (key) => createSqlFunction('upper', key);
@@ -0,0 +1,34 @@
1
+ import type { EntityManager } from '../EntityManager';
2
+ import { type LoggingOptions } from '../logging/Logger';
3
+ /**
4
+ * Uses `AsyncLocalStorage` to create async context that holds the current EM fork.
5
+ */
6
+ export declare class RequestContext {
7
+ readonly map: Map<string, EntityManager>;
8
+ private static storage;
9
+ private static counter;
10
+ readonly id: number;
11
+ constructor(map: Map<string, EntityManager>);
12
+ /**
13
+ * Returns default EntityManager.
14
+ */
15
+ get em(): EntityManager | undefined;
16
+ /**
17
+ * Creates new RequestContext instance and runs the code inside its domain.
18
+ * If the handler is async, the return value needs to be awaited.
19
+ */
20
+ static create<T>(em: EntityManager | EntityManager[], next: (...args: any[]) => T, options?: CreateContextOptions): T;
21
+ /**
22
+ * Returns current RequestContext (if available).
23
+ */
24
+ static currentRequestContext(): RequestContext | undefined;
25
+ /**
26
+ * Returns current EntityManager (if available).
27
+ */
28
+ static getEntityManager(name?: string): EntityManager | undefined;
29
+ private static createContext;
30
+ }
31
+ export interface CreateContextOptions {
32
+ schema?: string;
33
+ loggerContext?: LoggingOptions;
34
+ }
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RequestContext = void 0;
4
+ const async_hooks_1 = require("async_hooks");
5
+ /**
6
+ * Uses `AsyncLocalStorage` to create async context that holds the current EM fork.
7
+ */
8
+ class RequestContext {
9
+ map;
10
+ static storage = new async_hooks_1.AsyncLocalStorage();
11
+ static counter = 1;
12
+ id = RequestContext.counter++;
13
+ constructor(map) {
14
+ this.map = map;
15
+ }
16
+ /**
17
+ * Returns default EntityManager.
18
+ */
19
+ get em() {
20
+ return this.map.get('default');
21
+ }
22
+ /**
23
+ * Creates new RequestContext instance and runs the code inside its domain.
24
+ * If the handler is async, the return value needs to be awaited.
25
+ */
26
+ static create(em, next, options = {}) {
27
+ const ctx = this.createContext(em, options);
28
+ return this.storage.run(ctx, next);
29
+ }
30
+ /**
31
+ * Returns current RequestContext (if available).
32
+ */
33
+ static currentRequestContext() {
34
+ return this.storage.getStore();
35
+ }
36
+ /**
37
+ * Returns current EntityManager (if available).
38
+ */
39
+ static getEntityManager(name = 'default') {
40
+ const context = RequestContext.currentRequestContext();
41
+ return context ? context.map.get(name) : undefined;
42
+ }
43
+ static createContext(em, options = {}) {
44
+ const forks = new Map();
45
+ if (Array.isArray(em)) {
46
+ em.forEach(em => forks.set(em.name, em.fork({ useContext: true, ...options })));
47
+ }
48
+ else {
49
+ forks.set(em.name, em.fork({ useContext: true, ...options }));
50
+ }
51
+ return new RequestContext(forks);
52
+ }
53
+ }
54
+ exports.RequestContext = RequestContext;
@@ -0,0 +1,19 @@
1
+ import type { EntityManager } from '../EntityManager';
2
+ export declare class TransactionContext {
3
+ readonly em: EntityManager;
4
+ private static storage;
5
+ readonly id: number;
6
+ constructor(em: EntityManager);
7
+ /**
8
+ * Creates new TransactionContext instance and runs the code inside its domain.
9
+ */
10
+ static create<T>(em: EntityManager, next: (...args: any[]) => T): T;
11
+ /**
12
+ * Returns current TransactionContext (if available).
13
+ */
14
+ static currentTransactionContext(): TransactionContext | undefined;
15
+ /**
16
+ * Returns current EntityManager (if available).
17
+ */
18
+ static getEntityManager(name?: string): EntityManager | undefined;
19
+ }
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TransactionContext = void 0;
4
+ const async_hooks_1 = require("async_hooks");
5
+ class TransactionContext {
6
+ em;
7
+ static storage = new async_hooks_1.AsyncLocalStorage();
8
+ id;
9
+ constructor(em) {
10
+ this.em = em;
11
+ this.id = this.em._id;
12
+ }
13
+ /**
14
+ * Creates new TransactionContext instance and runs the code inside its domain.
15
+ */
16
+ static create(em, next) {
17
+ const context = new TransactionContext(em);
18
+ return this.storage.run(context, next);
19
+ }
20
+ /**
21
+ * Returns current TransactionContext (if available).
22
+ */
23
+ static currentTransactionContext() {
24
+ return this.storage.getStore();
25
+ }
26
+ /**
27
+ * Returns current EntityManager (if available).
28
+ */
29
+ static getEntityManager(name = /* istanbul ignore next */ 'default') {
30
+ const context = TransactionContext.currentTransactionContext();
31
+ return context?.em.name === name ? context.em : undefined;
32
+ }
33
+ }
34
+ exports.TransactionContext = TransactionContext;