@contember/engine-content-api 2.2.0-alpha.18 → 2.2.0-alpha.19

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 (385) hide show
  1. package/dist/development/index.cjs +3 -0
  2. package/dist/development/index.cjs.map +1 -1
  3. package/dist/development/index.js +4 -1
  4. package/dist/development/index.js.map +1 -1
  5. package/dist/development/src/ExecutionContainer.cjs +1 -0
  6. package/dist/development/src/ExecutionContainer.cjs.map +1 -1
  7. package/dist/development/src/ExecutionContainer.js +1 -0
  8. package/dist/development/src/ExecutionContainer.js.map +1 -1
  9. package/dist/development/src/extensions/hasManyToHasOneReducer/HasManyToHasOneReducerExecutionHandler.cjs +2 -1
  10. package/dist/development/src/extensions/hasManyToHasOneReducer/HasManyToHasOneReducerExecutionHandler.cjs.map +1 -1
  11. package/dist/development/src/extensions/hasManyToHasOneReducer/HasManyToHasOneReducerExecutionHandler.js +2 -1
  12. package/dist/development/src/extensions/hasManyToHasOneReducer/HasManyToHasOneReducerExecutionHandler.js.map +1 -1
  13. package/dist/development/src/extensions/hasManyToHasOneReducer/HasManyToHasOneRelationReducerVisitor.cjs +5 -1
  14. package/dist/development/src/extensions/hasManyToHasOneReducer/HasManyToHasOneRelationReducerVisitor.cjs.map +1 -1
  15. package/dist/development/src/extensions/hasManyToHasOneReducer/HasManyToHasOneRelationReducerVisitor.js +5 -1
  16. package/dist/development/src/extensions/hasManyToHasOneReducer/HasManyToHasOneRelationReducerVisitor.js.map +1 -1
  17. package/dist/development/src/extensions/paginatedHasMany/PaginatedHasManyExecutionHandler.cjs +2 -1
  18. package/dist/development/src/extensions/paginatedHasMany/PaginatedHasManyExecutionHandler.cjs.map +1 -1
  19. package/dist/development/src/extensions/paginatedHasMany/PaginatedHasManyExecutionHandler.js +2 -1
  20. package/dist/development/src/extensions/paginatedHasMany/PaginatedHasManyExecutionHandler.js.map +1 -1
  21. package/dist/development/src/extensions/paginatedHasMany/PaginatedHasManyFieldProviderVisitor.cjs +4 -1
  22. package/dist/development/src/extensions/paginatedHasMany/PaginatedHasManyFieldProviderVisitor.cjs.map +1 -1
  23. package/dist/development/src/extensions/paginatedHasMany/PaginatedHasManyFieldProviderVisitor.js +4 -1
  24. package/dist/development/src/extensions/paginatedHasMany/PaginatedHasManyFieldProviderVisitor.js.map +1 -1
  25. package/dist/development/src/input-validation/preValidation/UpdateInputPreValidationProcessor.cjs +24 -3
  26. package/dist/development/src/input-validation/preValidation/UpdateInputPreValidationProcessor.cjs.map +1 -1
  27. package/dist/development/src/input-validation/preValidation/UpdateInputPreValidationProcessor.js +24 -3
  28. package/dist/development/src/input-validation/preValidation/UpdateInputPreValidationProcessor.js.map +1 -1
  29. package/dist/development/src/inputProcessing/UpdateInputVisitor.cjs +52 -2
  30. package/dist/development/src/inputProcessing/UpdateInputVisitor.cjs.map +1 -1
  31. package/dist/development/src/inputProcessing/UpdateInputVisitor.js +52 -2
  32. package/dist/development/src/inputProcessing/UpdateInputVisitor.js.map +1 -1
  33. package/dist/development/src/mapper/ErrorUtils.cjs +10 -0
  34. package/dist/development/src/mapper/ErrorUtils.cjs.map +1 -1
  35. package/dist/development/src/mapper/ErrorUtils.js +10 -0
  36. package/dist/development/src/mapper/ErrorUtils.js.map +1 -1
  37. package/dist/development/src/mapper/Mapper.cjs +37 -1
  38. package/dist/development/src/mapper/Mapper.cjs.map +1 -1
  39. package/dist/development/src/mapper/Mapper.js +38 -2
  40. package/dist/development/src/mapper/Mapper.js.map +1 -1
  41. package/dist/development/src/mapper/MutationProcessorHelper.cjs +12 -0
  42. package/dist/development/src/mapper/MutationProcessorHelper.cjs.map +1 -1
  43. package/dist/development/src/mapper/MutationProcessorHelper.js +13 -1
  44. package/dist/development/src/mapper/MutationProcessorHelper.js.map +1 -1
  45. package/dist/development/src/mapper/Result.cjs +1 -0
  46. package/dist/development/src/mapper/Result.cjs.map +1 -1
  47. package/dist/development/src/mapper/Result.js +1 -0
  48. package/dist/development/src/mapper/Result.js.map +1 -1
  49. package/dist/development/src/mapper/delete/DeleteExecutor.cjs +1 -1
  50. package/dist/development/src/mapper/delete/DeleteExecutor.js +1 -1
  51. package/dist/development/src/mapper/select/handlers/MetaHandler.cjs +1 -1
  52. package/dist/development/src/mapper/select/handlers/MetaHandler.js +1 -1
  53. package/dist/development/src/mapper/select/optimizer/WhereOptimizer.cjs +2 -2
  54. package/dist/development/src/mapper/select/optimizer/WhereOptimizer.cjs.map +1 -1
  55. package/dist/development/src/mapper/select/optimizer/WhereOptimizer.js +1 -1
  56. package/dist/development/src/mapper/select/optimizer/WhereOptimizer.js.map +1 -1
  57. package/dist/development/src/mapper/select/optimizer/WhereReplacer.cjs +3 -3
  58. package/dist/development/src/mapper/select/optimizer/WhereReplacer.cjs.map +1 -1
  59. package/dist/development/src/mapper/select/optimizer/WhereReplacer.js +1 -1
  60. package/dist/development/src/mapper/select/optimizer/WhereReplacer.js.map +1 -1
  61. package/dist/development/src/mapper/update/SqlUpdateInputProcessor.cjs +6 -3
  62. package/dist/development/src/mapper/update/SqlUpdateInputProcessor.cjs.map +1 -1
  63. package/dist/development/src/mapper/update/SqlUpdateInputProcessor.js +7 -4
  64. package/dist/development/src/mapper/update/SqlUpdateInputProcessor.js.map +1 -1
  65. package/dist/development/src/mapper/update/Updater.cjs +1 -1
  66. package/dist/development/src/mapper/update/Updater.js +1 -1
  67. package/dist/development/src/mapper/update/relations/ManyHasManyUpdateInputProcessor.cjs +6 -0
  68. package/dist/development/src/mapper/update/relations/ManyHasManyUpdateInputProcessor.cjs.map +1 -1
  69. package/dist/development/src/mapper/update/relations/ManyHasManyUpdateInputProcessor.js +6 -0
  70. package/dist/development/src/mapper/update/relations/ManyHasManyUpdateInputProcessor.js.map +1 -1
  71. package/dist/development/src/mapper/update/relations/OneHasManyUpdateInputProcessor.cjs +6 -0
  72. package/dist/development/src/mapper/update/relations/OneHasManyUpdateInputProcessor.cjs.map +1 -1
  73. package/dist/development/src/mapper/update/relations/OneHasManyUpdateInputProcessor.js +6 -0
  74. package/dist/development/src/mapper/update/relations/OneHasManyUpdateInputProcessor.js.map +1 -1
  75. package/dist/development/src/mapper/update/relations/SetManyRelationHelper.cjs +123 -0
  76. package/dist/development/src/mapper/update/relations/SetManyRelationHelper.cjs.map +1 -0
  77. package/dist/development/src/mapper/update/relations/SetManyRelationHelper.js +123 -0
  78. package/dist/development/src/mapper/update/relations/SetManyRelationHelper.js.map +1 -0
  79. package/dist/development/src/resolvers/MutationResolver.cjs +4 -1
  80. package/dist/development/src/resolvers/MutationResolver.cjs.map +1 -1
  81. package/dist/development/src/resolvers/MutationResolver.js +4 -1
  82. package/dist/development/src/resolvers/MutationResolver.js.map +1 -1
  83. package/dist/development/src/resolvers/ReadHelpers.cjs +2 -1
  84. package/dist/development/src/resolvers/ReadHelpers.cjs.map +1 -1
  85. package/dist/development/src/resolvers/ReadHelpers.js +2 -1
  86. package/dist/development/src/resolvers/ReadHelpers.js.map +1 -1
  87. package/dist/development/src/schema/CustomTypesProvider.cjs +35 -14
  88. package/dist/development/src/schema/CustomTypesProvider.cjs.map +1 -1
  89. package/dist/development/src/schema/CustomTypesProvider.js +36 -15
  90. package/dist/development/src/schema/CustomTypesProvider.js.map +1 -1
  91. package/dist/development/src/schema/EntityTypeProvider.cjs +8 -5
  92. package/dist/development/src/schema/EntityTypeProvider.cjs.map +1 -1
  93. package/dist/development/src/schema/EntityTypeProvider.js +8 -5
  94. package/dist/development/src/schema/EntityTypeProvider.js.map +1 -1
  95. package/dist/development/src/schema/GraphQlSchemaBuilderFactory.cjs +1 -1
  96. package/dist/development/src/schema/GraphQlSchemaBuilderFactory.js +1 -1
  97. package/dist/development/src/schema/MutationProvider.cjs +4 -0
  98. package/dist/development/src/schema/MutationProvider.cjs.map +1 -1
  99. package/dist/development/src/schema/MutationProvider.js +4 -0
  100. package/dist/development/src/schema/MutationProvider.js.map +1 -1
  101. package/dist/development/src/schema/OrderByTypeProvider.cjs +8 -2
  102. package/dist/development/src/schema/OrderByTypeProvider.cjs.map +1 -1
  103. package/dist/development/src/schema/OrderByTypeProvider.js +9 -3
  104. package/dist/development/src/schema/OrderByTypeProvider.js.map +1 -1
  105. package/dist/development/src/schema/QueryProvider.cjs +3 -0
  106. package/dist/development/src/schema/QueryProvider.cjs.map +1 -1
  107. package/dist/development/src/schema/QueryProvider.js +3 -0
  108. package/dist/development/src/schema/QueryProvider.js.map +1 -1
  109. package/dist/development/src/schema/ValidationQueriesProvider.cjs +2 -0
  110. package/dist/development/src/schema/ValidationQueriesProvider.cjs.map +1 -1
  111. package/dist/development/src/schema/ValidationQueriesProvider.js +2 -0
  112. package/dist/development/src/schema/ValidationQueriesProvider.js.map +1 -1
  113. package/dist/development/src/schema/WhereTypeProvider.cjs +17 -5
  114. package/dist/development/src/schema/WhereTypeProvider.cjs.map +1 -1
  115. package/dist/development/src/schema/WhereTypeProvider.js +18 -6
  116. package/dist/development/src/schema/WhereTypeProvider.js.map +1 -1
  117. package/dist/development/src/schema/calendarDate.cjs +21 -0
  118. package/dist/development/src/schema/calendarDate.cjs.map +1 -0
  119. package/dist/development/src/schema/calendarDate.js +21 -0
  120. package/dist/development/src/schema/calendarDate.js.map +1 -0
  121. package/dist/development/src/schema/mutations/CreateEntityInputFieldVisitor.cjs +11 -3
  122. package/dist/development/src/schema/mutations/CreateEntityInputFieldVisitor.cjs.map +1 -1
  123. package/dist/development/src/schema/mutations/CreateEntityInputFieldVisitor.js +11 -3
  124. package/dist/development/src/schema/mutations/CreateEntityInputFieldVisitor.js.map +1 -1
  125. package/dist/development/src/schema/mutations/UpdateEntityInputFieldVisitor.cjs +11 -3
  126. package/dist/development/src/schema/mutations/UpdateEntityInputFieldVisitor.cjs.map +1 -1
  127. package/dist/development/src/schema/mutations/UpdateEntityInputFieldVisitor.js +11 -3
  128. package/dist/development/src/schema/mutations/UpdateEntityInputFieldVisitor.js.map +1 -1
  129. package/dist/development/src/schema/mutations/UpdateEntityRelationInputFieldVisitor.cjs +39 -2
  130. package/dist/development/src/schema/mutations/UpdateEntityRelationInputFieldVisitor.cjs.map +1 -1
  131. package/dist/development/src/schema/mutations/UpdateEntityRelationInputFieldVisitor.js +40 -3
  132. package/dist/development/src/schema/mutations/UpdateEntityRelationInputFieldVisitor.js.map +1 -1
  133. package/dist/development/src/schema/utils.cjs +10 -0
  134. package/dist/development/src/schema/utils.cjs.map +1 -1
  135. package/dist/development/src/schema/utils.js +11 -1
  136. package/dist/development/src/schema/utils.js.map +1 -1
  137. package/dist/production/index.cjs +3 -0
  138. package/dist/production/index.cjs.map +1 -1
  139. package/dist/production/index.js +4 -1
  140. package/dist/production/index.js.map +1 -1
  141. package/dist/production/src/ExecutionContainer.cjs +1 -0
  142. package/dist/production/src/ExecutionContainer.cjs.map +1 -1
  143. package/dist/production/src/ExecutionContainer.js +1 -0
  144. package/dist/production/src/ExecutionContainer.js.map +1 -1
  145. package/dist/production/src/extensions/hasManyToHasOneReducer/HasManyToHasOneReducerExecutionHandler.cjs +2 -1
  146. package/dist/production/src/extensions/hasManyToHasOneReducer/HasManyToHasOneReducerExecutionHandler.cjs.map +1 -1
  147. package/dist/production/src/extensions/hasManyToHasOneReducer/HasManyToHasOneReducerExecutionHandler.js +2 -1
  148. package/dist/production/src/extensions/hasManyToHasOneReducer/HasManyToHasOneReducerExecutionHandler.js.map +1 -1
  149. package/dist/production/src/extensions/hasManyToHasOneReducer/HasManyToHasOneRelationReducerVisitor.cjs +5 -1
  150. package/dist/production/src/extensions/hasManyToHasOneReducer/HasManyToHasOneRelationReducerVisitor.cjs.map +1 -1
  151. package/dist/production/src/extensions/hasManyToHasOneReducer/HasManyToHasOneRelationReducerVisitor.js +5 -1
  152. package/dist/production/src/extensions/hasManyToHasOneReducer/HasManyToHasOneRelationReducerVisitor.js.map +1 -1
  153. package/dist/production/src/extensions/paginatedHasMany/PaginatedHasManyExecutionHandler.cjs +2 -1
  154. package/dist/production/src/extensions/paginatedHasMany/PaginatedHasManyExecutionHandler.cjs.map +1 -1
  155. package/dist/production/src/extensions/paginatedHasMany/PaginatedHasManyExecutionHandler.js +2 -1
  156. package/dist/production/src/extensions/paginatedHasMany/PaginatedHasManyExecutionHandler.js.map +1 -1
  157. package/dist/production/src/extensions/paginatedHasMany/PaginatedHasManyFieldProviderVisitor.cjs +4 -1
  158. package/dist/production/src/extensions/paginatedHasMany/PaginatedHasManyFieldProviderVisitor.cjs.map +1 -1
  159. package/dist/production/src/extensions/paginatedHasMany/PaginatedHasManyFieldProviderVisitor.js +4 -1
  160. package/dist/production/src/extensions/paginatedHasMany/PaginatedHasManyFieldProviderVisitor.js.map +1 -1
  161. package/dist/production/src/input-validation/preValidation/UpdateInputPreValidationProcessor.cjs +24 -3
  162. package/dist/production/src/input-validation/preValidation/UpdateInputPreValidationProcessor.cjs.map +1 -1
  163. package/dist/production/src/input-validation/preValidation/UpdateInputPreValidationProcessor.js +24 -3
  164. package/dist/production/src/input-validation/preValidation/UpdateInputPreValidationProcessor.js.map +1 -1
  165. package/dist/production/src/inputProcessing/UpdateInputVisitor.cjs +52 -2
  166. package/dist/production/src/inputProcessing/UpdateInputVisitor.cjs.map +1 -1
  167. package/dist/production/src/inputProcessing/UpdateInputVisitor.js +52 -2
  168. package/dist/production/src/inputProcessing/UpdateInputVisitor.js.map +1 -1
  169. package/dist/production/src/mapper/ErrorUtils.cjs +10 -0
  170. package/dist/production/src/mapper/ErrorUtils.cjs.map +1 -1
  171. package/dist/production/src/mapper/ErrorUtils.js +10 -0
  172. package/dist/production/src/mapper/ErrorUtils.js.map +1 -1
  173. package/dist/production/src/mapper/Mapper.cjs +37 -1
  174. package/dist/production/src/mapper/Mapper.cjs.map +1 -1
  175. package/dist/production/src/mapper/Mapper.js +38 -2
  176. package/dist/production/src/mapper/Mapper.js.map +1 -1
  177. package/dist/production/src/mapper/MutationProcessorHelper.cjs +12 -0
  178. package/dist/production/src/mapper/MutationProcessorHelper.cjs.map +1 -1
  179. package/dist/production/src/mapper/MutationProcessorHelper.js +13 -1
  180. package/dist/production/src/mapper/MutationProcessorHelper.js.map +1 -1
  181. package/dist/production/src/mapper/Result.cjs +1 -0
  182. package/dist/production/src/mapper/Result.cjs.map +1 -1
  183. package/dist/production/src/mapper/Result.js +1 -0
  184. package/dist/production/src/mapper/Result.js.map +1 -1
  185. package/dist/production/src/mapper/delete/DeleteExecutor.cjs +1 -1
  186. package/dist/production/src/mapper/delete/DeleteExecutor.js +1 -1
  187. package/dist/production/src/mapper/select/handlers/MetaHandler.cjs +1 -1
  188. package/dist/production/src/mapper/select/handlers/MetaHandler.js +1 -1
  189. package/dist/production/src/mapper/select/optimizer/WhereOptimizer.cjs +2 -2
  190. package/dist/production/src/mapper/select/optimizer/WhereOptimizer.cjs.map +1 -1
  191. package/dist/production/src/mapper/select/optimizer/WhereOptimizer.js +1 -1
  192. package/dist/production/src/mapper/select/optimizer/WhereOptimizer.js.map +1 -1
  193. package/dist/production/src/mapper/select/optimizer/WhereReplacer.cjs +3 -3
  194. package/dist/production/src/mapper/select/optimizer/WhereReplacer.cjs.map +1 -1
  195. package/dist/production/src/mapper/select/optimizer/WhereReplacer.js +1 -1
  196. package/dist/production/src/mapper/select/optimizer/WhereReplacer.js.map +1 -1
  197. package/dist/production/src/mapper/update/SqlUpdateInputProcessor.cjs +6 -3
  198. package/dist/production/src/mapper/update/SqlUpdateInputProcessor.cjs.map +1 -1
  199. package/dist/production/src/mapper/update/SqlUpdateInputProcessor.js +7 -4
  200. package/dist/production/src/mapper/update/SqlUpdateInputProcessor.js.map +1 -1
  201. package/dist/production/src/mapper/update/Updater.cjs +1 -1
  202. package/dist/production/src/mapper/update/Updater.js +1 -1
  203. package/dist/production/src/mapper/update/relations/ManyHasManyUpdateInputProcessor.cjs +6 -0
  204. package/dist/production/src/mapper/update/relations/ManyHasManyUpdateInputProcessor.cjs.map +1 -1
  205. package/dist/production/src/mapper/update/relations/ManyHasManyUpdateInputProcessor.js +6 -0
  206. package/dist/production/src/mapper/update/relations/ManyHasManyUpdateInputProcessor.js.map +1 -1
  207. package/dist/production/src/mapper/update/relations/OneHasManyUpdateInputProcessor.cjs +6 -0
  208. package/dist/production/src/mapper/update/relations/OneHasManyUpdateInputProcessor.cjs.map +1 -1
  209. package/dist/production/src/mapper/update/relations/OneHasManyUpdateInputProcessor.js +6 -0
  210. package/dist/production/src/mapper/update/relations/OneHasManyUpdateInputProcessor.js.map +1 -1
  211. package/dist/production/src/mapper/update/relations/SetManyRelationHelper.cjs +123 -0
  212. package/dist/production/src/mapper/update/relations/SetManyRelationHelper.cjs.map +1 -0
  213. package/dist/production/src/mapper/update/relations/SetManyRelationHelper.js +123 -0
  214. package/dist/production/src/mapper/update/relations/SetManyRelationHelper.js.map +1 -0
  215. package/dist/production/src/resolvers/MutationResolver.cjs +4 -1
  216. package/dist/production/src/resolvers/MutationResolver.cjs.map +1 -1
  217. package/dist/production/src/resolvers/MutationResolver.js +4 -1
  218. package/dist/production/src/resolvers/MutationResolver.js.map +1 -1
  219. package/dist/production/src/resolvers/ReadHelpers.cjs +2 -1
  220. package/dist/production/src/resolvers/ReadHelpers.cjs.map +1 -1
  221. package/dist/production/src/resolvers/ReadHelpers.js +2 -1
  222. package/dist/production/src/resolvers/ReadHelpers.js.map +1 -1
  223. package/dist/production/src/schema/CustomTypesProvider.cjs +35 -14
  224. package/dist/production/src/schema/CustomTypesProvider.cjs.map +1 -1
  225. package/dist/production/src/schema/CustomTypesProvider.js +36 -15
  226. package/dist/production/src/schema/CustomTypesProvider.js.map +1 -1
  227. package/dist/production/src/schema/EntityTypeProvider.cjs +8 -5
  228. package/dist/production/src/schema/EntityTypeProvider.cjs.map +1 -1
  229. package/dist/production/src/schema/EntityTypeProvider.js +8 -5
  230. package/dist/production/src/schema/EntityTypeProvider.js.map +1 -1
  231. package/dist/production/src/schema/GraphQlSchemaBuilderFactory.cjs +1 -1
  232. package/dist/production/src/schema/GraphQlSchemaBuilderFactory.js +1 -1
  233. package/dist/production/src/schema/MutationProvider.cjs +4 -0
  234. package/dist/production/src/schema/MutationProvider.cjs.map +1 -1
  235. package/dist/production/src/schema/MutationProvider.js +4 -0
  236. package/dist/production/src/schema/MutationProvider.js.map +1 -1
  237. package/dist/production/src/schema/OrderByTypeProvider.cjs +8 -2
  238. package/dist/production/src/schema/OrderByTypeProvider.cjs.map +1 -1
  239. package/dist/production/src/schema/OrderByTypeProvider.js +9 -3
  240. package/dist/production/src/schema/OrderByTypeProvider.js.map +1 -1
  241. package/dist/production/src/schema/QueryProvider.cjs +3 -0
  242. package/dist/production/src/schema/QueryProvider.cjs.map +1 -1
  243. package/dist/production/src/schema/QueryProvider.js +3 -0
  244. package/dist/production/src/schema/QueryProvider.js.map +1 -1
  245. package/dist/production/src/schema/ValidationQueriesProvider.cjs +2 -0
  246. package/dist/production/src/schema/ValidationQueriesProvider.cjs.map +1 -1
  247. package/dist/production/src/schema/ValidationQueriesProvider.js +2 -0
  248. package/dist/production/src/schema/ValidationQueriesProvider.js.map +1 -1
  249. package/dist/production/src/schema/WhereTypeProvider.cjs +17 -5
  250. package/dist/production/src/schema/WhereTypeProvider.cjs.map +1 -1
  251. package/dist/production/src/schema/WhereTypeProvider.js +18 -6
  252. package/dist/production/src/schema/WhereTypeProvider.js.map +1 -1
  253. package/dist/production/src/schema/calendarDate.cjs +21 -0
  254. package/dist/production/src/schema/calendarDate.cjs.map +1 -0
  255. package/dist/production/src/schema/calendarDate.js +21 -0
  256. package/dist/production/src/schema/calendarDate.js.map +1 -0
  257. package/dist/production/src/schema/mutations/CreateEntityInputFieldVisitor.cjs +11 -3
  258. package/dist/production/src/schema/mutations/CreateEntityInputFieldVisitor.cjs.map +1 -1
  259. package/dist/production/src/schema/mutations/CreateEntityInputFieldVisitor.js +11 -3
  260. package/dist/production/src/schema/mutations/CreateEntityInputFieldVisitor.js.map +1 -1
  261. package/dist/production/src/schema/mutations/UpdateEntityInputFieldVisitor.cjs +11 -3
  262. package/dist/production/src/schema/mutations/UpdateEntityInputFieldVisitor.cjs.map +1 -1
  263. package/dist/production/src/schema/mutations/UpdateEntityInputFieldVisitor.js +11 -3
  264. package/dist/production/src/schema/mutations/UpdateEntityInputFieldVisitor.js.map +1 -1
  265. package/dist/production/src/schema/mutations/UpdateEntityRelationInputFieldVisitor.cjs +39 -2
  266. package/dist/production/src/schema/mutations/UpdateEntityRelationInputFieldVisitor.cjs.map +1 -1
  267. package/dist/production/src/schema/mutations/UpdateEntityRelationInputFieldVisitor.js +40 -3
  268. package/dist/production/src/schema/mutations/UpdateEntityRelationInputFieldVisitor.js.map +1 -1
  269. package/dist/production/src/schema/utils.cjs +10 -0
  270. package/dist/production/src/schema/utils.cjs.map +1 -1
  271. package/dist/production/src/schema/utils.js +11 -1
  272. package/dist/production/src/schema/utils.js.map +1 -1
  273. package/dist/tests/cases/integration/graphQlRequests/update/manyHasManyInverse/set.test.d.ts +2 -0
  274. package/dist/tests/cases/integration/graphQlRequests/update/manyHasManyInverse/set.test.d.ts.map +1 -0
  275. package/dist/tests/cases/integration/graphQlRequests/update/manyHasManyOwning/set.test.d.ts +2 -0
  276. package/dist/tests/cases/integration/graphQlRequests/update/manyHasManyOwning/set.test.d.ts.map +1 -0
  277. package/dist/tests/cases/integration/graphQlRequests/update/oneHasMany/set.test.d.ts +2 -0
  278. package/dist/tests/cases/integration/graphQlRequests/update/oneHasMany/set.test.d.ts.map +1 -0
  279. package/dist/tests/cases/unit/checkViolationError.test.d.ts +2 -0
  280. package/dist/tests/cases/unit/checkViolationError.test.d.ts.map +1 -0
  281. package/dist/tests/cases/unit/dateType.test.d.ts +2 -0
  282. package/dist/tests/cases/unit/dateType.test.d.ts.map +1 -0
  283. package/dist/tests/tsconfig.tsbuildinfo +1 -1
  284. package/dist/types/extensions/hasManyToHasOneReducer/HasManyToHasOneRelationReducerVisitor.d.ts.map +1 -1
  285. package/dist/types/extensions/paginatedHasMany/PaginatedHasManyFieldProviderVisitor.d.ts.map +1 -1
  286. package/dist/types/input-validation/preValidation/UpdateInputPreValidationProcessor.d.ts +6 -0
  287. package/dist/types/input-validation/preValidation/UpdateInputPreValidationProcessor.d.ts.map +1 -1
  288. package/dist/types/inputProcessing/UpdateInputProcessor.d.ts +7 -0
  289. package/dist/types/inputProcessing/UpdateInputProcessor.d.ts.map +1 -1
  290. package/dist/types/inputProcessing/UpdateInputVisitor.d.ts +2 -0
  291. package/dist/types/inputProcessing/UpdateInputVisitor.d.ts.map +1 -1
  292. package/dist/types/mapper/ErrorUtils.d.ts.map +1 -1
  293. package/dist/types/mapper/Mapper.d.ts +5 -0
  294. package/dist/types/mapper/Mapper.d.ts.map +1 -1
  295. package/dist/types/mapper/MutationProcessorHelper.d.ts +3 -0
  296. package/dist/types/mapper/MutationProcessorHelper.d.ts.map +1 -1
  297. package/dist/types/mapper/Result.d.ts +2 -1
  298. package/dist/types/mapper/Result.d.ts.map +1 -1
  299. package/dist/types/mapper/types.d.ts +8 -1
  300. package/dist/types/mapper/types.d.ts.map +1 -1
  301. package/dist/types/mapper/update/SqlUpdateInputProcessor.d.ts.map +1 -1
  302. package/dist/types/mapper/update/relations/ManyHasManyUpdateInputProcessor.d.ts +5 -0
  303. package/dist/types/mapper/update/relations/ManyHasManyUpdateInputProcessor.d.ts.map +1 -1
  304. package/dist/types/mapper/update/relations/OneHasManyUpdateInputProcessor.d.ts +5 -0
  305. package/dist/types/mapper/update/relations/OneHasManyUpdateInputProcessor.d.ts.map +1 -1
  306. package/dist/types/mapper/update/relations/SetManyRelationHelper.d.ts +67 -0
  307. package/dist/types/mapper/update/relations/SetManyRelationHelper.d.ts.map +1 -0
  308. package/dist/types/resolvers/MutationResolver.d.ts.map +1 -1
  309. package/dist/types/schema/CustomTypesProvider.d.ts.map +1 -1
  310. package/dist/types/schema/EntityTypeProvider.d.ts.map +1 -1
  311. package/dist/types/schema/MutationProvider.d.ts.map +1 -1
  312. package/dist/types/schema/OrderByTypeProvider.d.ts.map +1 -1
  313. package/dist/types/schema/QueryProvider.d.ts.map +1 -1
  314. package/dist/types/schema/ValidationQueriesProvider.d.ts.map +1 -1
  315. package/dist/types/schema/WhereTypeProvider.d.ts.map +1 -1
  316. package/dist/types/schema/calendarDate.d.ts +6 -0
  317. package/dist/types/schema/calendarDate.d.ts.map +1 -0
  318. package/dist/types/schema/index.d.ts +1 -0
  319. package/dist/types/schema/index.d.ts.map +1 -1
  320. package/dist/types/schema/mutations/CreateEntityInputFieldVisitor.d.ts.map +1 -1
  321. package/dist/types/schema/mutations/UpdateEntityInputFieldVisitor.d.ts +3 -0
  322. package/dist/types/schema/mutations/UpdateEntityInputFieldVisitor.d.ts.map +1 -1
  323. package/dist/types/schema/mutations/UpdateEntityRelationInputFieldVisitor.d.ts +1 -0
  324. package/dist/types/schema/mutations/UpdateEntityRelationInputFieldVisitor.d.ts.map +1 -1
  325. package/dist/types/schema/utils.d.ts +7 -0
  326. package/dist/types/schema/utils.d.ts.map +1 -1
  327. package/dist/types/tsconfig.tsbuildinfo +1 -1
  328. package/package.json +10 -10
  329. package/src/extensions/hasManyToHasOneReducer/HasManyToHasOneRelationReducerVisitor.ts +3 -0
  330. package/src/extensions/paginatedHasMany/PaginatedHasManyFieldProviderVisitor.ts +9 -7
  331. package/src/input-validation/preValidation/UpdateInputPreValidationProcessor.ts +29 -0
  332. package/src/inputProcessing/UpdateInputProcessor.ts +6 -0
  333. package/src/inputProcessing/UpdateInputVisitor.ts +64 -2
  334. package/src/mapper/ErrorUtils.ts +11 -0
  335. package/src/mapper/Mapper.ts +61 -1
  336. package/src/mapper/MutationProcessorHelper.ts +14 -0
  337. package/src/mapper/Result.ts +1 -0
  338. package/src/mapper/select/optimizer/WhereOptimizer.ts +1 -1
  339. package/src/mapper/select/optimizer/WhereReplacer.ts +1 -1
  340. package/src/mapper/types.ts +16 -1
  341. package/src/mapper/update/SqlUpdateInputProcessor.ts +4 -1
  342. package/src/mapper/update/relations/ManyHasManyUpdateInputProcessor.ts +9 -0
  343. package/src/mapper/update/relations/OneHasManyUpdateInputProcessor.ts +9 -0
  344. package/src/mapper/update/relations/SetManyRelationHelper.ts +199 -0
  345. package/src/resolvers/MutationResolver.ts +2 -0
  346. package/src/schema/CustomTypesProvider.ts +40 -15
  347. package/src/schema/EntityTypeProvider.ts +8 -4
  348. package/src/schema/MutationProvider.ts +4 -0
  349. package/src/schema/OrderByTypeProvider.ts +9 -3
  350. package/src/schema/QueryProvider.ts +3 -0
  351. package/src/schema/ValidationQueriesProvider.ts +2 -0
  352. package/src/schema/WhereTypeProvider.ts +18 -6
  353. package/src/schema/calendarDate.ts +26 -0
  354. package/src/schema/index.ts +1 -0
  355. package/src/schema/mutations/CreateEntityInputFieldVisitor.ts +10 -2
  356. package/src/schema/mutations/UpdateEntityInputFieldVisitor.ts +10 -2
  357. package/src/schema/mutations/UpdateEntityRelationInputFieldVisitor.ts +66 -7
  358. package/src/schema/utils.ts +14 -0
  359. package/src/tsconfig.json +2 -1
  360. package/tests/cases/integration/graphQlRequests/update/manyHasManyInverse/set.test.ts +219 -0
  361. package/tests/cases/integration/graphQlRequests/update/manyHasManyOwning/set.test.ts +479 -0
  362. package/tests/cases/integration/graphQlRequests/update/oneHasMany/set.test.ts +948 -0
  363. package/tests/cases/integration/graphQlSchema/graphQlSchemaBuilder.test.ts +102 -1
  364. package/tests/cases/integration/graphQlSchema/schema-acl-allowed.gql +17 -0
  365. package/tests/cases/integration/graphQlSchema/schema-acl-create-only.gql +1 -0
  366. package/tests/cases/integration/graphQlSchema/schema-acl-restricted-create.gql +14 -0
  367. package/tests/cases/integration/graphQlSchema/schema-acl-restricted-delete.gql +11 -0
  368. package/tests/cases/integration/graphQlSchema/schema-acl-restricted-read.gql +254 -0
  369. package/tests/cases/integration/graphQlSchema/schema-acl-restricted-update.gql +1 -0
  370. package/tests/cases/integration/graphQlSchema/schema-acl.gql +1 -0
  371. package/tests/cases/integration/graphQlSchema/schema-aliased-type.gql +1 -0
  372. package/tests/cases/integration/graphQlSchema/schema-array.gql +1 -0
  373. package/tests/cases/integration/graphQlSchema/schema-basic.gql +50 -0
  374. package/tests/cases/integration/graphQlSchema/schema-bug-66.gql +17 -0
  375. package/tests/cases/integration/graphQlSchema/schema-column-types.gql +1 -0
  376. package/tests/cases/integration/graphQlSchema/schema-custom-primary.gql +50 -0
  377. package/tests/cases/integration/graphQlSchema/schema-deprecation.gql +962 -0
  378. package/tests/cases/integration/graphQlSchema/schema-description.gql +992 -0
  379. package/tests/cases/integration/graphQlSchema/schema-has-many-reduction.gql +17 -0
  380. package/tests/cases/integration/graphQlSchema/schema-mixed-root-through.gql +1 -0
  381. package/tests/cases/integration/graphQlSchema/schema-new-builder.gql +50 -0
  382. package/tests/cases/integration/graphQlSchema/schema-no-root-ops.gql +1 -0
  383. package/tests/cases/unit/checkViolationError.test.ts +49 -0
  384. package/tests/cases/unit/dateType.test.ts +46 -0
  385. package/tests/cases/unit/decimalType.test.ts +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"ErrorUtils.js","sources":["../../../../../packages/engine-content-api/src/mapper/ErrorUtils.ts"],"sourcesContent":["import {\n\tConstraintType,\n\tInputErrorKind,\n\tMutationConstraintViolationError,\n\tMutationInputError,\n\tMutationResult,\n\tMutationResultHint,\n\tMutationResultList,\n\tMutationSqlError,\n} from './Result.js'\nimport * as Database from '@contember/database'\nimport { UniqueWhereError } from '../inputProcessing/index.js'\nimport { Model } from '@contember/schema'\nimport { acceptFieldVisitor, tryGetColumnName } from '@contember/schema-utils'\nimport { logger } from '@contember/logger'\nimport { DatabaseMetadata } from '@contember/database'\n\ntype UniqueConstraintResult = {\n\tentity: Model.Entity\n\tfields: string[]\n}\n\nconst getEntityByTableName = (model: Model.Schema, tableName: string) => Object.values(model.entities).find(it => it.tableName === tableName)\n\nconst findUniqueConstraint = (\n\tmodel: Model.Schema,\n\tdatabaseMetadata: DatabaseMetadata,\n\ttableName: string,\n\tconstraintName: string,\n): UniqueConstraintResult | null => {\n\tconst constraint = databaseMetadata.uniqueConstraints.filter({ tableName, constraintName }).first()\n\tif (!constraint) {\n\t\treturn null\n\t}\n\tconst entity = getEntityByTableName(model, constraint.tableName)\n\tif (!entity) {\n\t\treturn null\n\t}\n\tconst fieldsInConstraint: string[] = []\n\tfor (const field of Object.values(entity.fields)) {\n\t\tconst columnName = tryGetColumnName(model, entity, field.name)\n\t\tif (columnName && constraint.columnNames.includes(columnName)) {\n\t\t\tfieldsInConstraint.push(field.name)\n\t\t}\n\t}\n\tif (fieldsInConstraint.length === constraint.columnNames.length) {\n\t\treturn { entity, fields: fieldsInConstraint }\n\t}\n\treturn null\n}\n\ntype RelationInfo = {\n\towningEntity: Model.Entity\n\towningRelation: Model.Relation\n\ttargetEntity: Model.Entity\n}\n\nconst findForeignConstraint = (\n\tmodel: Model.Schema,\n\tdatabaseMetadata: DatabaseMetadata,\n\ttableName: string,\n\tconstraintName: string,\n): RelationInfo | null => {\n\tconst constraint = databaseMetadata.foreignKeys.filter({ fromTable: tableName, constraintName }).first()\n\tif (!constraint) {\n\t\treturn null\n\t}\n\tconst owningEntity = getEntityByTableName(model, constraint.fromTable)\n\tif (!owningEntity) {\n\t\t// todo m:n\n\t\treturn null\n\t}\n\n\tconst targetEntity = getEntityByTableName(model, constraint.toTable)\n\tif (!targetEntity) {\n\t\treturn null\n\t}\n\tfor (const field of Object.values(owningEntity.fields)) {\n\t\tconst relation = acceptFieldVisitor<(Model.Relation & Model.JoiningColumnRelation) | null>(model, owningEntity, field, {\n\t\t\tvisitColumn: () => null,\n\t\t\tvisitOneHasOneInverse: () => null,\n\t\t\tvisitManyHasManyInverse: () => null,\n\t\t\tvisitManyHasManyOwning: () => null,\n\t\t\tvisitOneHasMany: () => null,\n\t\t\tvisitOneHasOneOwning: ({ relation }) => relation,\n\t\t\tvisitManyHasOne: ({ relation }) => relation,\n\t\t})\n\t\tif (relation && relation.joiningColumn.columnName === constraint.fromColumn) {\n\t\t\treturn {\n\t\t\t\towningEntity,\n\t\t\t\towningRelation: relation,\n\t\t\t\ttargetEntity,\n\t\t\t}\n\t\t}\n\t}\n\treturn null\n}\n\nexport const convertError = (\n\tschema: Model.Schema,\n\tdatabaseMetadata: DatabaseMetadata,\n\te: any,\n): MutationResult => {\n\tif (e instanceof Database.NotNullViolationError) {\n\t\treturn new MutationConstraintViolationError([], ConstraintType.notNull, e.originalMessage, [\n\t\t\tMutationResultHint.sqlError,\n\t\t])\n\t}\n\tif (e instanceof Database.ForeignKeyViolationError) {\n\t\tconst relationInfo = e.constraint && e.table ? findForeignConstraint(schema, databaseMetadata, e.table, e.constraint) : null\n\t\tconst violationDetail: string = 'detail' in e.previous ? e.previous.detail : ''\n\t\tconst matchResult = violationDetail.match(/^Key \\(.+\\)=\\((.+)\\) is still referenced from table/)\n\t\tconst message = relationInfo\n\t\t\t? `Cannot delete ${matchResult ? `row ${matchResult[1]}` : 'unknown row'}`\n\t\t\t\t+ ` of entity ${relationInfo.targetEntity.name},`\n\t\t\t\t+ ` because it is still referenced from ${relationInfo.owningEntity.name}::${relationInfo.owningRelation.name}.`\n\t\t\t\t+ ' This is possibly caused by ACL denial or by missing \"on delete cascade\"'\n\t\t\t: e.originalMessage\n\t\treturn new MutationConstraintViolationError([], ConstraintType.foreignKey, message, [MutationResultHint.sqlError])\n\t}\n\tif (e instanceof Database.UniqueViolationError) {\n\t\tconst constraint = e.constraint && e.table ? findUniqueConstraint(schema, databaseMetadata, e.table, e.constraint) : null\n\t\tconst violationDetail: string = 'detail' in e.previous ? e.previous.detail : ''\n\t\tconst matchResult = violationDetail.match(/^Key \\(.+\\)=\\((.+)\\) already exists\\.$/)\n\t\tconst values = matchResult?.[1]\n\t\tconst message = constraint\n\t\t\t? `${values ? `Value (${values})` : 'Unknown value'}`\n\t\t\t\t+ ` already exists in unique columns (${constraint.fields.join(', ')}) on entity ${constraint.entity.name}`\n\t\t\t: e.originalMessage\n\t\tconst paths = constraint ? constraint.fields.map(it => [{ field: it }]) : []\n\t\treturn new MutationConstraintViolationError(paths, ConstraintType.uniqueKey, message, [MutationResultHint.sqlError])\n\t}\n\tif (e instanceof UniqueWhereError) {\n\t\treturn new MutationInputError([], InputErrorKind.nonUniqueWhere, e.message)\n\t}\n\tif (e instanceof Database.InvalidDataError) {\n\t\treturn new MutationInputError([], InputErrorKind.invalidData, e.originalMessage, [MutationResultHint.sqlError])\n\t}\n\tif (e instanceof Database.SerializationFailureError) {\n\t\tthrow e\n\t}\n\tif (e instanceof Database.TransactionAbortedError) {\n\t\treturn new MutationSqlError([], e.originalMessage, [MutationResultHint.subSequentSqlError])\n\t}\n\tif (e instanceof Database.CannotCommitError) {\n\t\tlogger.error(e, { loc: 'convertError' })\n\t\treturn new MutationSqlError([], e.originalMessage, [MutationResultHint.sqlError])\n\t}\n\tif (e instanceof Database.QueryError) {\n\t\tlogger.error(e, { loc: 'convertError' })\n\t\tconst message = hasClientFacingMessage(e.code) ? e.originalMessage : 'Database query failed'\n\t\treturn new MutationSqlError([], message, [MutationResultHint.sqlError])\n\t}\n\tthrow e\n}\n\n// Data (22) and integrity (23) errors and project trigger exceptions (P0001) carry messages clients act on. Other\n// messages (e.g. class 42) can quote internal SQL identifiers, which embed ACL predicate names.\nconst hasClientFacingMessage = (code: string | undefined): boolean =>\n\tcode !== undefined && (code.startsWith('22') || code.startsWith('23') || code === 'P0001')\n\nexport const tryMutation = async (\n\tschema: Model.Schema,\n\tdatabaseMetadata: DatabaseMetadata,\n\tcb: () => Promise<MutationResultList>,\n): Promise<MutationResultList> => {\n\ttry {\n\t\treturn await cb()\n\t} catch (e) {\n\t\treturn [convertError(schema, databaseMetadata, e)]\n\t}\n}\n"],"names":["relation"],"mappings":";;;;;;AAsBA,MAAM,uBAAuB,CAAC,OAAqB,cAAsB,OAAO,OAAO,MAAM,QAAQ,EAAE,KAAK,CAAA,OAAM,GAAG,cAAc,SAAS;AAE5I,MAAM,uBAAuB,CAC5B,OACA,kBACA,WACA,mBACmC;AACnC,QAAM,aAAa,iBAAiB,kBAAkB,OAAO,EAAE,WAAW,gBAAgB,EAAE,MAAA;AAC5F,MAAI,CAAC,YAAY;AAChB,WAAO;AAAA,EACR;AACA,QAAM,SAAS,qBAAqB,OAAO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,WAAW,SAAS,CAAC,mBAAmB,QAAQ,CAAC;AAAA,EACpH;AACA,MAAI,aAAa,kBAAkB;AAClC,WAAO,IAAI,mBAAmB,CAAA,GAAI,eAAe,gBAAgB,EAAE,OAAO;AAAA,EAC3E;AACA,MAAI,aAAa,SAAS,kBAAkB;AAC3C,WAAO,IAAI,mBAAmB,CAAA,GAAI,eAAe,aAAa,EAAE,iBAAiB,CAAC,mBAAmB,QAAQ,CAAC;AAAA,EAC/G;AACA,MAAI,aAAa,SAAS,2BAA2B;AACpD,UAAM;AAAA,EACP;AACA,MAAI,aAAa,SAAS,yBAAyB;AAClD,WAAO,IAAI,iBAAiB,IAAI,EAAE,iBAAiB,CAAC,mBAAmB,kBAAkB,CAAC;AAAA,EAC3F;AACA,MAAI,aAAa,SAAS,mBAAmB;AAC5C,WAAO,MAAM,GAAG,EAAE,KAAK,gBAAgB;AACvC,WAAO,IAAI,iBAAiB,IAAI,EAAE,iBAAiB,CAAC,mBAAmB,QAAQ,CAAC;AAAA,EACjF;AACA,MAAI,aAAa,SAAS,YAAY;AACrC,WAAO,MAAM,GAAG,EAAE,KAAK,gBAAgB;AACvC,UAAM,UAAU,uBAAuB,EAAE,IAAI,IAAI,EAAE,kBAAkB;AACrE,WAAO,IAAI,iBAAiB,CAAA,GAAI,SAAS,CAAC,mBAAmB,QAAQ,CAAC;AAAA,EACvE;AACA,QAAM;AACP;AAIA,MAAM,yBAAyB,CAAC,SAC/B,SAAS,WAAc,KAAK,WAAW,IAAI,KAAK,KAAK,WAAW,IAAI,KAAK,SAAS;AAE5E,MAAM,cAAc,OAC1B,QACA,kBACA,OACiC;AACjC,MAAI;AACH,WAAO,MAAM,GAAA;AAAA,EACd,SAAS,GAAG;AACX,WAAO,CAAC,aAAa,QAAQ,kBAAkB,CAAC,CAAC;AAAA,EAClD;AACD;"}
1
+ {"version":3,"file":"ErrorUtils.js","sources":["../../../../../packages/engine-content-api/src/mapper/ErrorUtils.ts"],"sourcesContent":["import {\n\tConstraintType,\n\tInputErrorKind,\n\tMutationConstraintViolationError,\n\tMutationInputError,\n\tMutationResult,\n\tMutationResultHint,\n\tMutationResultList,\n\tMutationSqlError,\n} from './Result.js'\nimport * as Database from '@contember/database'\nimport { UniqueWhereError } from '../inputProcessing/index.js'\nimport { Model } from '@contember/schema'\nimport { acceptFieldVisitor, tryGetColumnName } from '@contember/schema-utils'\nimport { logger } from '@contember/logger'\nimport { DatabaseMetadata } from '@contember/database'\n\ntype UniqueConstraintResult = {\n\tentity: Model.Entity\n\tfields: string[]\n}\n\nconst getEntityByTableName = (model: Model.Schema, tableName: string) => Object.values(model.entities).find(it => it.tableName === tableName)\n\nconst findUniqueConstraint = (\n\tmodel: Model.Schema,\n\tdatabaseMetadata: DatabaseMetadata,\n\ttableName: string,\n\tconstraintName: string,\n): UniqueConstraintResult | null => {\n\tconst constraint = databaseMetadata.uniqueConstraints.filter({ tableName, constraintName }).first()\n\tif (!constraint) {\n\t\treturn null\n\t}\n\tconst entity = getEntityByTableName(model, constraint.tableName)\n\tif (!entity) {\n\t\treturn null\n\t}\n\tconst fieldsInConstraint: string[] = []\n\tfor (const field of Object.values(entity.fields)) {\n\t\tconst columnName = tryGetColumnName(model, entity, field.name)\n\t\tif (columnName && constraint.columnNames.includes(columnName)) {\n\t\t\tfieldsInConstraint.push(field.name)\n\t\t}\n\t}\n\tif (fieldsInConstraint.length === constraint.columnNames.length) {\n\t\treturn { entity, fields: fieldsInConstraint }\n\t}\n\treturn null\n}\n\ntype RelationInfo = {\n\towningEntity: Model.Entity\n\towningRelation: Model.Relation\n\ttargetEntity: Model.Entity\n}\n\nconst findForeignConstraint = (\n\tmodel: Model.Schema,\n\tdatabaseMetadata: DatabaseMetadata,\n\ttableName: string,\n\tconstraintName: string,\n): RelationInfo | null => {\n\tconst constraint = databaseMetadata.foreignKeys.filter({ fromTable: tableName, constraintName }).first()\n\tif (!constraint) {\n\t\treturn null\n\t}\n\tconst owningEntity = getEntityByTableName(model, constraint.fromTable)\n\tif (!owningEntity) {\n\t\t// todo m:n\n\t\treturn null\n\t}\n\n\tconst targetEntity = getEntityByTableName(model, constraint.toTable)\n\tif (!targetEntity) {\n\t\treturn null\n\t}\n\tfor (const field of Object.values(owningEntity.fields)) {\n\t\tconst relation = acceptFieldVisitor<(Model.Relation & Model.JoiningColumnRelation) | null>(model, owningEntity, field, {\n\t\t\tvisitColumn: () => null,\n\t\t\tvisitOneHasOneInverse: () => null,\n\t\t\tvisitManyHasManyInverse: () => null,\n\t\t\tvisitManyHasManyOwning: () => null,\n\t\t\tvisitOneHasMany: () => null,\n\t\t\tvisitOneHasOneOwning: ({ relation }) => relation,\n\t\t\tvisitManyHasOne: ({ relation }) => relation,\n\t\t})\n\t\tif (relation && relation.joiningColumn.columnName === constraint.fromColumn) {\n\t\t\treturn {\n\t\t\t\towningEntity,\n\t\t\t\towningRelation: relation,\n\t\t\t\ttargetEntity,\n\t\t\t}\n\t\t}\n\t}\n\treturn null\n}\n\nexport const convertError = (\n\tschema: Model.Schema,\n\tdatabaseMetadata: DatabaseMetadata,\n\te: any,\n): MutationResult => {\n\tif (e instanceof Database.NotNullViolationError) {\n\t\treturn new MutationConstraintViolationError([], ConstraintType.notNull, e.originalMessage, [\n\t\t\tMutationResultHint.sqlError,\n\t\t])\n\t}\n\tif (e instanceof Database.ForeignKeyViolationError) {\n\t\tconst relationInfo = e.constraint && e.table ? findForeignConstraint(schema, databaseMetadata, e.table, e.constraint) : null\n\t\tconst violationDetail: string = 'detail' in e.previous ? e.previous.detail : ''\n\t\tconst matchResult = violationDetail.match(/^Key \\(.+\\)=\\((.+)\\) is still referenced from table/)\n\t\tconst message = relationInfo\n\t\t\t? `Cannot delete ${matchResult ? `row ${matchResult[1]}` : 'unknown row'}`\n\t\t\t\t+ ` of entity ${relationInfo.targetEntity.name},`\n\t\t\t\t+ ` because it is still referenced from ${relationInfo.owningEntity.name}::${relationInfo.owningRelation.name}.`\n\t\t\t\t+ ' This is possibly caused by ACL denial or by missing \"on delete cascade\"'\n\t\t\t: e.originalMessage\n\t\treturn new MutationConstraintViolationError([], ConstraintType.foreignKey, message, [MutationResultHint.sqlError])\n\t}\n\tif (e instanceof Database.UniqueViolationError) {\n\t\tconst constraint = e.constraint && e.table ? findUniqueConstraint(schema, databaseMetadata, e.table, e.constraint) : null\n\t\tconst violationDetail: string = 'detail' in e.previous ? e.previous.detail : ''\n\t\tconst matchResult = violationDetail.match(/^Key \\(.+\\)=\\((.+)\\) already exists\\.$/)\n\t\tconst values = matchResult?.[1]\n\t\tconst message = constraint\n\t\t\t? `${values ? `Value (${values})` : 'Unknown value'}`\n\t\t\t\t+ ` already exists in unique columns (${constraint.fields.join(', ')}) on entity ${constraint.entity.name}`\n\t\t\t: e.originalMessage\n\t\tconst paths = constraint ? constraint.fields.map(it => [{ field: it }]) : []\n\t\treturn new MutationConstraintViolationError(paths, ConstraintType.uniqueKey, message, [MutationResultHint.sqlError])\n\t}\n\tif (e instanceof Database.CheckViolationError) {\n\t\tconst entity = e.table ? getEntityByTableName(schema, e.table) : undefined\n\t\tconst check = entity && e.constraint ? entity.checks?.find(it => it.name === e.constraint) : undefined\n\t\tif (entity && check) {\n\t\t\tconst message = `Check constraint \"${check.name}\" on entity ${entity.name} violated`\n\t\t\treturn new MutationConstraintViolationError([], ConstraintType.check, message, [MutationResultHint.sqlError])\n\t\t}\n\t\t// a DOMAIN check (enum or custom column type) or a check created outside the schema\n\t\tlogger.warn(e, { loc: 'convertError' })\n\t\treturn new MutationConstraintViolationError([], ConstraintType.check, e.originalMessage, [MutationResultHint.sqlError])\n\t}\n\tif (e instanceof UniqueWhereError) {\n\t\treturn new MutationInputError([], InputErrorKind.nonUniqueWhere, e.message)\n\t}\n\tif (e instanceof Database.InvalidDataError) {\n\t\treturn new MutationInputError([], InputErrorKind.invalidData, e.originalMessage, [MutationResultHint.sqlError])\n\t}\n\tif (e instanceof Database.SerializationFailureError) {\n\t\tthrow e\n\t}\n\tif (e instanceof Database.TransactionAbortedError) {\n\t\treturn new MutationSqlError([], e.originalMessage, [MutationResultHint.subSequentSqlError])\n\t}\n\tif (e instanceof Database.CannotCommitError) {\n\t\tlogger.error(e, { loc: 'convertError' })\n\t\treturn new MutationSqlError([], e.originalMessage, [MutationResultHint.sqlError])\n\t}\n\tif (e instanceof Database.QueryError) {\n\t\tlogger.error(e, { loc: 'convertError' })\n\t\tconst message = hasClientFacingMessage(e.code) ? e.originalMessage : 'Database query failed'\n\t\treturn new MutationSqlError([], message, [MutationResultHint.sqlError])\n\t}\n\tthrow e\n}\n\n// Data (22) and integrity (23) errors and project trigger exceptions (P0001) carry messages clients act on. Other\n// messages (e.g. class 42) can quote internal SQL identifiers, which embed ACL predicate names.\nconst hasClientFacingMessage = (code: string | undefined): boolean =>\n\tcode !== undefined && (code.startsWith('22') || code.startsWith('23') || code === 'P0001')\n\nexport const tryMutation = async (\n\tschema: Model.Schema,\n\tdatabaseMetadata: DatabaseMetadata,\n\tcb: () => Promise<MutationResultList>,\n): Promise<MutationResultList> => {\n\ttry {\n\t\treturn await cb()\n\t} catch (e) {\n\t\treturn [convertError(schema, databaseMetadata, e)]\n\t}\n}\n"],"names":["relation"],"mappings":";;;;;;AAsBA,MAAM,uBAAuB,CAAC,OAAqB,cAAsB,OAAO,OAAO,MAAM,QAAQ,EAAE,KAAK,CAAA,OAAM,GAAG,cAAc,SAAS;AAE5I,MAAM,uBAAuB,CAC5B,OACA,kBACA,WACA,mBACmC;AACnC,QAAM,aAAa,iBAAiB,kBAAkB,OAAO,EAAE,WAAW,gBAAgB,EAAE,MAAA;AAC5F,MAAI,CAAC,YAAY;AAChB,WAAO;AAAA,EACR;AACA,QAAM,SAAS,qBAAqB,OAAO,WAAW,SAAS;AAC/D,MAAI,CAAC,QAAQ;AACZ,WAAO;AAAA,EACR;AACA,QAAM,qBAA+B,CAAA;AACrC,aAAW,SAAS,OAAO,OAAO,OAAO,MAAM,GAAG;AACjD,UAAM,aAAa,iBAAiB,OAAO,QAAQ,MAAM,IAAI;AAC7D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AS,WAAc,KAAK,WAAW,IAAI,KAAK,KAAK,WAAW,IAAI,KAAK,SAAS;AAE5E,MAAM,cAAc,OAC1B,QACA,kBACA,OACiC;AACjC,MAAI;AACH,WAAO,MAAM,GAAA;AAAA,EACd,SAAS,GAAG;AACX,WAAO,CAAC,aAAa,QAAQ,kBAAkB,CAAC,CAAC;AAAA,EAClD;AACD;"}
@@ -7,7 +7,7 @@ require("node:crypto");
7
7
  const AclScope = require("../acl/AclScope.cjs");
8
8
  const exception = require("../exception.cjs");
9
9
  const Mutex = require("../utils/Mutex.cjs");
10
- require("fast-deep-equal");
10
+ require("@contember/utilities");
11
11
  require("../acl/PredicatesInjector.cjs");
12
12
  require("./select/Path.cjs");
13
13
  const OrderByHelper = require("./select/OrderByHelper.cjs");
@@ -246,6 +246,42 @@ class Mapper {
246
246
  visitManyHasOne: err
247
247
  });
248
248
  }
249
+ /**
250
+ * Fetches the primary values of entities currently in a has-many relation of the given owner.
251
+ * Used by the declarative `set` operation to compute orphans. Respects ACL read predicates on the target entity.
252
+ */
253
+ async fetchHasManyPrimaries(context, ownerPrimary) {
254
+ if (context.type === "oneHasMany") {
255
+ const { targetEntity: targetEntity2, targetRelation } = context;
256
+ const readPredicate2 = this.predicatesInjector.inject(targetEntity2, {}, "nested");
257
+ const path = this.pathFactory.create([]);
258
+ let qb2 = Database.SelectBuilder.create().from(targetEntity2.tableName, path.alias).select([path.alias, targetEntity2.primaryColumn], "primary_").where((cond) => cond.compare([path.alias, targetRelation.joiningColumn.columnName], Database.Operator.eq, ownerPrimary));
259
+ if (Object.keys(readPredicate2).length > 0) {
260
+ qb2 = this.whereBuilder.build(qb2, targetEntity2, path, readPredicate2);
261
+ }
262
+ const rows2 = await qb2.getResult(this.db);
263
+ return rows2.map((it) => it.primary_);
264
+ }
265
+ const owningContext = context.type === "manyHasManyOwning" ? { entity: context.entity, relation: context.relation, ownerIsJoining: true } : { entity: context.targetEntity, relation: context.targetRelation, ownerIsJoining: false };
266
+ const targetEntity = context.targetEntity;
267
+ const joiningTable = owningContext.relation.joiningTable;
268
+ const ownerColumn = owningContext.ownerIsJoining ? joiningTable.joiningColumn.columnName : joiningTable.inverseJoiningColumn.columnName;
269
+ const targetColumn = owningContext.ownerIsJoining ? joiningTable.inverseJoiningColumn.columnName : joiningTable.joiningColumn.columnName;
270
+ const readPredicate = this.predicatesInjector.inject(targetEntity, {}, "nested");
271
+ const hasReadPredicate = Object.keys(readPredicate).length > 0;
272
+ let qb = Database.SelectBuilder.create().from(joiningTable.tableName, "junction_").select(["junction_", targetColumn], "primary_").where((cond) => cond.compare(["junction_", ownerColumn], Database.Operator.eq, ownerPrimary));
273
+ if (hasReadPredicate) {
274
+ const path = this.pathFactory.create([]);
275
+ qb = qb.join(
276
+ targetEntity.tableName,
277
+ path.alias,
278
+ (clause) => clause.compareColumns(["junction_", targetColumn], Database.Operator.eq, [path.alias, targetEntity.primaryColumn])
279
+ );
280
+ qb = this.whereBuilder.build(qb, targetEntity, path, readPredicate);
281
+ }
282
+ const rows = await qb.getResult(this.db);
283
+ return rows.map((it) => it.primary_);
284
+ }
249
285
  async getPrimaryValue(entity, where, scope) {
250
286
  if (where instanceof CheckedPrimary.CheckedPrimary) {
251
287
  return [where.primaryValue, void 0];
@@ -1 +1 @@
1
- {"version":3,"file":"Mapper.cjs","sources":["../../../../../packages/engine-content-api/src/mapper/Mapper.ts"],"sourcesContent":["import { Input, Model } from '@contember/schema'\nimport { acceptFieldVisitor, getColumnName } from '@contember/schema-utils'\nimport {\n\tOrderByHelper,\n\tPathFactory,\n\tSelectBuilderFactory,\n\tSelectGroupedObjects,\n\tSelectHydrator,\n\tSelectIndexedResultObjects,\n\tSelectResultObject,\n\tWhereBuilder,\n} from './select/index.js'\nimport { Client, Connection, ConstraintHelper, DatabaseMetadata, RequestMemoryBudget, SelectBuilder } from '@contember/database'\nimport { AclScope, aclScopeFromPath, PredicatesInjector, ROW_LOOKUP_SCOPE } from '../acl/index.js'\nimport { JunctionTableManager } from './JunctionTableManager.js'\nimport { DeletedEntitiesStorage, DeleteExecutor } from './delete/index.js'\nimport { MutationEntryNotFoundError, MutationResultList } from './Result.js'\nimport { UpdateBuilder, Updater } from './update/index.js'\nimport { InsertBuilder, Inserter } from './insert/index.js'\nimport { tryMutation } from './ErrorUtils.js'\nimport { ObjectNode, UniqueWhereExpander } from '../inputProcessing/index.js'\nimport { Mutex } from '../utils/index.js'\nimport { CheckedPrimary } from './CheckedPrimary.js'\nimport { ImplementationException } from '../exception.js'\nimport { EventManager } from './EventManager.js'\nimport { MapperInput } from './types.js'\n\nexport class Mapper<ConnectionType extends Connection.ConnectionLike = Connection.ConnectionLike> {\n\tprivate systemVariablesSetupDone: Promise<void> | undefined\n\tpublic readonly deletedEntities = new DeletedEntitiesStorage()\n\tpublic readonly mutex = new Mutex()\n\tpublic readonly constraintHelper: ConstraintHelper\n\t/** Charges the request memory budget; only selection results use it, internal mutation queries stay on `db`. */\n\tpublic readonly selectionDb: Client<ConnectionType>\n\n\tpublic readonly eventManager: EventManager\n\n\tconstructor(\n\t\tpublic readonly db: Client<ConnectionType>,\n\t\tpublic readonly identityId: string,\n\t\tpublic readonly transactionId: string,\n\t\tprivate readonly schema: Model.Schema,\n\t\tprivate readonly schemaDatabaseMetadata: DatabaseMetadata,\n\t\tprivate readonly predicatesInjector: PredicatesInjector,\n\t\tprivate readonly selectBuilderFactory: SelectBuilderFactory,\n\t\tprivate readonly uniqueWhereExpander: UniqueWhereExpander,\n\t\tprivate readonly whereBuilder: WhereBuilder,\n\t\tprivate readonly junctionTableManager: JunctionTableManager,\n\t\tprivate readonly deleteExecutor: DeleteExecutor,\n\t\tprivate readonly updater: Updater,\n\t\tprivate readonly inserter: Inserter,\n\t\tprivate readonly pathFactory: PathFactory,\n\t\tprivate readonly memoryBudget?: RequestMemoryBudget,\n\t) {\n\t\tthis.constraintHelper = new ConstraintHelper(db, this.schemaDatabaseMetadata)\n\t\tthis.selectionDb = memoryBudget ? db.withMemoryBudget(memoryBudget, { chargeRows: true }) : db\n\t\tthis.eventManager = new EventManager(this)\n\t}\n\n\tpublic async selectField(entity: Model.Entity, where: Input.UniqueWhere | CheckedPrimary, fieldName: string, scope: AclScope) {\n\t\tconst columnName = getColumnName(this.schema, entity, fieldName)\n\n\t\tconst qb = SelectBuilder.create() //\n\t\t\t.from(entity.tableName, 'root_')\n\t\t\t.select(['root_', columnName])\n\t\tconst expandedWhere = this.uniqueWhereExpander.expand(entity, where)\n\t\tconst withPredicates = this.predicatesInjector.inject(entity, expandedWhere, scope)\n\t\tconst builtQb = this.whereBuilder.build(qb, entity, this.pathFactory.create([]), withPredicates)\n\t\tconst result = await builtQb.getResult(this.db)\n\n\t\treturn result[0] !== undefined ? result[0][columnName] : undefined\n\t}\n\n\tpublic async selectAssoc(\n\t\tentity: Model.Entity,\n\t\tinput: ObjectNode<Input.ListQueryInput>,\n\t\trelationPath: Model.AnyRelationContext[],\n\t\tindexBy: string,\n\t): Promise<SelectIndexedResultObjects> {\n\t\tconst hydrator = new SelectHydrator(this.memoryBudget)\n\t\tconst path = this.pathFactory.create([])\n\t\tconst indexByAlias: string = path.forInternal('index').for(indexBy).alias\n\t\tconst qb: SelectBuilder = SelectBuilder.create()\n\t\t\t.select([path.alias, getColumnName(this.schema, entity, indexBy)], indexByAlias)\n\t\tconst rows = await this.selectRows(hydrator, qb, entity, input, relationPath)\n\t\treturn await hydrator.hydrateAll(rows, indexByAlias)\n\t}\n\n\tpublic async select(\n\t\tentity: Model.Entity,\n\t\tinput: ObjectNode<Input.ListQueryInput>,\n\t\trelationPath: Model.AnyRelationContext[],\n\t): Promise<SelectResultObject[]> {\n\t\tconst hydrator = new SelectHydrator(this.memoryBudget)\n\t\tconst qb: SelectBuilder<SelectBuilder.Result> = SelectBuilder.create()\n\n\t\tconst rows = await this.selectRows(hydrator, qb, entity, input, relationPath)\n\n\t\treturn await hydrator.hydrateAll(rows)\n\t}\n\n\tpublic async selectUnique(\n\t\tentity: Model.Entity,\n\t\tquery: ObjectNode<Input.UniqueQueryInput>,\n\t\trelationPath: Model.AnyRelationContext[],\n\t): Promise<SelectResultObject | null> {\n\t\tconst uniqueWhere = this.uniqueWhereExpander.expand(entity, query.args.by)\n\t\tconst where = query.args.filter ? { and: [uniqueWhere, query.args.filter] } : uniqueWhere\n\t\tconst queryExpanded = query.withArg<Input.ListQueryInput>('filter', where)\n\n\t\tconst rows = await this.select(entity, queryExpanded, relationPath)\n\n\t\treturn rows[0] ?? null\n\t}\n\n\tpublic async selectGrouped(\n\t\tentity: Model.Entity,\n\t\tinput: ObjectNode<Input.ListQueryInput>,\n\t\trelation: Model.JoiningColumnRelation & Model.AnyRelation,\n\t\trelationPath: Model.AnyRelationContext[],\n\t): Promise<SelectGroupedObjects> {\n\t\tconst hydrator = new SelectHydrator(this.memoryBudget)\n\t\tconst path = this.pathFactory.create([])\n\t\tconst groupingKey = '__grouping_key'\n\t\tconst qb: SelectBuilder = SelectBuilder.create()\n\t\t\t.select([path.alias, relation.joiningColumn.columnName], groupingKey)\n\n\t\tconst rows = await this.selectRows(hydrator, qb, entity, input, relationPath, relation.name)\n\n\t\treturn await hydrator.hydrateGroups(rows, groupingKey)\n\t}\n\n\tprivate async selectRows(\n\t\thydrator: SelectHydrator,\n\t\tqb: SelectBuilder<SelectBuilder.Result>,\n\t\tentity: Model.Entity,\n\t\tinput: ObjectNode<Input.ListQueryInput>,\n\t\trelationPath: Model.AnyRelationContext[],\n\t\tgroupBy?: string,\n\t) {\n\t\tconst inputWithOrder = OrderByHelper.appendDefaultOrderBy(entity, input, undefined)\n\t\tconst path = this.pathFactory.create([])\n\t\tconst augmentedBuilder = qb.from(entity.tableName, path.alias).meta('path', [...input.path, input.alias])\n\n\t\tconst selector = this.selectBuilderFactory.create(augmentedBuilder, hydrator, relationPath)\n\t\tconst filterWithPredicates = this.predicatesInjector.inject(\n\t\t\tentity,\n\t\t\tinputWithOrder.args.filter || {},\n\t\t\taclScopeFromPath(relationPath),\n\t\t\trelationPath[relationPath.length - 1],\n\t\t\trelationPath,\n\t\t)\n\t\tconst inputWithPredicates = inputWithOrder.withArg('filter', filterWithPredicates)\n\t\tselector.select(this, entity, inputWithPredicates, path, groupBy)\n\t\treturn await selector.execute(this.selectionDb)\n\t}\n\n\tpublic async count(entity: Model.Entity, filter: Input.OptionalWhere, scope: AclScope) {\n\t\tconst path = this.pathFactory.create([])\n\t\tconst qb = SelectBuilder.create()\n\t\t\t.from(entity.tableName, path.alias)\n\t\t\t.select(expr => expr.raw('count(*)'), 'row_count')\n\t\tconst withPredicates = this.predicatesInjector.inject(entity, filter, scope)\n\t\tconst qbWithWhere = this.whereBuilder.build(qb, entity, path, withPredicates)\n\t\tconst result = await qbWithWhere.getResult(this.db)\n\t\treturn result[0].row_count\n\t}\n\n\tpublic async countGrouped(\n\t\tentity: Model.Entity,\n\t\tfilter: Input.OptionalWhere,\n\t\trelation: Model.JoiningColumnRelation & Model.Relation,\n\t\trelationPath: Model.AnyRelationContext[],\n\t): Promise<Record<string, number>> {\n\t\tconst path = this.pathFactory.create([])\n\t\tconst qb = SelectBuilder.create()\n\t\t\t.from(entity.tableName, path.alias)\n\t\t\t.select(expr => expr.raw('count(*)'), 'row_count')\n\t\t\t.select([path.alias, relation.joiningColumn.columnName])\n\t\t\t.groupBy([path.alias, relation.joiningColumn.columnName])\n\t\tconst withPredicates = this.predicatesInjector.inject(\n\t\t\tentity,\n\t\t\tfilter,\n\t\t\taclScopeFromPath(relationPath),\n\t\t\trelationPath[relationPath.length - 1],\n\t\t\trelationPath,\n\t\t)\n\t\tconst qbWithWhere = this.whereBuilder.build(qb, entity, path, withPredicates, { relationPath })\n\t\tconst rows = await qbWithWhere.getResult(this.db)\n\t\tconst result = new Map<string, number>()\n\t\tfor (const row of rows) {\n\t\t\tresult.set(String(row[relation.joiningColumn.columnName]), Number(row.row_count))\n\t\t}\n\t\treturn Object.fromEntries(result)\n\t}\n\n\tpublic async insert(\n\t\tentity: Model.Entity,\n\t\tdata: MapperInput.CreateDataInput,\n\t\tscope: AclScope,\n\t\tbuilderCb: (builder: InsertBuilder) => void = () => {},\n\t): Promise<MutationResultList> {\n\t\tif (entity.view) {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\tawait this.setupSystemVariables()\n\t\treturn tryMutation(this.schema, this.schemaDatabaseMetadata, () => this.insertInternal(entity, data, scope, builderCb))\n\t}\n\n\tpublic async update(\n\t\tentity: Model.Entity,\n\t\tby: Input.UniqueWhere | CheckedPrimary,\n\t\tdata: MapperInput.UpdateDataInput,\n\t\tscope: AclScope,\n\t\tfilter?: Input.OptionalWhere,\n\t): Promise<MutationResultList> {\n\t\tif (entity.view) {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\tawait this.setupSystemVariables()\n\t\treturn tryMutation(this.schema, this.schemaDatabaseMetadata, async () => {\n\t\t\tconst [primaryValue, err] = await this.getPrimaryValue(entity, by, ROW_LOOKUP_SCOPE)\n\t\t\tif (err) return [err]\n\n\t\t\treturn await this.updater.update(this, entity, primaryValue, data, scope, filter)\n\t\t})\n\t}\n\n\tpublic async updateInternal(\n\t\tentity: Model.Entity,\n\t\tby: Input.UniqueWhere | CheckedPrimary,\n\t\tbuilderCb: (builder: UpdateBuilder) => void,\n\t\tscope: AclScope,\n\t): Promise<MutationResultList> {\n\t\tif (entity.view) {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\tawait this.setupSystemVariables()\n\t\treturn tryMutation(this.schema, this.schemaDatabaseMetadata, async () => {\n\t\t\tconst [primaryValue, err] = await this.getPrimaryValue(entity, by, ROW_LOOKUP_SCOPE)\n\t\t\tif (err) return [err]\n\n\t\t\treturn await this.updater.updateCb(this, entity, primaryValue, builderCb, scope)\n\t\t})\n\t}\n\tpublic async upsert(\n\t\tentity: Model.Entity,\n\t\tby: Input.UniqueWhere | CheckedPrimary,\n\t\tupdate: MapperInput.UpdateDataInput,\n\t\tcreate: MapperInput.CreateDataInput,\n\t\tscope: AclScope,\n\t\tfilter?: Input.OptionalWhere,\n\t): Promise<MutationResultList> {\n\t\tif (entity.view) {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\tawait this.setupSystemVariables()\n\t\treturn tryMutation(this.schema, this.schemaDatabaseMetadata, async () => {\n\t\t\tconst [primaryValue] = await this.getPrimaryValue(entity, by, ROW_LOOKUP_SCOPE)\n\t\t\tif (primaryValue === undefined) {\n\t\t\t\treturn await this.insertInternal(entity, create, scope)\n\t\t\t}\n\t\t\treturn await this.updater.update(this, entity, primaryValue, update, scope, filter)\n\t\t})\n\t}\n\n\tprivate insertInternal(\n\t\tentity: Model.Entity,\n\t\tdata: MapperInput.CreateDataInput,\n\t\tscope: AclScope,\n\t\tbuilderCb: (builder: InsertBuilder) => void = () => {},\n\t) {\n\t\treturn this.inserter.insert(\n\t\t\tthis,\n\t\t\tentity,\n\t\t\tdata,\n\t\t\tid => {\n\t\t\t},\n\t\t\tbuilderCb,\n\t\t\tscope,\n\t\t)\n\t}\n\n\tpublic async delete(\n\t\tentity: Model.Entity,\n\t\tby: Input.UniqueWhere | CheckedPrimary,\n\t\tscope: AclScope,\n\t\tfilter?: Input.OptionalWhere,\n\t): Promise<MutationResultList> {\n\t\tif (entity.view) {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\tawait this.setupSystemVariables()\n\t\treturn tryMutation(this.schema, this.schemaDatabaseMetadata, () => {\n\t\t\treturn this.deleteExecutor.execute(this, entity, by, scope, filter)\n\t\t})\n\t}\n\n\t/**\n\t * `scope` belongs to `entity` - the side the caller named. The other side of the junction is\n\t * reached over the relation, so it always resolves as nested.\n\t */\n\tpublic async connectJunction(\n\t\tentity: Model.Entity,\n\t\trelation: Model.ManyHasManyOwningRelation | Model.ManyHasManyInverseRelation,\n\t\tthisPrimary: Input.PrimaryValue,\n\t\totherPrimary: Input.PrimaryValue,\n\t\tscope: AclScope,\n\t): Promise<MutationResultList> {\n\t\tawait this.setupSystemVariables()\n\t\tconst err = () => {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\treturn await acceptFieldVisitor(this.schema, entity, relation, {\n\t\t\tvisitManyHasManyOwning: ({ entity, relation }) => {\n\t\t\t\treturn this.junctionTableManager.connectJunction(this, entity, relation, thisPrimary, otherPrimary, {\n\t\t\t\t\towning: scope,\n\t\t\t\t\tinverse: 'nested',\n\t\t\t\t})\n\t\t\t},\n\t\t\tvisitManyHasManyInverse: ({ targetEntity, targetRelation }) => {\n\t\t\t\treturn this.junctionTableManager.connectJunction(this, targetEntity, targetRelation, otherPrimary, thisPrimary, {\n\t\t\t\t\towning: 'nested',\n\t\t\t\t\tinverse: scope,\n\t\t\t\t})\n\t\t\t},\n\t\t\tvisitColumn: err,\n\t\t\tvisitOneHasMany: err,\n\t\t\tvisitOneHasOneInverse: err,\n\t\t\tvisitOneHasOneOwning: err,\n\t\t\tvisitManyHasOne: err,\n\t\t})\n\t}\n\n\t/** See {@link connectJunction} for how `scope` maps onto the two sides. */\n\tpublic async disconnectJunction(\n\t\tentity: Model.Entity,\n\t\trelation: Model.ManyHasManyOwningRelation | Model.ManyHasManyInverseRelation,\n\t\tthisPrimary: Input.PrimaryValue,\n\t\totherPrimary: Input.PrimaryValue,\n\t\tscope: AclScope,\n\t): Promise<MutationResultList> {\n\t\tawait this.setupSystemVariables()\n\t\tconst err = () => {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\treturn await acceptFieldVisitor(this.schema, entity, relation, {\n\t\t\tvisitManyHasManyOwning: ({ entity, relation }) => {\n\t\t\t\treturn this.junctionTableManager.disconnectJunction(this, entity, relation, thisPrimary, otherPrimary, {\n\t\t\t\t\towning: scope,\n\t\t\t\t\tinverse: 'nested',\n\t\t\t\t})\n\t\t\t},\n\t\t\tvisitManyHasManyInverse: ({ targetEntity, targetRelation }) => {\n\t\t\t\treturn this.junctionTableManager.disconnectJunction(this, targetEntity, targetRelation, otherPrimary, thisPrimary, {\n\t\t\t\t\towning: 'nested',\n\t\t\t\t\tinverse: scope,\n\t\t\t\t})\n\t\t\t},\n\t\t\tvisitColumn: err,\n\t\t\tvisitOneHasMany: err,\n\t\t\tvisitOneHasOneInverse: err,\n\t\t\tvisitOneHasOneOwning: err,\n\t\t\tvisitManyHasOne: err,\n\t\t})\n\t}\n\n\tpublic async getPrimaryValue(\n\t\tentity: Model.Entity,\n\t\twhere: Input.UniqueWhere | CheckedPrimary,\n\t\tscope: AclScope,\n\t): Promise<[Input.PrimaryValue, undefined] | [undefined, MutationEntryNotFoundError]> {\n\t\tif (where instanceof CheckedPrimary) {\n\t\t\treturn [where.primaryValue, undefined]\n\t\t}\n\t\tconst result = await this.selectField(entity, where, entity.primary, scope)\n\t\treturn result ? [result, undefined] : [undefined, new MutationEntryNotFoundError([], where)]\n\t}\n\n\tprivate async setupSystemVariables() {\n\t\tthis.systemVariablesSetupDone ??= (async () => {\n\t\t\tawait this.db.query('SELECT set_config(?, ?, false)', ['tenant.identity_id', this.identityId]) // todo rename to system.identity_id\n\t\t\tawait this.db.query('SELECT set_config(?, ?, false)', ['system.transaction_id', this.transactionId])\n\t\t})()\n\t\tawait this.systemVariablesSetupDone\n\t}\n}\n"],"names":["DeletedEntitiesStorage","Mutex","ConstraintHelper","EventManager","getColumnName","SelectBuilder","SelectHydrator","OrderByHelper","aclScopeFromPath","ImplementationException","tryMutation","ROW_LOOKUP_SCOPE","acceptFieldVisitor","entity","relation","CheckedPrimary","MutationEntryNotFoundError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA2BO,MAAM,OAAqF;AAAA,EAUjG,YACiB,IACA,YACA,eACC,QACA,wBACA,oBACA,sBACA,qBACA,cACA,sBACA,gBACA,SACA,UACA,aACA,cAChB;AAfe,SAAA,KAAA;AACA,SAAA,aAAA;AACA,SAAA,gBAAA;AACC,SAAA,SAAA;AACA,SAAA,yBAAA;AACA,SAAA,qBAAA;AACA,SAAA,uBAAA;AACA,SAAA,sBAAA;AACA,SAAA,eAAA;AACA,SAAA,uBAAA;AACA,SAAA,iBAAA;AACA,SAAA,UAAA;AACA,SAAA,WAAA;AACA,SAAA,c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AC,SAAQ,UAAAC,gBAAe;AACjD,eAAO,KAAK,qBAAqB,mBAAmB,MAAMD,SAAQC,WAAU,aAAa,cAAc;AAAA,UACtG,QAAQ;AAAA,UACR,SAAS;AAAA,QAAA,CACT;AAAA,MACF;AAAA,MACA,yBAAyB,CAAC,EAAE,cAAc,qBAAqB;AAC9D,eAAO,KAAK,qBAAqB,mBAAmB,MAAM,cAAc,gBAAgB,cAAc,aAAa;AAAA,UAClH,QAAQ;AAAA,UACR,SAAS;AAAA,QAAA,CACT;AAAA,MACF;AAAA,MACA,aAAa;AAAA,MACb,iBAAiB;AAAA,MACjB,uBAAuB;AAAA,MACvB,sBAAsB;AAAA,MACtB,iBAAiB;AAAA,IAAA,CACjB;AAAA,EACF;AAAA,EAEA,MAAa,gBACZ,QACA,OACA,OACqF;AACrF,QAAI,iBAAiBC,eAAAA,gBAAgB;AACpC,aAAO,CAAC,MAAM,cAAc,MAAS;AAAA,IACtC;AACA,UAAM,SAAS,MAAM,KAAK,YAAY,QAAQ,OAAO,OAAO,SAAS,KAAK;AAC1E,WAAO,SAAS,CAAC,QAAQ,MAAS,IAAI,CAAC,QAAW,IAAIC,OAAAA,2BAA2B,IAAI,KAAK,CAAC;AAAA,EAC5F;AAAA,EAEA,MAAc,uBAAuB;AACpC,SAAK,6BAAL,KAAK,4BAA8B,YAAY;AAC9C,YAAM,KAAK,GAAG,MAAM,kCAAkC,CAAC,sBAAsB,KAAK,UAAU,CAAC;AAC7F,YAAM,KAAK,GAAG,MAAM,kCAAkC,CAAC,yBAAyB,KAAK,aAAa,CAAC;AAAA,IACpG;AACA,UAAM,KAAK;AAAA,EACZ;AACD;;"}
1
+ {"version":3,"file":"Mapper.cjs","sources":["../../../../../packages/engine-content-api/src/mapper/Mapper.ts"],"sourcesContent":["import { Input, Model } from '@contember/schema'\nimport { acceptFieldVisitor, getColumnName } from '@contember/schema-utils'\nimport {\n\tOrderByHelper,\n\tPathFactory,\n\tSelectBuilderFactory,\n\tSelectGroupedObjects,\n\tSelectHydrator,\n\tSelectIndexedResultObjects,\n\tSelectResultObject,\n\tWhereBuilder,\n} from './select/index.js'\nimport { Client, Connection, ConstraintHelper, DatabaseMetadata, Operator, RequestMemoryBudget, SelectBuilder } from '@contember/database'\nimport { AclScope, aclScopeFromPath, PredicatesInjector, ROW_LOOKUP_SCOPE } from '../acl/index.js'\nimport { JunctionTableManager } from './JunctionTableManager.js'\nimport { DeletedEntitiesStorage, DeleteExecutor } from './delete/index.js'\nimport { MutationEntryNotFoundError, MutationResultList } from './Result.js'\nimport { UpdateBuilder, Updater } from './update/index.js'\nimport { InsertBuilder, Inserter } from './insert/index.js'\nimport { tryMutation } from './ErrorUtils.js'\nimport { ObjectNode, UniqueWhereExpander } from '../inputProcessing/index.js'\nimport { Mutex } from '../utils/index.js'\nimport { CheckedPrimary } from './CheckedPrimary.js'\nimport { ImplementationException } from '../exception.js'\nimport { EventManager } from './EventManager.js'\nimport { MapperInput } from './types.js'\n\nexport class Mapper<ConnectionType extends Connection.ConnectionLike = Connection.ConnectionLike> {\n\tprivate systemVariablesSetupDone: Promise<void> | undefined\n\tpublic readonly deletedEntities = new DeletedEntitiesStorage()\n\tpublic readonly mutex = new Mutex()\n\tpublic readonly constraintHelper: ConstraintHelper\n\t/** Charges the request memory budget; only selection results use it, internal mutation queries stay on `db`. */\n\tpublic readonly selectionDb: Client<ConnectionType>\n\n\tpublic readonly eventManager: EventManager\n\n\tconstructor(\n\t\tpublic readonly db: Client<ConnectionType>,\n\t\tpublic readonly identityId: string,\n\t\tpublic readonly transactionId: string,\n\t\tprivate readonly schema: Model.Schema,\n\t\tprivate readonly schemaDatabaseMetadata: DatabaseMetadata,\n\t\tprivate readonly predicatesInjector: PredicatesInjector,\n\t\tprivate readonly selectBuilderFactory: SelectBuilderFactory,\n\t\tprivate readonly uniqueWhereExpander: UniqueWhereExpander,\n\t\tprivate readonly whereBuilder: WhereBuilder,\n\t\tprivate readonly junctionTableManager: JunctionTableManager,\n\t\tprivate readonly deleteExecutor: DeleteExecutor,\n\t\tprivate readonly updater: Updater,\n\t\tprivate readonly inserter: Inserter,\n\t\tprivate readonly pathFactory: PathFactory,\n\t\tprivate readonly memoryBudget?: RequestMemoryBudget,\n\t) {\n\t\tthis.constraintHelper = new ConstraintHelper(db, this.schemaDatabaseMetadata)\n\t\tthis.selectionDb = memoryBudget ? db.withMemoryBudget(memoryBudget, { chargeRows: true }) : db\n\t\tthis.eventManager = new EventManager(this)\n\t}\n\n\tpublic async selectField(entity: Model.Entity, where: Input.UniqueWhere | CheckedPrimary, fieldName: string, scope: AclScope) {\n\t\tconst columnName = getColumnName(this.schema, entity, fieldName)\n\n\t\tconst qb = SelectBuilder.create() //\n\t\t\t.from(entity.tableName, 'root_')\n\t\t\t.select(['root_', columnName])\n\t\tconst expandedWhere = this.uniqueWhereExpander.expand(entity, where)\n\t\tconst withPredicates = this.predicatesInjector.inject(entity, expandedWhere, scope)\n\t\tconst builtQb = this.whereBuilder.build(qb, entity, this.pathFactory.create([]), withPredicates)\n\t\tconst result = await builtQb.getResult(this.db)\n\n\t\treturn result[0] !== undefined ? result[0][columnName] : undefined\n\t}\n\n\tpublic async selectAssoc(\n\t\tentity: Model.Entity,\n\t\tinput: ObjectNode<Input.ListQueryInput>,\n\t\trelationPath: Model.AnyRelationContext[],\n\t\tindexBy: string,\n\t): Promise<SelectIndexedResultObjects> {\n\t\tconst hydrator = new SelectHydrator(this.memoryBudget)\n\t\tconst path = this.pathFactory.create([])\n\t\tconst indexByAlias: string = path.forInternal('index').for(indexBy).alias\n\t\tconst qb: SelectBuilder = SelectBuilder.create()\n\t\t\t.select([path.alias, getColumnName(this.schema, entity, indexBy)], indexByAlias)\n\t\tconst rows = await this.selectRows(hydrator, qb, entity, input, relationPath)\n\t\treturn await hydrator.hydrateAll(rows, indexByAlias)\n\t}\n\n\tpublic async select(\n\t\tentity: Model.Entity,\n\t\tinput: ObjectNode<Input.ListQueryInput>,\n\t\trelationPath: Model.AnyRelationContext[],\n\t): Promise<SelectResultObject[]> {\n\t\tconst hydrator = new SelectHydrator(this.memoryBudget)\n\t\tconst qb: SelectBuilder<SelectBuilder.Result> = SelectBuilder.create()\n\n\t\tconst rows = await this.selectRows(hydrator, qb, entity, input, relationPath)\n\n\t\treturn await hydrator.hydrateAll(rows)\n\t}\n\n\tpublic async selectUnique(\n\t\tentity: Model.Entity,\n\t\tquery: ObjectNode<Input.UniqueQueryInput>,\n\t\trelationPath: Model.AnyRelationContext[],\n\t): Promise<SelectResultObject | null> {\n\t\tconst uniqueWhere = this.uniqueWhereExpander.expand(entity, query.args.by)\n\t\tconst where = query.args.filter ? { and: [uniqueWhere, query.args.filter] } : uniqueWhere\n\t\tconst queryExpanded = query.withArg<Input.ListQueryInput>('filter', where)\n\n\t\tconst rows = await this.select(entity, queryExpanded, relationPath)\n\n\t\treturn rows[0] ?? null\n\t}\n\n\tpublic async selectGrouped(\n\t\tentity: Model.Entity,\n\t\tinput: ObjectNode<Input.ListQueryInput>,\n\t\trelation: Model.JoiningColumnRelation & Model.AnyRelation,\n\t\trelationPath: Model.AnyRelationContext[],\n\t): Promise<SelectGroupedObjects> {\n\t\tconst hydrator = new SelectHydrator(this.memoryBudget)\n\t\tconst path = this.pathFactory.create([])\n\t\tconst groupingKey = '__grouping_key'\n\t\tconst qb: SelectBuilder = SelectBuilder.create()\n\t\t\t.select([path.alias, relation.joiningColumn.columnName], groupingKey)\n\n\t\tconst rows = await this.selectRows(hydrator, qb, entity, input, relationPath, relation.name)\n\n\t\treturn await hydrator.hydrateGroups(rows, groupingKey)\n\t}\n\n\tprivate async selectRows(\n\t\thydrator: SelectHydrator,\n\t\tqb: SelectBuilder<SelectBuilder.Result>,\n\t\tentity: Model.Entity,\n\t\tinput: ObjectNode<Input.ListQueryInput>,\n\t\trelationPath: Model.AnyRelationContext[],\n\t\tgroupBy?: string,\n\t) {\n\t\tconst inputWithOrder = OrderByHelper.appendDefaultOrderBy(entity, input, undefined)\n\t\tconst path = this.pathFactory.create([])\n\t\tconst augmentedBuilder = qb.from(entity.tableName, path.alias).meta('path', [...input.path, input.alias])\n\n\t\tconst selector = this.selectBuilderFactory.create(augmentedBuilder, hydrator, relationPath)\n\t\tconst filterWithPredicates = this.predicatesInjector.inject(\n\t\t\tentity,\n\t\t\tinputWithOrder.args.filter || {},\n\t\t\taclScopeFromPath(relationPath),\n\t\t\trelationPath[relationPath.length - 1],\n\t\t\trelationPath,\n\t\t)\n\t\tconst inputWithPredicates = inputWithOrder.withArg('filter', filterWithPredicates)\n\t\tselector.select(this, entity, inputWithPredicates, path, groupBy)\n\t\treturn await selector.execute(this.selectionDb)\n\t}\n\n\tpublic async count(entity: Model.Entity, filter: Input.OptionalWhere, scope: AclScope) {\n\t\tconst path = this.pathFactory.create([])\n\t\tconst qb = SelectBuilder.create()\n\t\t\t.from(entity.tableName, path.alias)\n\t\t\t.select(expr => expr.raw('count(*)'), 'row_count')\n\t\tconst withPredicates = this.predicatesInjector.inject(entity, filter, scope)\n\t\tconst qbWithWhere = this.whereBuilder.build(qb, entity, path, withPredicates)\n\t\tconst result = await qbWithWhere.getResult(this.db)\n\t\treturn result[0].row_count\n\t}\n\n\tpublic async countGrouped(\n\t\tentity: Model.Entity,\n\t\tfilter: Input.OptionalWhere,\n\t\trelation: Model.JoiningColumnRelation & Model.Relation,\n\t\trelationPath: Model.AnyRelationContext[],\n\t): Promise<Record<string, number>> {\n\t\tconst path = this.pathFactory.create([])\n\t\tconst qb = SelectBuilder.create()\n\t\t\t.from(entity.tableName, path.alias)\n\t\t\t.select(expr => expr.raw('count(*)'), 'row_count')\n\t\t\t.select([path.alias, relation.joiningColumn.columnName])\n\t\t\t.groupBy([path.alias, relation.joiningColumn.columnName])\n\t\tconst withPredicates = this.predicatesInjector.inject(\n\t\t\tentity,\n\t\t\tfilter,\n\t\t\taclScopeFromPath(relationPath),\n\t\t\trelationPath[relationPath.length - 1],\n\t\t\trelationPath,\n\t\t)\n\t\tconst qbWithWhere = this.whereBuilder.build(qb, entity, path, withPredicates, { relationPath })\n\t\tconst rows = await qbWithWhere.getResult(this.db)\n\t\tconst result = new Map<string, number>()\n\t\tfor (const row of rows) {\n\t\t\tresult.set(String(row[relation.joiningColumn.columnName]), Number(row.row_count))\n\t\t}\n\t\treturn Object.fromEntries(result)\n\t}\n\n\tpublic async insert(\n\t\tentity: Model.Entity,\n\t\tdata: MapperInput.CreateDataInput,\n\t\tscope: AclScope,\n\t\tbuilderCb: (builder: InsertBuilder) => void = () => {},\n\t): Promise<MutationResultList> {\n\t\tif (entity.view) {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\tawait this.setupSystemVariables()\n\t\treturn tryMutation(this.schema, this.schemaDatabaseMetadata, () => this.insertInternal(entity, data, scope, builderCb))\n\t}\n\n\tpublic async update(\n\t\tentity: Model.Entity,\n\t\tby: Input.UniqueWhere | CheckedPrimary,\n\t\tdata: MapperInput.UpdateDataInput,\n\t\tscope: AclScope,\n\t\tfilter?: Input.OptionalWhere,\n\t): Promise<MutationResultList> {\n\t\tif (entity.view) {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\tawait this.setupSystemVariables()\n\t\treturn tryMutation(this.schema, this.schemaDatabaseMetadata, async () => {\n\t\t\tconst [primaryValue, err] = await this.getPrimaryValue(entity, by, ROW_LOOKUP_SCOPE)\n\t\t\tif (err) return [err]\n\n\t\t\treturn await this.updater.update(this, entity, primaryValue, data, scope, filter)\n\t\t})\n\t}\n\n\tpublic async updateInternal(\n\t\tentity: Model.Entity,\n\t\tby: Input.UniqueWhere | CheckedPrimary,\n\t\tbuilderCb: (builder: UpdateBuilder) => void,\n\t\tscope: AclScope,\n\t): Promise<MutationResultList> {\n\t\tif (entity.view) {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\tawait this.setupSystemVariables()\n\t\treturn tryMutation(this.schema, this.schemaDatabaseMetadata, async () => {\n\t\t\tconst [primaryValue, err] = await this.getPrimaryValue(entity, by, ROW_LOOKUP_SCOPE)\n\t\t\tif (err) return [err]\n\n\t\t\treturn await this.updater.updateCb(this, entity, primaryValue, builderCb, scope)\n\t\t})\n\t}\n\tpublic async upsert(\n\t\tentity: Model.Entity,\n\t\tby: Input.UniqueWhere | CheckedPrimary,\n\t\tupdate: MapperInput.UpdateDataInput,\n\t\tcreate: MapperInput.CreateDataInput,\n\t\tscope: AclScope,\n\t\tfilter?: Input.OptionalWhere,\n\t): Promise<MutationResultList> {\n\t\tif (entity.view) {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\tawait this.setupSystemVariables()\n\t\treturn tryMutation(this.schema, this.schemaDatabaseMetadata, async () => {\n\t\t\tconst [primaryValue] = await this.getPrimaryValue(entity, by, ROW_LOOKUP_SCOPE)\n\t\t\tif (primaryValue === undefined) {\n\t\t\t\treturn await this.insertInternal(entity, create, scope)\n\t\t\t}\n\t\t\treturn await this.updater.update(this, entity, primaryValue, update, scope, filter)\n\t\t})\n\t}\n\n\tprivate insertInternal(\n\t\tentity: Model.Entity,\n\t\tdata: MapperInput.CreateDataInput,\n\t\tscope: AclScope,\n\t\tbuilderCb: (builder: InsertBuilder) => void = () => {},\n\t) {\n\t\treturn this.inserter.insert(\n\t\t\tthis,\n\t\t\tentity,\n\t\t\tdata,\n\t\t\tid => {\n\t\t\t},\n\t\t\tbuilderCb,\n\t\t\tscope,\n\t\t)\n\t}\n\n\tpublic async delete(\n\t\tentity: Model.Entity,\n\t\tby: Input.UniqueWhere | CheckedPrimary,\n\t\tscope: AclScope,\n\t\tfilter?: Input.OptionalWhere,\n\t): Promise<MutationResultList> {\n\t\tif (entity.view) {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\tawait this.setupSystemVariables()\n\t\treturn tryMutation(this.schema, this.schemaDatabaseMetadata, () => {\n\t\t\treturn this.deleteExecutor.execute(this, entity, by, scope, filter)\n\t\t})\n\t}\n\n\t/**\n\t * `scope` belongs to `entity` - the side the caller named. The other side of the junction is\n\t * reached over the relation, so it always resolves as nested.\n\t */\n\tpublic async connectJunction(\n\t\tentity: Model.Entity,\n\t\trelation: Model.ManyHasManyOwningRelation | Model.ManyHasManyInverseRelation,\n\t\tthisPrimary: Input.PrimaryValue,\n\t\totherPrimary: Input.PrimaryValue,\n\t\tscope: AclScope,\n\t): Promise<MutationResultList> {\n\t\tawait this.setupSystemVariables()\n\t\tconst err = () => {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\treturn await acceptFieldVisitor(this.schema, entity, relation, {\n\t\t\tvisitManyHasManyOwning: ({ entity, relation }) => {\n\t\t\t\treturn this.junctionTableManager.connectJunction(this, entity, relation, thisPrimary, otherPrimary, {\n\t\t\t\t\towning: scope,\n\t\t\t\t\tinverse: 'nested',\n\t\t\t\t})\n\t\t\t},\n\t\t\tvisitManyHasManyInverse: ({ targetEntity, targetRelation }) => {\n\t\t\t\treturn this.junctionTableManager.connectJunction(this, targetEntity, targetRelation, otherPrimary, thisPrimary, {\n\t\t\t\t\towning: 'nested',\n\t\t\t\t\tinverse: scope,\n\t\t\t\t})\n\t\t\t},\n\t\t\tvisitColumn: err,\n\t\t\tvisitOneHasMany: err,\n\t\t\tvisitOneHasOneInverse: err,\n\t\t\tvisitOneHasOneOwning: err,\n\t\t\tvisitManyHasOne: err,\n\t\t})\n\t}\n\n\t/** See {@link connectJunction} for how `scope` maps onto the two sides. */\n\tpublic async disconnectJunction(\n\t\tentity: Model.Entity,\n\t\trelation: Model.ManyHasManyOwningRelation | Model.ManyHasManyInverseRelation,\n\t\tthisPrimary: Input.PrimaryValue,\n\t\totherPrimary: Input.PrimaryValue,\n\t\tscope: AclScope,\n\t): Promise<MutationResultList> {\n\t\tawait this.setupSystemVariables()\n\t\tconst err = () => {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\treturn await acceptFieldVisitor(this.schema, entity, relation, {\n\t\t\tvisitManyHasManyOwning: ({ entity, relation }) => {\n\t\t\t\treturn this.junctionTableManager.disconnectJunction(this, entity, relation, thisPrimary, otherPrimary, {\n\t\t\t\t\towning: scope,\n\t\t\t\t\tinverse: 'nested',\n\t\t\t\t})\n\t\t\t},\n\t\t\tvisitManyHasManyInverse: ({ targetEntity, targetRelation }) => {\n\t\t\t\treturn this.junctionTableManager.disconnectJunction(this, targetEntity, targetRelation, otherPrimary, thisPrimary, {\n\t\t\t\t\towning: 'nested',\n\t\t\t\t\tinverse: scope,\n\t\t\t\t})\n\t\t\t},\n\t\t\tvisitColumn: err,\n\t\t\tvisitOneHasMany: err,\n\t\t\tvisitOneHasOneInverse: err,\n\t\t\tvisitOneHasOneOwning: err,\n\t\t\tvisitManyHasOne: err,\n\t\t})\n\t}\n\n\t/**\n\t * Fetches the primary values of entities currently in a has-many relation of the given owner.\n\t * Used by the declarative `set` operation to compute orphans. Respects ACL read predicates on the target entity.\n\t */\n\tpublic async fetchHasManyPrimaries(\n\t\tcontext: Model.OneHasManyContext | Model.ManyHasManyOwningContext | Model.ManyHasManyInverseContext,\n\t\townerPrimary: Input.PrimaryValue,\n\t): Promise<Input.PrimaryValue[]> {\n\t\tif (context.type === 'oneHasMany') {\n\t\t\tconst { targetEntity, targetRelation } = context\n\t\t\t// Compare the FK column directly: filtering through the back-reference relation would also apply\n\t\t\t// the owner's and the relation field's read predicates, unlike the many-has-many junction read.\n\t\t\tconst readPredicate = this.predicatesInjector.inject(targetEntity, {}, 'nested')\n\t\t\tconst path = this.pathFactory.create([])\n\t\t\tlet qb = SelectBuilder.create()\n\t\t\t\t.from(targetEntity.tableName, path.alias)\n\t\t\t\t.select([path.alias, targetEntity.primaryColumn], 'primary_')\n\t\t\t\t.where(cond => cond.compare([path.alias, targetRelation.joiningColumn.columnName], Operator.eq, ownerPrimary))\n\t\t\tif (Object.keys(readPredicate).length > 0) {\n\t\t\t\tqb = this.whereBuilder.build(qb, targetEntity, path, readPredicate)\n\t\t\t}\n\t\t\tconst rows = await qb.getResult(this.db)\n\t\t\treturn rows.map(it => it.primary_ as Input.PrimaryValue)\n\t\t}\n\n\t\t// many-has-many: read from the junction table via the owning side\n\t\tconst owningContext = context.type === 'manyHasManyOwning'\n\t\t\t? { entity: context.entity, relation: context.relation, ownerIsJoining: true }\n\t\t\t: { entity: context.targetEntity, relation: context.targetRelation, ownerIsJoining: false }\n\t\tconst targetEntity = context.targetEntity\n\t\tconst joiningTable = owningContext.relation.joiningTable\n\t\tconst ownerColumn = owningContext.ownerIsJoining ? joiningTable.joiningColumn.columnName : joiningTable.inverseJoiningColumn.columnName\n\t\tconst targetColumn = owningContext.ownerIsJoining ? joiningTable.inverseJoiningColumn.columnName : joiningTable.joiningColumn.columnName\n\n\t\t// Apply the target entity's ACL read predicate so that members the current role cannot read\n\t\t// are excluded from the orphan computation (left untouched), matching the oneHasMany behavior.\n\t\t// `inject` returns an empty where when there is no read predicate, in which case the junction\n\t\t// is read directly with no join, preserving the permissive/no-ACL query unchanged.\n\t\tconst readPredicate = this.predicatesInjector.inject(targetEntity, {}, 'nested')\n\t\tconst hasReadPredicate = Object.keys(readPredicate).length > 0\n\n\t\tlet qb = SelectBuilder.create()\n\t\t\t.from(joiningTable.tableName, 'junction_')\n\t\t\t.select(['junction_', targetColumn], 'primary_')\n\t\t\t.where(cond => cond.compare(['junction_', ownerColumn], Operator.eq, ownerPrimary))\n\n\t\tif (hasReadPredicate) {\n\t\t\tconst path = this.pathFactory.create([])\n\t\t\tqb = qb.join(\n\t\t\t\ttargetEntity.tableName,\n\t\t\t\tpath.alias,\n\t\t\t\tclause => clause.compareColumns(['junction_', targetColumn], Operator.eq, [path.alias, targetEntity.primaryColumn]),\n\t\t\t)\n\t\t\tqb = this.whereBuilder.build(qb, targetEntity, path, readPredicate)\n\t\t}\n\n\t\tconst rows = await qb.getResult(this.db)\n\t\treturn rows.map(it => it.primary_ as Input.PrimaryValue)\n\t}\n\n\tpublic async getPrimaryValue(\n\t\tentity: Model.Entity,\n\t\twhere: Input.UniqueWhere | CheckedPrimary,\n\t\tscope: AclScope,\n\t): Promise<[Input.PrimaryValue, undefined] | [undefined, MutationEntryNotFoundError]> {\n\t\tif (where instanceof CheckedPrimary) {\n\t\t\treturn [where.primaryValue, undefined]\n\t\t}\n\t\tconst result = await this.selectField(entity, where, entity.primary, scope)\n\t\treturn result ? [result, undefined] : [undefined, new MutationEntryNotFoundError([], where)]\n\t}\n\n\tprivate async setupSystemVariables() {\n\t\tthis.systemVariablesSetupDone ??= (async () => {\n\t\t\tawait this.db.query('SELECT set_config(?, ?, false)', ['tenant.identity_id', this.identityId]) // todo rename to system.identity_id\n\t\t\tawait this.db.query('SELECT set_config(?, ?, false)', ['system.transaction_id', this.transactionId])\n\t\t})()\n\t\tawait this.systemVariablesSetupDone\n\t}\n}\n"],"names":["DeletedEntitiesStorage","Mutex","ConstraintHelper","EventManager","getColumnName","SelectBuilder","SelectHydrator","OrderByHelper","aclScopeFromPath","ImplementationException","tryMutation","ROW_LOOKUP_SCOPE","acceptFieldVisitor","entity","relation","targetEntity","readPredicate","qb","Operator","rows","CheckedPrimary","MutationEntryNotFoundError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA2BO,MAAM,OAAqF;AAAA,EAUjG,YACiB,IACA,YACA,eACC,QACA,wBACA,oBACA,sBACA,qBACA,cACA,sBACA,gBACA,SACA,UACA,aACA,cAChB;AAfe,SAAA,KAAA;AACA,SAAA,aAAA;AACA,SAAA,gBAAA;AACC,SAAA,SAAA;AACA,SAAA,yBAAA;AACA,SAAA,qBAAA;AACA,SAAA,uBAAA;AACA,SAAA,sBAAA;AACA,SAAA,eAAA;AACA,SAAA,uBAAA;AACA,SAAA,iBAAA;AACA,SAAA,UAAA;AACA,SAAA,WAAA;AACA,SAAA,cAAA;AACA,SAAA,eAAA;AAxBlB,kBAAA,MAAQ,0BAAA;AACR,kBAAA,MAAgB,mBAAkB,IAAIA,uBAAAA,uBAAA,CAAuB;AAC7D,kBAAA,MAAgB,SAAQ,IAAIC,MAAAA,MAAA,CAAM;AAClC,kBAAA,MAAgB,kBAAA;AAEhB,kBAAA,MAAgB,aAAA;AAEhB,kBAAA,MAAgB,cAAA;AAmBf,SAAK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C,sBAAsB,KAAK,UAAU,CAAC;AAC7F,YAAM,KAAK,GAAG,MAAM,kCAAkC,CAAC,yBAAyB,KAAK,aAAa,CAAC;AAAA,IACpG;AACA,UAAM,KAAK;AAAA,EACZ;AACD;;"}
@@ -1,11 +1,11 @@
1
1
  import { getColumnName, acceptFieldVisitor } from "@contember/schema-utils";
2
2
  import "@contember/schema";
3
- import { ConstraintHelper, SelectBuilder } from "@contember/database";
3
+ import { ConstraintHelper, SelectBuilder, Operator } from "@contember/database";
4
4
  import "node:crypto";
5
5
  import { aclScopeFromPath, ROW_LOOKUP_SCOPE } from "../acl/AclScope.js";
6
6
  import { ImplementationException } from "../exception.js";
7
7
  import { Mutex } from "../utils/Mutex.js";
8
- import "fast-deep-equal";
8
+ import "@contember/utilities";
9
9
  import "../acl/PredicatesInjector.js";
10
10
  import "./select/Path.js";
11
11
  import { OrderByHelper } from "./select/OrderByHelper.js";
@@ -244,6 +244,42 @@ class Mapper {
244
244
  visitManyHasOne: err
245
245
  });
246
246
  }
247
+ /**
248
+ * Fetches the primary values of entities currently in a has-many relation of the given owner.
249
+ * Used by the declarative `set` operation to compute orphans. Respects ACL read predicates on the target entity.
250
+ */
251
+ async fetchHasManyPrimaries(context, ownerPrimary) {
252
+ if (context.type === "oneHasMany") {
253
+ const { targetEntity: targetEntity2, targetRelation } = context;
254
+ const readPredicate2 = this.predicatesInjector.inject(targetEntity2, {}, "nested");
255
+ const path = this.pathFactory.create([]);
256
+ let qb2 = SelectBuilder.create().from(targetEntity2.tableName, path.alias).select([path.alias, targetEntity2.primaryColumn], "primary_").where((cond) => cond.compare([path.alias, targetRelation.joiningColumn.columnName], Operator.eq, ownerPrimary));
257
+ if (Object.keys(readPredicate2).length > 0) {
258
+ qb2 = this.whereBuilder.build(qb2, targetEntity2, path, readPredicate2);
259
+ }
260
+ const rows2 = await qb2.getResult(this.db);
261
+ return rows2.map((it) => it.primary_);
262
+ }
263
+ const owningContext = context.type === "manyHasManyOwning" ? { entity: context.entity, relation: context.relation, ownerIsJoining: true } : { entity: context.targetEntity, relation: context.targetRelation, ownerIsJoining: false };
264
+ const targetEntity = context.targetEntity;
265
+ const joiningTable = owningContext.relation.joiningTable;
266
+ const ownerColumn = owningContext.ownerIsJoining ? joiningTable.joiningColumn.columnName : joiningTable.inverseJoiningColumn.columnName;
267
+ const targetColumn = owningContext.ownerIsJoining ? joiningTable.inverseJoiningColumn.columnName : joiningTable.joiningColumn.columnName;
268
+ const readPredicate = this.predicatesInjector.inject(targetEntity, {}, "nested");
269
+ const hasReadPredicate = Object.keys(readPredicate).length > 0;
270
+ let qb = SelectBuilder.create().from(joiningTable.tableName, "junction_").select(["junction_", targetColumn], "primary_").where((cond) => cond.compare(["junction_", ownerColumn], Operator.eq, ownerPrimary));
271
+ if (hasReadPredicate) {
272
+ const path = this.pathFactory.create([]);
273
+ qb = qb.join(
274
+ targetEntity.tableName,
275
+ path.alias,
276
+ (clause) => clause.compareColumns(["junction_", targetColumn], Operator.eq, [path.alias, targetEntity.primaryColumn])
277
+ );
278
+ qb = this.whereBuilder.build(qb, targetEntity, path, readPredicate);
279
+ }
280
+ const rows = await qb.getResult(this.db);
281
+ return rows.map((it) => it.primary_);
282
+ }
247
283
  async getPrimaryValue(entity, where, scope) {
248
284
  if (where instanceof CheckedPrimary) {
249
285
  return [where.primaryValue, void 0];
@@ -1 +1 @@
1
- {"version":3,"file":"Mapper.js","sources":["../../../../../packages/engine-content-api/src/mapper/Mapper.ts"],"sourcesContent":["import { Input, Model } from '@contember/schema'\nimport { acceptFieldVisitor, getColumnName } from '@contember/schema-utils'\nimport {\n\tOrderByHelper,\n\tPathFactory,\n\tSelectBuilderFactory,\n\tSelectGroupedObjects,\n\tSelectHydrator,\n\tSelectIndexedResultObjects,\n\tSelectResultObject,\n\tWhereBuilder,\n} from './select/index.js'\nimport { Client, Connection, ConstraintHelper, DatabaseMetadata, RequestMemoryBudget, SelectBuilder } from '@contember/database'\nimport { AclScope, aclScopeFromPath, PredicatesInjector, ROW_LOOKUP_SCOPE } from '../acl/index.js'\nimport { JunctionTableManager } from './JunctionTableManager.js'\nimport { DeletedEntitiesStorage, DeleteExecutor } from './delete/index.js'\nimport { MutationEntryNotFoundError, MutationResultList } from './Result.js'\nimport { UpdateBuilder, Updater } from './update/index.js'\nimport { InsertBuilder, Inserter } from './insert/index.js'\nimport { tryMutation } from './ErrorUtils.js'\nimport { ObjectNode, UniqueWhereExpander } from '../inputProcessing/index.js'\nimport { Mutex } from '../utils/index.js'\nimport { CheckedPrimary } from './CheckedPrimary.js'\nimport { ImplementationException } from '../exception.js'\nimport { EventManager } from './EventManager.js'\nimport { MapperInput } from './types.js'\n\nexport class Mapper<ConnectionType extends Connection.ConnectionLike = Connection.ConnectionLike> {\n\tprivate systemVariablesSetupDone: Promise<void> | undefined\n\tpublic readonly deletedEntities = new DeletedEntitiesStorage()\n\tpublic readonly mutex = new Mutex()\n\tpublic readonly constraintHelper: ConstraintHelper\n\t/** Charges the request memory budget; only selection results use it, internal mutation queries stay on `db`. */\n\tpublic readonly selectionDb: Client<ConnectionType>\n\n\tpublic readonly eventManager: EventManager\n\n\tconstructor(\n\t\tpublic readonly db: Client<ConnectionType>,\n\t\tpublic readonly identityId: string,\n\t\tpublic readonly transactionId: string,\n\t\tprivate readonly schema: Model.Schema,\n\t\tprivate readonly schemaDatabaseMetadata: DatabaseMetadata,\n\t\tprivate readonly predicatesInjector: PredicatesInjector,\n\t\tprivate readonly selectBuilderFactory: SelectBuilderFactory,\n\t\tprivate readonly uniqueWhereExpander: UniqueWhereExpander,\n\t\tprivate readonly whereBuilder: WhereBuilder,\n\t\tprivate readonly junctionTableManager: JunctionTableManager,\n\t\tprivate readonly deleteExecutor: DeleteExecutor,\n\t\tprivate readonly updater: Updater,\n\t\tprivate readonly inserter: Inserter,\n\t\tprivate readonly pathFactory: PathFactory,\n\t\tprivate readonly memoryBudget?: RequestMemoryBudget,\n\t) {\n\t\tthis.constraintHelper = new ConstraintHelper(db, this.schemaDatabaseMetadata)\n\t\tthis.selectionDb = memoryBudget ? db.withMemoryBudget(memoryBudget, { chargeRows: true }) : db\n\t\tthis.eventManager = new EventManager(this)\n\t}\n\n\tpublic async selectField(entity: Model.Entity, where: Input.UniqueWhere | CheckedPrimary, fieldName: string, scope: AclScope) {\n\t\tconst columnName = getColumnName(this.schema, entity, fieldName)\n\n\t\tconst qb = SelectBuilder.create() //\n\t\t\t.from(entity.tableName, 'root_')\n\t\t\t.select(['root_', columnName])\n\t\tconst expandedWhere = this.uniqueWhereExpander.expand(entity, where)\n\t\tconst withPredicates = this.predicatesInjector.inject(entity, expandedWhere, scope)\n\t\tconst builtQb = this.whereBuilder.build(qb, entity, this.pathFactory.create([]), withPredicates)\n\t\tconst result = await builtQb.getResult(this.db)\n\n\t\treturn result[0] !== undefined ? result[0][columnName] : undefined\n\t}\n\n\tpublic async selectAssoc(\n\t\tentity: Model.Entity,\n\t\tinput: ObjectNode<Input.ListQueryInput>,\n\t\trelationPath: Model.AnyRelationContext[],\n\t\tindexBy: string,\n\t): Promise<SelectIndexedResultObjects> {\n\t\tconst hydrator = new SelectHydrator(this.memoryBudget)\n\t\tconst path = this.pathFactory.create([])\n\t\tconst indexByAlias: string = path.forInternal('index').for(indexBy).alias\n\t\tconst qb: SelectBuilder = SelectBuilder.create()\n\t\t\t.select([path.alias, getColumnName(this.schema, entity, indexBy)], indexByAlias)\n\t\tconst rows = await this.selectRows(hydrator, qb, entity, input, relationPath)\n\t\treturn await hydrator.hydrateAll(rows, indexByAlias)\n\t}\n\n\tpublic async select(\n\t\tentity: Model.Entity,\n\t\tinput: ObjectNode<Input.ListQueryInput>,\n\t\trelationPath: Model.AnyRelationContext[],\n\t): Promise<SelectResultObject[]> {\n\t\tconst hydrator = new SelectHydrator(this.memoryBudget)\n\t\tconst qb: SelectBuilder<SelectBuilder.Result> = SelectBuilder.create()\n\n\t\tconst rows = await this.selectRows(hydrator, qb, entity, input, relationPath)\n\n\t\treturn await hydrator.hydrateAll(rows)\n\t}\n\n\tpublic async selectUnique(\n\t\tentity: Model.Entity,\n\t\tquery: ObjectNode<Input.UniqueQueryInput>,\n\t\trelationPath: Model.AnyRelationContext[],\n\t): Promise<SelectResultObject | null> {\n\t\tconst uniqueWhere = this.uniqueWhereExpander.expand(entity, query.args.by)\n\t\tconst where = query.args.filter ? { and: [uniqueWhere, query.args.filter] } : uniqueWhere\n\t\tconst queryExpanded = query.withArg<Input.ListQueryInput>('filter', where)\n\n\t\tconst rows = await this.select(entity, queryExpanded, relationPath)\n\n\t\treturn rows[0] ?? null\n\t}\n\n\tpublic async selectGrouped(\n\t\tentity: Model.Entity,\n\t\tinput: ObjectNode<Input.ListQueryInput>,\n\t\trelation: Model.JoiningColumnRelation & Model.AnyRelation,\n\t\trelationPath: Model.AnyRelationContext[],\n\t): Promise<SelectGroupedObjects> {\n\t\tconst hydrator = new SelectHydrator(this.memoryBudget)\n\t\tconst path = this.pathFactory.create([])\n\t\tconst groupingKey = '__grouping_key'\n\t\tconst qb: SelectBuilder = SelectBuilder.create()\n\t\t\t.select([path.alias, relation.joiningColumn.columnName], groupingKey)\n\n\t\tconst rows = await this.selectRows(hydrator, qb, entity, input, relationPath, relation.name)\n\n\t\treturn await hydrator.hydrateGroups(rows, groupingKey)\n\t}\n\n\tprivate async selectRows(\n\t\thydrator: SelectHydrator,\n\t\tqb: SelectBuilder<SelectBuilder.Result>,\n\t\tentity: Model.Entity,\n\t\tinput: ObjectNode<Input.ListQueryInput>,\n\t\trelationPath: Model.AnyRelationContext[],\n\t\tgroupBy?: string,\n\t) {\n\t\tconst inputWithOrder = OrderByHelper.appendDefaultOrderBy(entity, input, undefined)\n\t\tconst path = this.pathFactory.create([])\n\t\tconst augmentedBuilder = qb.from(entity.tableName, path.alias).meta('path', [...input.path, input.alias])\n\n\t\tconst selector = this.selectBuilderFactory.create(augmentedBuilder, hydrator, relationPath)\n\t\tconst filterWithPredicates = this.predicatesInjector.inject(\n\t\t\tentity,\n\t\t\tinputWithOrder.args.filter || {},\n\t\t\taclScopeFromPath(relationPath),\n\t\t\trelationPath[relationPath.length - 1],\n\t\t\trelationPath,\n\t\t)\n\t\tconst inputWithPredicates = inputWithOrder.withArg('filter', filterWithPredicates)\n\t\tselector.select(this, entity, inputWithPredicates, path, groupBy)\n\t\treturn await selector.execute(this.selectionDb)\n\t}\n\n\tpublic async count(entity: Model.Entity, filter: Input.OptionalWhere, scope: AclScope) {\n\t\tconst path = this.pathFactory.create([])\n\t\tconst qb = SelectBuilder.create()\n\t\t\t.from(entity.tableName, path.alias)\n\t\t\t.select(expr => expr.raw('count(*)'), 'row_count')\n\t\tconst withPredicates = this.predicatesInjector.inject(entity, filter, scope)\n\t\tconst qbWithWhere = this.whereBuilder.build(qb, entity, path, withPredicates)\n\t\tconst result = await qbWithWhere.getResult(this.db)\n\t\treturn result[0].row_count\n\t}\n\n\tpublic async countGrouped(\n\t\tentity: Model.Entity,\n\t\tfilter: Input.OptionalWhere,\n\t\trelation: Model.JoiningColumnRelation & Model.Relation,\n\t\trelationPath: Model.AnyRelationContext[],\n\t): Promise<Record<string, number>> {\n\t\tconst path = this.pathFactory.create([])\n\t\tconst qb = SelectBuilder.create()\n\t\t\t.from(entity.tableName, path.alias)\n\t\t\t.select(expr => expr.raw('count(*)'), 'row_count')\n\t\t\t.select([path.alias, relation.joiningColumn.columnName])\n\t\t\t.groupBy([path.alias, relation.joiningColumn.columnName])\n\t\tconst withPredicates = this.predicatesInjector.inject(\n\t\t\tentity,\n\t\t\tfilter,\n\t\t\taclScopeFromPath(relationPath),\n\t\t\trelationPath[relationPath.length - 1],\n\t\t\trelationPath,\n\t\t)\n\t\tconst qbWithWhere = this.whereBuilder.build(qb, entity, path, withPredicates, { relationPath })\n\t\tconst rows = await qbWithWhere.getResult(this.db)\n\t\tconst result = new Map<string, number>()\n\t\tfor (const row of rows) {\n\t\t\tresult.set(String(row[relation.joiningColumn.columnName]), Number(row.row_count))\n\t\t}\n\t\treturn Object.fromEntries(result)\n\t}\n\n\tpublic async insert(\n\t\tentity: Model.Entity,\n\t\tdata: MapperInput.CreateDataInput,\n\t\tscope: AclScope,\n\t\tbuilderCb: (builder: InsertBuilder) => void = () => {},\n\t): Promise<MutationResultList> {\n\t\tif (entity.view) {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\tawait this.setupSystemVariables()\n\t\treturn tryMutation(this.schema, this.schemaDatabaseMetadata, () => this.insertInternal(entity, data, scope, builderCb))\n\t}\n\n\tpublic async update(\n\t\tentity: Model.Entity,\n\t\tby: Input.UniqueWhere | CheckedPrimary,\n\t\tdata: MapperInput.UpdateDataInput,\n\t\tscope: AclScope,\n\t\tfilter?: Input.OptionalWhere,\n\t): Promise<MutationResultList> {\n\t\tif (entity.view) {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\tawait this.setupSystemVariables()\n\t\treturn tryMutation(this.schema, this.schemaDatabaseMetadata, async () => {\n\t\t\tconst [primaryValue, err] = await this.getPrimaryValue(entity, by, ROW_LOOKUP_SCOPE)\n\t\t\tif (err) return [err]\n\n\t\t\treturn await this.updater.update(this, entity, primaryValue, data, scope, filter)\n\t\t})\n\t}\n\n\tpublic async updateInternal(\n\t\tentity: Model.Entity,\n\t\tby: Input.UniqueWhere | CheckedPrimary,\n\t\tbuilderCb: (builder: UpdateBuilder) => void,\n\t\tscope: AclScope,\n\t): Promise<MutationResultList> {\n\t\tif (entity.view) {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\tawait this.setupSystemVariables()\n\t\treturn tryMutation(this.schema, this.schemaDatabaseMetadata, async () => {\n\t\t\tconst [primaryValue, err] = await this.getPrimaryValue(entity, by, ROW_LOOKUP_SCOPE)\n\t\t\tif (err) return [err]\n\n\t\t\treturn await this.updater.updateCb(this, entity, primaryValue, builderCb, scope)\n\t\t})\n\t}\n\tpublic async upsert(\n\t\tentity: Model.Entity,\n\t\tby: Input.UniqueWhere | CheckedPrimary,\n\t\tupdate: MapperInput.UpdateDataInput,\n\t\tcreate: MapperInput.CreateDataInput,\n\t\tscope: AclScope,\n\t\tfilter?: Input.OptionalWhere,\n\t): Promise<MutationResultList> {\n\t\tif (entity.view) {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\tawait this.setupSystemVariables()\n\t\treturn tryMutation(this.schema, this.schemaDatabaseMetadata, async () => {\n\t\t\tconst [primaryValue] = await this.getPrimaryValue(entity, by, ROW_LOOKUP_SCOPE)\n\t\t\tif (primaryValue === undefined) {\n\t\t\t\treturn await this.insertInternal(entity, create, scope)\n\t\t\t}\n\t\t\treturn await this.updater.update(this, entity, primaryValue, update, scope, filter)\n\t\t})\n\t}\n\n\tprivate insertInternal(\n\t\tentity: Model.Entity,\n\t\tdata: MapperInput.CreateDataInput,\n\t\tscope: AclScope,\n\t\tbuilderCb: (builder: InsertBuilder) => void = () => {},\n\t) {\n\t\treturn this.inserter.insert(\n\t\t\tthis,\n\t\t\tentity,\n\t\t\tdata,\n\t\t\tid => {\n\t\t\t},\n\t\t\tbuilderCb,\n\t\t\tscope,\n\t\t)\n\t}\n\n\tpublic async delete(\n\t\tentity: Model.Entity,\n\t\tby: Input.UniqueWhere | CheckedPrimary,\n\t\tscope: AclScope,\n\t\tfilter?: Input.OptionalWhere,\n\t): Promise<MutationResultList> {\n\t\tif (entity.view) {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\tawait this.setupSystemVariables()\n\t\treturn tryMutation(this.schema, this.schemaDatabaseMetadata, () => {\n\t\t\treturn this.deleteExecutor.execute(this, entity, by, scope, filter)\n\t\t})\n\t}\n\n\t/**\n\t * `scope` belongs to `entity` - the side the caller named. The other side of the junction is\n\t * reached over the relation, so it always resolves as nested.\n\t */\n\tpublic async connectJunction(\n\t\tentity: Model.Entity,\n\t\trelation: Model.ManyHasManyOwningRelation | Model.ManyHasManyInverseRelation,\n\t\tthisPrimary: Input.PrimaryValue,\n\t\totherPrimary: Input.PrimaryValue,\n\t\tscope: AclScope,\n\t): Promise<MutationResultList> {\n\t\tawait this.setupSystemVariables()\n\t\tconst err = () => {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\treturn await acceptFieldVisitor(this.schema, entity, relation, {\n\t\t\tvisitManyHasManyOwning: ({ entity, relation }) => {\n\t\t\t\treturn this.junctionTableManager.connectJunction(this, entity, relation, thisPrimary, otherPrimary, {\n\t\t\t\t\towning: scope,\n\t\t\t\t\tinverse: 'nested',\n\t\t\t\t})\n\t\t\t},\n\t\t\tvisitManyHasManyInverse: ({ targetEntity, targetRelation }) => {\n\t\t\t\treturn this.junctionTableManager.connectJunction(this, targetEntity, targetRelation, otherPrimary, thisPrimary, {\n\t\t\t\t\towning: 'nested',\n\t\t\t\t\tinverse: scope,\n\t\t\t\t})\n\t\t\t},\n\t\t\tvisitColumn: err,\n\t\t\tvisitOneHasMany: err,\n\t\t\tvisitOneHasOneInverse: err,\n\t\t\tvisitOneHasOneOwning: err,\n\t\t\tvisitManyHasOne: err,\n\t\t})\n\t}\n\n\t/** See {@link connectJunction} for how `scope` maps onto the two sides. */\n\tpublic async disconnectJunction(\n\t\tentity: Model.Entity,\n\t\trelation: Model.ManyHasManyOwningRelation | Model.ManyHasManyInverseRelation,\n\t\tthisPrimary: Input.PrimaryValue,\n\t\totherPrimary: Input.PrimaryValue,\n\t\tscope: AclScope,\n\t): Promise<MutationResultList> {\n\t\tawait this.setupSystemVariables()\n\t\tconst err = () => {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\treturn await acceptFieldVisitor(this.schema, entity, relation, {\n\t\t\tvisitManyHasManyOwning: ({ entity, relation }) => {\n\t\t\t\treturn this.junctionTableManager.disconnectJunction(this, entity, relation, thisPrimary, otherPrimary, {\n\t\t\t\t\towning: scope,\n\t\t\t\t\tinverse: 'nested',\n\t\t\t\t})\n\t\t\t},\n\t\t\tvisitManyHasManyInverse: ({ targetEntity, targetRelation }) => {\n\t\t\t\treturn this.junctionTableManager.disconnectJunction(this, targetEntity, targetRelation, otherPrimary, thisPrimary, {\n\t\t\t\t\towning: 'nested',\n\t\t\t\t\tinverse: scope,\n\t\t\t\t})\n\t\t\t},\n\t\t\tvisitColumn: err,\n\t\t\tvisitOneHasMany: err,\n\t\t\tvisitOneHasOneInverse: err,\n\t\t\tvisitOneHasOneOwning: err,\n\t\t\tvisitManyHasOne: err,\n\t\t})\n\t}\n\n\tpublic async getPrimaryValue(\n\t\tentity: Model.Entity,\n\t\twhere: Input.UniqueWhere | CheckedPrimary,\n\t\tscope: AclScope,\n\t): Promise<[Input.PrimaryValue, undefined] | [undefined, MutationEntryNotFoundError]> {\n\t\tif (where instanceof CheckedPrimary) {\n\t\t\treturn [where.primaryValue, undefined]\n\t\t}\n\t\tconst result = await this.selectField(entity, where, entity.primary, scope)\n\t\treturn result ? [result, undefined] : [undefined, new MutationEntryNotFoundError([], where)]\n\t}\n\n\tprivate async setupSystemVariables() {\n\t\tthis.systemVariablesSetupDone ??= (async () => {\n\t\t\tawait this.db.query('SELECT set_config(?, ?, false)', ['tenant.identity_id', this.identityId]) // todo rename to system.identity_id\n\t\t\tawait this.db.query('SELECT set_config(?, ?, false)', ['system.transaction_id', this.transactionId])\n\t\t})()\n\t\tawait this.systemVariablesSetupDone\n\t}\n}\n"],"names":["entity","relation"],"mappings":";;;;;;;;;;;;;;;;;;;;AA2BO,MAAM,OAAqF;AAAA,EAUjG,YACiB,IACA,YACA,eACC,QACA,wBACA,oBACA,sBACA,qBACA,cACA,sBACA,gBACA,SACA,UACA,aACA,cAChB;AAfe,SAAA,KAAA;AACA,SAAA,aAAA;AACA,SAAA,gBAAA;AACC,SAAA,SAAA;AACA,SAAA,yBAAA;AACA,SAAA,qBAAA;AACA,SAAA,uBAAA;AACA,SAAA,sBAAA;AACA,SAAA,eAAA;AACA,SAAA,uBAAA;AACA,SAAA,iBAAA;AACA,SAAA,UAAA;AACA,SAAA,WAAA;AACA,SAAA,cAAA;AACA,SAAA,eAAA;AAxBlB,kBAAA,MAAQ,0BAAA;AACR,kBAAA,MAAgB,mBAAkB,IAAI,uBAAA,CAAuB;AAC7D,kB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BAAiB;AAAA,MACjB,uBAAuB;AAAA,MACvB,sBAAsB;AAAA,MACtB,iBAAiB;AAAA,IAAA,CACjB;AAAA,EACF;AAAA,EAEA,MAAa,gBACZ,QACA,OACA,OACqF;AACrF,QAAI,iBAAiB,gBAAgB;AACpC,aAAO,CAAC,MAAM,cAAc,MAAS;AAAA,IACtC;AACA,UAAM,SAAS,MAAM,KAAK,YAAY,QAAQ,OAAO,OAAO,SAAS,KAAK;AAC1E,WAAO,SAAS,CAAC,QAAQ,MAAS,IAAI,CAAC,QAAW,IAAI,2BAA2B,IAAI,KAAK,CAAC;AAAA,EAC5F;AAAA,EAEA,MAAc,uBAAuB;AACpC,SAAK,6BAAL,KAAK,4BAA8B,YAAY;AAC9C,YAAM,KAAK,GAAG,MAAM,kCAAkC,CAAC,sBAAsB,KAAK,UAAU,CAAC;AAC7F,YAAM,KAAK,GAAG,MAAM,kCAAkC,CAAC,yBAAyB,KAAK,aAAa,CAAC;AAAA,IACpG;AACA,UAAM,KAAK;AAAA,EACZ;AACD;"}
1
+ {"version":3,"file":"Mapper.js","sources":["../../../../../packages/engine-content-api/src/mapper/Mapper.ts"],"sourcesContent":["import { Input, Model } from '@contember/schema'\nimport { acceptFieldVisitor, getColumnName } from '@contember/schema-utils'\nimport {\n\tOrderByHelper,\n\tPathFactory,\n\tSelectBuilderFactory,\n\tSelectGroupedObjects,\n\tSelectHydrator,\n\tSelectIndexedResultObjects,\n\tSelectResultObject,\n\tWhereBuilder,\n} from './select/index.js'\nimport { Client, Connection, ConstraintHelper, DatabaseMetadata, Operator, RequestMemoryBudget, SelectBuilder } from '@contember/database'\nimport { AclScope, aclScopeFromPath, PredicatesInjector, ROW_LOOKUP_SCOPE } from '../acl/index.js'\nimport { JunctionTableManager } from './JunctionTableManager.js'\nimport { DeletedEntitiesStorage, DeleteExecutor } from './delete/index.js'\nimport { MutationEntryNotFoundError, MutationResultList } from './Result.js'\nimport { UpdateBuilder, Updater } from './update/index.js'\nimport { InsertBuilder, Inserter } from './insert/index.js'\nimport { tryMutation } from './ErrorUtils.js'\nimport { ObjectNode, UniqueWhereExpander } from '../inputProcessing/index.js'\nimport { Mutex } from '../utils/index.js'\nimport { CheckedPrimary } from './CheckedPrimary.js'\nimport { ImplementationException } from '../exception.js'\nimport { EventManager } from './EventManager.js'\nimport { MapperInput } from './types.js'\n\nexport class Mapper<ConnectionType extends Connection.ConnectionLike = Connection.ConnectionLike> {\n\tprivate systemVariablesSetupDone: Promise<void> | undefined\n\tpublic readonly deletedEntities = new DeletedEntitiesStorage()\n\tpublic readonly mutex = new Mutex()\n\tpublic readonly constraintHelper: ConstraintHelper\n\t/** Charges the request memory budget; only selection results use it, internal mutation queries stay on `db`. */\n\tpublic readonly selectionDb: Client<ConnectionType>\n\n\tpublic readonly eventManager: EventManager\n\n\tconstructor(\n\t\tpublic readonly db: Client<ConnectionType>,\n\t\tpublic readonly identityId: string,\n\t\tpublic readonly transactionId: string,\n\t\tprivate readonly schema: Model.Schema,\n\t\tprivate readonly schemaDatabaseMetadata: DatabaseMetadata,\n\t\tprivate readonly predicatesInjector: PredicatesInjector,\n\t\tprivate readonly selectBuilderFactory: SelectBuilderFactory,\n\t\tprivate readonly uniqueWhereExpander: UniqueWhereExpander,\n\t\tprivate readonly whereBuilder: WhereBuilder,\n\t\tprivate readonly junctionTableManager: JunctionTableManager,\n\t\tprivate readonly deleteExecutor: DeleteExecutor,\n\t\tprivate readonly updater: Updater,\n\t\tprivate readonly inserter: Inserter,\n\t\tprivate readonly pathFactory: PathFactory,\n\t\tprivate readonly memoryBudget?: RequestMemoryBudget,\n\t) {\n\t\tthis.constraintHelper = new ConstraintHelper(db, this.schemaDatabaseMetadata)\n\t\tthis.selectionDb = memoryBudget ? db.withMemoryBudget(memoryBudget, { chargeRows: true }) : db\n\t\tthis.eventManager = new EventManager(this)\n\t}\n\n\tpublic async selectField(entity: Model.Entity, where: Input.UniqueWhere | CheckedPrimary, fieldName: string, scope: AclScope) {\n\t\tconst columnName = getColumnName(this.schema, entity, fieldName)\n\n\t\tconst qb = SelectBuilder.create() //\n\t\t\t.from(entity.tableName, 'root_')\n\t\t\t.select(['root_', columnName])\n\t\tconst expandedWhere = this.uniqueWhereExpander.expand(entity, where)\n\t\tconst withPredicates = this.predicatesInjector.inject(entity, expandedWhere, scope)\n\t\tconst builtQb = this.whereBuilder.build(qb, entity, this.pathFactory.create([]), withPredicates)\n\t\tconst result = await builtQb.getResult(this.db)\n\n\t\treturn result[0] !== undefined ? result[0][columnName] : undefined\n\t}\n\n\tpublic async selectAssoc(\n\t\tentity: Model.Entity,\n\t\tinput: ObjectNode<Input.ListQueryInput>,\n\t\trelationPath: Model.AnyRelationContext[],\n\t\tindexBy: string,\n\t): Promise<SelectIndexedResultObjects> {\n\t\tconst hydrator = new SelectHydrator(this.memoryBudget)\n\t\tconst path = this.pathFactory.create([])\n\t\tconst indexByAlias: string = path.forInternal('index').for(indexBy).alias\n\t\tconst qb: SelectBuilder = SelectBuilder.create()\n\t\t\t.select([path.alias, getColumnName(this.schema, entity, indexBy)], indexByAlias)\n\t\tconst rows = await this.selectRows(hydrator, qb, entity, input, relationPath)\n\t\treturn await hydrator.hydrateAll(rows, indexByAlias)\n\t}\n\n\tpublic async select(\n\t\tentity: Model.Entity,\n\t\tinput: ObjectNode<Input.ListQueryInput>,\n\t\trelationPath: Model.AnyRelationContext[],\n\t): Promise<SelectResultObject[]> {\n\t\tconst hydrator = new SelectHydrator(this.memoryBudget)\n\t\tconst qb: SelectBuilder<SelectBuilder.Result> = SelectBuilder.create()\n\n\t\tconst rows = await this.selectRows(hydrator, qb, entity, input, relationPath)\n\n\t\treturn await hydrator.hydrateAll(rows)\n\t}\n\n\tpublic async selectUnique(\n\t\tentity: Model.Entity,\n\t\tquery: ObjectNode<Input.UniqueQueryInput>,\n\t\trelationPath: Model.AnyRelationContext[],\n\t): Promise<SelectResultObject | null> {\n\t\tconst uniqueWhere = this.uniqueWhereExpander.expand(entity, query.args.by)\n\t\tconst where = query.args.filter ? { and: [uniqueWhere, query.args.filter] } : uniqueWhere\n\t\tconst queryExpanded = query.withArg<Input.ListQueryInput>('filter', where)\n\n\t\tconst rows = await this.select(entity, queryExpanded, relationPath)\n\n\t\treturn rows[0] ?? null\n\t}\n\n\tpublic async selectGrouped(\n\t\tentity: Model.Entity,\n\t\tinput: ObjectNode<Input.ListQueryInput>,\n\t\trelation: Model.JoiningColumnRelation & Model.AnyRelation,\n\t\trelationPath: Model.AnyRelationContext[],\n\t): Promise<SelectGroupedObjects> {\n\t\tconst hydrator = new SelectHydrator(this.memoryBudget)\n\t\tconst path = this.pathFactory.create([])\n\t\tconst groupingKey = '__grouping_key'\n\t\tconst qb: SelectBuilder = SelectBuilder.create()\n\t\t\t.select([path.alias, relation.joiningColumn.columnName], groupingKey)\n\n\t\tconst rows = await this.selectRows(hydrator, qb, entity, input, relationPath, relation.name)\n\n\t\treturn await hydrator.hydrateGroups(rows, groupingKey)\n\t}\n\n\tprivate async selectRows(\n\t\thydrator: SelectHydrator,\n\t\tqb: SelectBuilder<SelectBuilder.Result>,\n\t\tentity: Model.Entity,\n\t\tinput: ObjectNode<Input.ListQueryInput>,\n\t\trelationPath: Model.AnyRelationContext[],\n\t\tgroupBy?: string,\n\t) {\n\t\tconst inputWithOrder = OrderByHelper.appendDefaultOrderBy(entity, input, undefined)\n\t\tconst path = this.pathFactory.create([])\n\t\tconst augmentedBuilder = qb.from(entity.tableName, path.alias).meta('path', [...input.path, input.alias])\n\n\t\tconst selector = this.selectBuilderFactory.create(augmentedBuilder, hydrator, relationPath)\n\t\tconst filterWithPredicates = this.predicatesInjector.inject(\n\t\t\tentity,\n\t\t\tinputWithOrder.args.filter || {},\n\t\t\taclScopeFromPath(relationPath),\n\t\t\trelationPath[relationPath.length - 1],\n\t\t\trelationPath,\n\t\t)\n\t\tconst inputWithPredicates = inputWithOrder.withArg('filter', filterWithPredicates)\n\t\tselector.select(this, entity, inputWithPredicates, path, groupBy)\n\t\treturn await selector.execute(this.selectionDb)\n\t}\n\n\tpublic async count(entity: Model.Entity, filter: Input.OptionalWhere, scope: AclScope) {\n\t\tconst path = this.pathFactory.create([])\n\t\tconst qb = SelectBuilder.create()\n\t\t\t.from(entity.tableName, path.alias)\n\t\t\t.select(expr => expr.raw('count(*)'), 'row_count')\n\t\tconst withPredicates = this.predicatesInjector.inject(entity, filter, scope)\n\t\tconst qbWithWhere = this.whereBuilder.build(qb, entity, path, withPredicates)\n\t\tconst result = await qbWithWhere.getResult(this.db)\n\t\treturn result[0].row_count\n\t}\n\n\tpublic async countGrouped(\n\t\tentity: Model.Entity,\n\t\tfilter: Input.OptionalWhere,\n\t\trelation: Model.JoiningColumnRelation & Model.Relation,\n\t\trelationPath: Model.AnyRelationContext[],\n\t): Promise<Record<string, number>> {\n\t\tconst path = this.pathFactory.create([])\n\t\tconst qb = SelectBuilder.create()\n\t\t\t.from(entity.tableName, path.alias)\n\t\t\t.select(expr => expr.raw('count(*)'), 'row_count')\n\t\t\t.select([path.alias, relation.joiningColumn.columnName])\n\t\t\t.groupBy([path.alias, relation.joiningColumn.columnName])\n\t\tconst withPredicates = this.predicatesInjector.inject(\n\t\t\tentity,\n\t\t\tfilter,\n\t\t\taclScopeFromPath(relationPath),\n\t\t\trelationPath[relationPath.length - 1],\n\t\t\trelationPath,\n\t\t)\n\t\tconst qbWithWhere = this.whereBuilder.build(qb, entity, path, withPredicates, { relationPath })\n\t\tconst rows = await qbWithWhere.getResult(this.db)\n\t\tconst result = new Map<string, number>()\n\t\tfor (const row of rows) {\n\t\t\tresult.set(String(row[relation.joiningColumn.columnName]), Number(row.row_count))\n\t\t}\n\t\treturn Object.fromEntries(result)\n\t}\n\n\tpublic async insert(\n\t\tentity: Model.Entity,\n\t\tdata: MapperInput.CreateDataInput,\n\t\tscope: AclScope,\n\t\tbuilderCb: (builder: InsertBuilder) => void = () => {},\n\t): Promise<MutationResultList> {\n\t\tif (entity.view) {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\tawait this.setupSystemVariables()\n\t\treturn tryMutation(this.schema, this.schemaDatabaseMetadata, () => this.insertInternal(entity, data, scope, builderCb))\n\t}\n\n\tpublic async update(\n\t\tentity: Model.Entity,\n\t\tby: Input.UniqueWhere | CheckedPrimary,\n\t\tdata: MapperInput.UpdateDataInput,\n\t\tscope: AclScope,\n\t\tfilter?: Input.OptionalWhere,\n\t): Promise<MutationResultList> {\n\t\tif (entity.view) {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\tawait this.setupSystemVariables()\n\t\treturn tryMutation(this.schema, this.schemaDatabaseMetadata, async () => {\n\t\t\tconst [primaryValue, err] = await this.getPrimaryValue(entity, by, ROW_LOOKUP_SCOPE)\n\t\t\tif (err) return [err]\n\n\t\t\treturn await this.updater.update(this, entity, primaryValue, data, scope, filter)\n\t\t})\n\t}\n\n\tpublic async updateInternal(\n\t\tentity: Model.Entity,\n\t\tby: Input.UniqueWhere | CheckedPrimary,\n\t\tbuilderCb: (builder: UpdateBuilder) => void,\n\t\tscope: AclScope,\n\t): Promise<MutationResultList> {\n\t\tif (entity.view) {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\tawait this.setupSystemVariables()\n\t\treturn tryMutation(this.schema, this.schemaDatabaseMetadata, async () => {\n\t\t\tconst [primaryValue, err] = await this.getPrimaryValue(entity, by, ROW_LOOKUP_SCOPE)\n\t\t\tif (err) return [err]\n\n\t\t\treturn await this.updater.updateCb(this, entity, primaryValue, builderCb, scope)\n\t\t})\n\t}\n\tpublic async upsert(\n\t\tentity: Model.Entity,\n\t\tby: Input.UniqueWhere | CheckedPrimary,\n\t\tupdate: MapperInput.UpdateDataInput,\n\t\tcreate: MapperInput.CreateDataInput,\n\t\tscope: AclScope,\n\t\tfilter?: Input.OptionalWhere,\n\t): Promise<MutationResultList> {\n\t\tif (entity.view) {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\tawait this.setupSystemVariables()\n\t\treturn tryMutation(this.schema, this.schemaDatabaseMetadata, async () => {\n\t\t\tconst [primaryValue] = await this.getPrimaryValue(entity, by, ROW_LOOKUP_SCOPE)\n\t\t\tif (primaryValue === undefined) {\n\t\t\t\treturn await this.insertInternal(entity, create, scope)\n\t\t\t}\n\t\t\treturn await this.updater.update(this, entity, primaryValue, update, scope, filter)\n\t\t})\n\t}\n\n\tprivate insertInternal(\n\t\tentity: Model.Entity,\n\t\tdata: MapperInput.CreateDataInput,\n\t\tscope: AclScope,\n\t\tbuilderCb: (builder: InsertBuilder) => void = () => {},\n\t) {\n\t\treturn this.inserter.insert(\n\t\t\tthis,\n\t\t\tentity,\n\t\t\tdata,\n\t\t\tid => {\n\t\t\t},\n\t\t\tbuilderCb,\n\t\t\tscope,\n\t\t)\n\t}\n\n\tpublic async delete(\n\t\tentity: Model.Entity,\n\t\tby: Input.UniqueWhere | CheckedPrimary,\n\t\tscope: AclScope,\n\t\tfilter?: Input.OptionalWhere,\n\t): Promise<MutationResultList> {\n\t\tif (entity.view) {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\tawait this.setupSystemVariables()\n\t\treturn tryMutation(this.schema, this.schemaDatabaseMetadata, () => {\n\t\t\treturn this.deleteExecutor.execute(this, entity, by, scope, filter)\n\t\t})\n\t}\n\n\t/**\n\t * `scope` belongs to `entity` - the side the caller named. The other side of the junction is\n\t * reached over the relation, so it always resolves as nested.\n\t */\n\tpublic async connectJunction(\n\t\tentity: Model.Entity,\n\t\trelation: Model.ManyHasManyOwningRelation | Model.ManyHasManyInverseRelation,\n\t\tthisPrimary: Input.PrimaryValue,\n\t\totherPrimary: Input.PrimaryValue,\n\t\tscope: AclScope,\n\t): Promise<MutationResultList> {\n\t\tawait this.setupSystemVariables()\n\t\tconst err = () => {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\treturn await acceptFieldVisitor(this.schema, entity, relation, {\n\t\t\tvisitManyHasManyOwning: ({ entity, relation }) => {\n\t\t\t\treturn this.junctionTableManager.connectJunction(this, entity, relation, thisPrimary, otherPrimary, {\n\t\t\t\t\towning: scope,\n\t\t\t\t\tinverse: 'nested',\n\t\t\t\t})\n\t\t\t},\n\t\t\tvisitManyHasManyInverse: ({ targetEntity, targetRelation }) => {\n\t\t\t\treturn this.junctionTableManager.connectJunction(this, targetEntity, targetRelation, otherPrimary, thisPrimary, {\n\t\t\t\t\towning: 'nested',\n\t\t\t\t\tinverse: scope,\n\t\t\t\t})\n\t\t\t},\n\t\t\tvisitColumn: err,\n\t\t\tvisitOneHasMany: err,\n\t\t\tvisitOneHasOneInverse: err,\n\t\t\tvisitOneHasOneOwning: err,\n\t\t\tvisitManyHasOne: err,\n\t\t})\n\t}\n\n\t/** See {@link connectJunction} for how `scope` maps onto the two sides. */\n\tpublic async disconnectJunction(\n\t\tentity: Model.Entity,\n\t\trelation: Model.ManyHasManyOwningRelation | Model.ManyHasManyInverseRelation,\n\t\tthisPrimary: Input.PrimaryValue,\n\t\totherPrimary: Input.PrimaryValue,\n\t\tscope: AclScope,\n\t): Promise<MutationResultList> {\n\t\tawait this.setupSystemVariables()\n\t\tconst err = () => {\n\t\t\tthrow new ImplementationException()\n\t\t}\n\t\treturn await acceptFieldVisitor(this.schema, entity, relation, {\n\t\t\tvisitManyHasManyOwning: ({ entity, relation }) => {\n\t\t\t\treturn this.junctionTableManager.disconnectJunction(this, entity, relation, thisPrimary, otherPrimary, {\n\t\t\t\t\towning: scope,\n\t\t\t\t\tinverse: 'nested',\n\t\t\t\t})\n\t\t\t},\n\t\t\tvisitManyHasManyInverse: ({ targetEntity, targetRelation }) => {\n\t\t\t\treturn this.junctionTableManager.disconnectJunction(this, targetEntity, targetRelation, otherPrimary, thisPrimary, {\n\t\t\t\t\towning: 'nested',\n\t\t\t\t\tinverse: scope,\n\t\t\t\t})\n\t\t\t},\n\t\t\tvisitColumn: err,\n\t\t\tvisitOneHasMany: err,\n\t\t\tvisitOneHasOneInverse: err,\n\t\t\tvisitOneHasOneOwning: err,\n\t\t\tvisitManyHasOne: err,\n\t\t})\n\t}\n\n\t/**\n\t * Fetches the primary values of entities currently in a has-many relation of the given owner.\n\t * Used by the declarative `set` operation to compute orphans. Respects ACL read predicates on the target entity.\n\t */\n\tpublic async fetchHasManyPrimaries(\n\t\tcontext: Model.OneHasManyContext | Model.ManyHasManyOwningContext | Model.ManyHasManyInverseContext,\n\t\townerPrimary: Input.PrimaryValue,\n\t): Promise<Input.PrimaryValue[]> {\n\t\tif (context.type === 'oneHasMany') {\n\t\t\tconst { targetEntity, targetRelation } = context\n\t\t\t// Compare the FK column directly: filtering through the back-reference relation would also apply\n\t\t\t// the owner's and the relation field's read predicates, unlike the many-has-many junction read.\n\t\t\tconst readPredicate = this.predicatesInjector.inject(targetEntity, {}, 'nested')\n\t\t\tconst path = this.pathFactory.create([])\n\t\t\tlet qb = SelectBuilder.create()\n\t\t\t\t.from(targetEntity.tableName, path.alias)\n\t\t\t\t.select([path.alias, targetEntity.primaryColumn], 'primary_')\n\t\t\t\t.where(cond => cond.compare([path.alias, targetRelation.joiningColumn.columnName], Operator.eq, ownerPrimary))\n\t\t\tif (Object.keys(readPredicate).length > 0) {\n\t\t\t\tqb = this.whereBuilder.build(qb, targetEntity, path, readPredicate)\n\t\t\t}\n\t\t\tconst rows = await qb.getResult(this.db)\n\t\t\treturn rows.map(it => it.primary_ as Input.PrimaryValue)\n\t\t}\n\n\t\t// many-has-many: read from the junction table via the owning side\n\t\tconst owningContext = context.type === 'manyHasManyOwning'\n\t\t\t? { entity: context.entity, relation: context.relation, ownerIsJoining: true }\n\t\t\t: { entity: context.targetEntity, relation: context.targetRelation, ownerIsJoining: false }\n\t\tconst targetEntity = context.targetEntity\n\t\tconst joiningTable = owningContext.relation.joiningTable\n\t\tconst ownerColumn = owningContext.ownerIsJoining ? joiningTable.joiningColumn.columnName : joiningTable.inverseJoiningColumn.columnName\n\t\tconst targetColumn = owningContext.ownerIsJoining ? joiningTable.inverseJoiningColumn.columnName : joiningTable.joiningColumn.columnName\n\n\t\t// Apply the target entity's ACL read predicate so that members the current role cannot read\n\t\t// are excluded from the orphan computation (left untouched), matching the oneHasMany behavior.\n\t\t// `inject` returns an empty where when there is no read predicate, in which case the junction\n\t\t// is read directly with no join, preserving the permissive/no-ACL query unchanged.\n\t\tconst readPredicate = this.predicatesInjector.inject(targetEntity, {}, 'nested')\n\t\tconst hasReadPredicate = Object.keys(readPredicate).length > 0\n\n\t\tlet qb = SelectBuilder.create()\n\t\t\t.from(joiningTable.tableName, 'junction_')\n\t\t\t.select(['junction_', targetColumn], 'primary_')\n\t\t\t.where(cond => cond.compare(['junction_', ownerColumn], Operator.eq, ownerPrimary))\n\n\t\tif (hasReadPredicate) {\n\t\t\tconst path = this.pathFactory.create([])\n\t\t\tqb = qb.join(\n\t\t\t\ttargetEntity.tableName,\n\t\t\t\tpath.alias,\n\t\t\t\tclause => clause.compareColumns(['junction_', targetColumn], Operator.eq, [path.alias, targetEntity.primaryColumn]),\n\t\t\t)\n\t\t\tqb = this.whereBuilder.build(qb, targetEntity, path, readPredicate)\n\t\t}\n\n\t\tconst rows = await qb.getResult(this.db)\n\t\treturn rows.map(it => it.primary_ as Input.PrimaryValue)\n\t}\n\n\tpublic async getPrimaryValue(\n\t\tentity: Model.Entity,\n\t\twhere: Input.UniqueWhere | CheckedPrimary,\n\t\tscope: AclScope,\n\t): Promise<[Input.PrimaryValue, undefined] | [undefined, MutationEntryNotFoundError]> {\n\t\tif (where instanceof CheckedPrimary) {\n\t\t\treturn [where.primaryValue, undefined]\n\t\t}\n\t\tconst result = await this.selectField(entity, where, entity.primary, scope)\n\t\treturn result ? [result, undefined] : [undefined, new MutationEntryNotFoundError([], where)]\n\t}\n\n\tprivate async setupSystemVariables() {\n\t\tthis.systemVariablesSetupDone ??= (async () => {\n\t\t\tawait this.db.query('SELECT set_config(?, ?, false)', ['tenant.identity_id', this.identityId]) // todo rename to system.identity_id\n\t\t\tawait this.db.query('SELECT set_config(?, ?, false)', ['system.transaction_id', this.transactionId])\n\t\t})()\n\t\tawait this.systemVariablesSetupDone\n\t}\n}\n"],"names":["entity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A,OACqF;AACrF,QAAI,iBAAiB,gBAAgB;AACpC,aAAO,CAAC,MAAM,cAAc,MAAS;AAAA,IACtC;AACA,UAAM,SAAS,MAAM,KAAK,YAAY,QAAQ,OAAO,OAAO,SAAS,KAAK;AAC1E,WAAO,SAAS,CAAC,QAAQ,MAAS,IAAI,CAAC,QAAW,IAAI,2BAA2B,IAAI,KAAK,CAAC;AAAA,EAC5F;AAAA,EAEA,MAAc,uBAAuB;AACpC,SAAK,6BAAL,KAAK,4BAA8B,YAAY;AAC9C,YAAM,KAAK,GAAG,MAAM,kCAAkC,CAAC,sBAAsB,KAAK,UAAU,CAAC;AAC7F,YAAM,KAAK,GAAG,MAAM,kCAAkC,CAAC,yBAAyB,KAAK,aAAa,CAAC;AAAA,IACpG;AACA,UAAM,KAAK;AAAA,EACZ;AACD;"}
@@ -12,6 +12,17 @@ const hasManyProcessor = (innerProcessor) => {
12
12
  return Result.prependPath(path, innerResult);
13
13
  };
14
14
  };
15
+ const relationFieldProcessor = (innerProcessor) => {
16
+ return async (context) => {
17
+ const { relation } = context;
18
+ const path = [{ field: relation.name }];
19
+ const innerResult = await innerProcessor(context);
20
+ if (typeof innerResult === "function") {
21
+ return async (it) => Result.prependPath(path, await innerResult(it));
22
+ }
23
+ return Result.prependPath(path, innerResult);
24
+ };
25
+ };
15
26
  const hasOneProcessor = (innerProcessor) => {
16
27
  return async (context) => {
17
28
  const { relation } = context;
@@ -25,4 +36,5 @@ const hasOneProcessor = (innerProcessor) => {
25
36
  };
26
37
  exports.hasManyProcessor = hasManyProcessor;
27
38
  exports.hasOneProcessor = hasOneProcessor;
39
+ exports.relationFieldProcessor = relationFieldProcessor;
28
40
  //# sourceMappingURL=MutationProcessorHelper.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"MutationProcessorHelper.cjs","sources":["../../../../../packages/engine-content-api/src/mapper/MutationProcessorHelper.ts"],"sourcesContent":["import { MutationResultList, prependPath } from './Result.js'\nimport { Model } from '@contember/schema'\n\nexport const hasManyProcessor = <Context extends { relation: Model.AnyRelation; index: number; alias?: string }, Args>(\n\tinnerProcessor: (context: Context) => Promise<MutationResultList | ((args: Args) => Promise<MutationResultList>)>,\n) => {\n\treturn async (context: Context): Promise<MutationResultList | ((args: Args) => Promise<MutationResultList>)> => {\n\t\tconst { relation, index, alias } = context\n\t\tconst path = [{ field: relation.name }, { index, alias }]\n\t\tconst innerResult = await innerProcessor(context)\n\t\tif (typeof innerResult === 'function') {\n\t\t\treturn async (it: Args) => prependPath(path, await innerResult(it))\n\t\t}\n\t\treturn prependPath(path, innerResult)\n\t}\n}\n\nexport const hasOneProcessor = <Context extends { relation: Model.AnyRelation }, Args>(\n\tinnerProcessor: (context: Context) => Promise<MutationResultList | ((args: Args) => Promise<MutationResultList>)>,\n) => {\n\treturn async (context: Context): Promise<MutationResultList | ((args: Args) => Promise<MutationResultList>)> => {\n\t\tconst { relation } = context\n\t\tconst path = [{ field: relation.name }]\n\t\tconst innerResult = await innerProcessor(context)\n\t\tif (typeof innerResult === 'function') {\n\t\t\treturn async (it: Args) => prependPath(path, await innerResult(it))\n\t\t}\n\t\treturn prependPath(path, innerResult)\n\t}\n}\n"],"names":["prependPath"],"mappings":";;;AAGO,MAAM,mBAAmB,CAC/B,mBACI;AACJ,SAAO,OAAO,YAAkG;AAC/G,UAAM,EAAE,UAAU,OAAO,MAAA,IAAU;AACnC,UAAM,OAAO,CAAC,EAAE,OAAO,SAAS,QAAQ,EAAE,OAAO,OAAO;AACxD,UAAM,cAAc,MAAM,eAAe,OAAO;AAChD,QAAI,OAAO,gBAAgB,YAAY;AACtC,aAAO,OAAO,OAAaA,OAAAA,YAAY,MAAM,MAAM,YAAY,EAAE,CAAC;AAAA,IACnE;AACA,WAAOA,OAAAA,YAAY,MAAM,WAAW;AAAA,EACrC;AACD;AAEO,MAAM,kBAAkB,CAC9B,mBACI;AACJ,SAAO,OAAO,YAAkG;AAC/G,UAAM,EAAE,aAAa;AACrB,UAAM,OAAO,CAAC,EAAE,OAAO,SAAS,MAAM;AACtC,UAAM,cAAc,MAAM,eAAe,OAAO;AAChD,QAAI,OAAO,gBAAgB,YAAY;AACtC,aAAO,OAAO,OAAaA,OAAAA,YAAY,MAAM,MAAM,YAAY,EAAE,CAAC;AAAA,IACnE;AACA,WAAOA,OAAAA,YAAY,MAAM,WAAW;AAAA,EACrC;AACD;;;"}
1
+ {"version":3,"file":"MutationProcessorHelper.cjs","sources":["../../../../../packages/engine-content-api/src/mapper/MutationProcessorHelper.ts"],"sourcesContent":["import { MutationResultList, prependPath } from './Result.js'\nimport { Model } from '@contember/schema'\n\nexport const hasManyProcessor = <Context extends { relation: Model.AnyRelation; index: number; alias?: string }, Args>(\n\tinnerProcessor: (context: Context) => Promise<MutationResultList | ((args: Args) => Promise<MutationResultList>)>,\n) => {\n\treturn async (context: Context): Promise<MutationResultList | ((args: Args) => Promise<MutationResultList>)> => {\n\t\tconst { relation, index, alias } = context\n\t\tconst path = [{ field: relation.name }, { index, alias }]\n\t\tconst innerResult = await innerProcessor(context)\n\t\tif (typeof innerResult === 'function') {\n\t\t\treturn async (it: Args) => prependPath(path, await innerResult(it))\n\t\t}\n\t\treturn prependPath(path, innerResult)\n\t}\n}\n\nexport const relationFieldProcessor = <Context extends { relation: Model.AnyRelation }, Args>(\n\tinnerProcessor: (context: Context) => Promise<MutationResultList | ((args: Args) => Promise<MutationResultList>)>,\n) => {\n\treturn async (context: Context): Promise<MutationResultList | ((args: Args) => Promise<MutationResultList>)> => {\n\t\tconst { relation } = context\n\t\tconst path = [{ field: relation.name }]\n\t\tconst innerResult = await innerProcessor(context)\n\t\tif (typeof innerResult === 'function') {\n\t\t\treturn async (it: Args) => prependPath(path, await innerResult(it))\n\t\t}\n\t\treturn prependPath(path, innerResult)\n\t}\n}\n\nexport const hasOneProcessor = <Context extends { relation: Model.AnyRelation }, Args>(\n\tinnerProcessor: (context: Context) => Promise<MutationResultList | ((args: Args) => Promise<MutationResultList>)>,\n) => {\n\treturn async (context: Context): Promise<MutationResultList | ((args: Args) => Promise<MutationResultList>)> => {\n\t\tconst { relation } = context\n\t\tconst path = [{ field: relation.name }]\n\t\tconst innerResult = await innerProcessor(context)\n\t\tif (typeof innerResult === 'function') {\n\t\t\treturn async (it: Args) => prependPath(path, await innerResult(it))\n\t\t}\n\t\treturn prependPath(path, innerResult)\n\t}\n}\n"],"names":["prependPath"],"mappings":";;;AAGO,MAAM,mBAAmB,CAC/B,mBACI;AACJ,SAAO,OAAO,YAAkG;AAC/G,UAAM,EAAE,UAAU,OAAO,MAAA,IAAU;AACnC,UAAM,OAAO,CAAC,EAAE,OAAO,SAAS,QAAQ,EAAE,OAAO,OAAO;AACxD,UAAM,cAAc,MAAM,eAAe,OAAO;AAChD,QAAI,OAAO,gBAAgB,YAAY;AACtC,aAAO,OAAO,OAAaA,OAAAA,YAAY,MAAM,MAAM,YAAY,EAAE,CAAC;AAAA,IACnE;AACA,WAAOA,OAAAA,YAAY,MAAM,WAAW;AAAA,EACrC;AACD;AAEO,MAAM,yBAAyB,CACrC,mBACI;AACJ,SAAO,OAAO,YAAkG;AAC/G,UAAM,EAAE,aAAa;AACrB,UAAM,OAAO,CAAC,EAAE,OAAO,SAAS,MAAM;AACtC,UAAM,cAAc,MAAM,eAAe,OAAO;AAChD,QAAI,OAAO,gBAAgB,YAAY;AACtC,aAAO,OAAO,OAAaA,OAAAA,YAAY,MAAM,MAAM,YAAY,EAAE,CAAC;AAAA,IACnE;AACA,WAAOA,OAAAA,YAAY,MAAM,WAAW;AAAA,EACrC;AACD;AAEO,MAAM,kBAAkB,CAC9B,mBACI;AACJ,SAAO,OAAO,YAAkG;AAC/G,UAAM,EAAE,aAAa;AACrB,UAAM,OAAO,CAAC,EAAE,OAAO,SAAS,MAAM;AACtC,UAAM,cAAc,MAAM,eAAe,OAAO;AAChD,QAAI,OAAO,gBAAgB,YAAY;AACtC,aAAO,OAAO,OAAaA,OAAAA,YAAY,MAAM,MAAM,YAAY,EAAE,CAAC;AAAA,IACnE;AACA,WAAOA,OAAAA,YAAY,MAAM,WAAW;AAAA,EACrC;AACD;;;;"}
@@ -10,6 +10,17 @@ const hasManyProcessor = (innerProcessor) => {
10
10
  return prependPath(path, innerResult);
11
11
  };
12
12
  };
13
+ const relationFieldProcessor = (innerProcessor) => {
14
+ return async (context) => {
15
+ const { relation } = context;
16
+ const path = [{ field: relation.name }];
17
+ const innerResult = await innerProcessor(context);
18
+ if (typeof innerResult === "function") {
19
+ return async (it) => prependPath(path, await innerResult(it));
20
+ }
21
+ return prependPath(path, innerResult);
22
+ };
23
+ };
13
24
  const hasOneProcessor = (innerProcessor) => {
14
25
  return async (context) => {
15
26
  const { relation } = context;
@@ -23,6 +34,7 @@ const hasOneProcessor = (innerProcessor) => {
23
34
  };
24
35
  export {
25
36
  hasManyProcessor,
26
- hasOneProcessor
37
+ hasOneProcessor,
38
+ relationFieldProcessor
27
39
  };
28
40
  //# sourceMappingURL=MutationProcessorHelper.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"MutationProcessorHelper.js","sources":["../../../../../packages/engine-content-api/src/mapper/MutationProcessorHelper.ts"],"sourcesContent":["import { MutationResultList, prependPath } from './Result.js'\nimport { Model } from '@contember/schema'\n\nexport const hasManyProcessor = <Context extends { relation: Model.AnyRelation; index: number; alias?: string }, Args>(\n\tinnerProcessor: (context: Context) => Promise<MutationResultList | ((args: Args) => Promise<MutationResultList>)>,\n) => {\n\treturn async (context: Context): Promise<MutationResultList | ((args: Args) => Promise<MutationResultList>)> => {\n\t\tconst { relation, index, alias } = context\n\t\tconst path = [{ field: relation.name }, { index, alias }]\n\t\tconst innerResult = await innerProcessor(context)\n\t\tif (typeof innerResult === 'function') {\n\t\t\treturn async (it: Args) => prependPath(path, await innerResult(it))\n\t\t}\n\t\treturn prependPath(path, innerResult)\n\t}\n}\n\nexport const hasOneProcessor = <Context extends { relation: Model.AnyRelation }, Args>(\n\tinnerProcessor: (context: Context) => Promise<MutationResultList | ((args: Args) => Promise<MutationResultList>)>,\n) => {\n\treturn async (context: Context): Promise<MutationResultList | ((args: Args) => Promise<MutationResultList>)> => {\n\t\tconst { relation } = context\n\t\tconst path = [{ field: relation.name }]\n\t\tconst innerResult = await innerProcessor(context)\n\t\tif (typeof innerResult === 'function') {\n\t\t\treturn async (it: Args) => prependPath(path, await innerResult(it))\n\t\t}\n\t\treturn prependPath(path, innerResult)\n\t}\n}\n"],"names":[],"mappings":";AAGO,MAAM,mBAAmB,CAC/B,mBACI;AACJ,SAAO,OAAO,YAAkG;AAC/G,UAAM,EAAE,UAAU,OAAO,MAAA,IAAU;AACnC,UAAM,OAAO,CAAC,EAAE,OAAO,SAAS,QAAQ,EAAE,OAAO,OAAO;AACxD,UAAM,cAAc,MAAM,eAAe,OAAO;AAChD,QAAI,OAAO,gBAAgB,YAAY;AACtC,aAAO,OAAO,OAAa,YAAY,MAAM,MAAM,YAAY,EAAE,CAAC;AAAA,IACnE;AACA,WAAO,YAAY,MAAM,WAAW;AAAA,EACrC;AACD;AAEO,MAAM,kBAAkB,CAC9B,mBACI;AACJ,SAAO,OAAO,YAAkG;AAC/G,UAAM,EAAE,aAAa;AACrB,UAAM,OAAO,CAAC,EAAE,OAAO,SAAS,MAAM;AACtC,UAAM,cAAc,MAAM,eAAe,OAAO;AAChD,QAAI,OAAO,gBAAgB,YAAY;AACtC,aAAO,OAAO,OAAa,YAAY,MAAM,MAAM,YAAY,EAAE,CAAC;AAAA,IACnE;AACA,WAAO,YAAY,MAAM,WAAW;AAAA,EACrC;AACD;"}
1
+ {"version":3,"file":"MutationProcessorHelper.js","sources":["../../../../../packages/engine-content-api/src/mapper/MutationProcessorHelper.ts"],"sourcesContent":["import { MutationResultList, prependPath } from './Result.js'\nimport { Model } from '@contember/schema'\n\nexport const hasManyProcessor = <Context extends { relation: Model.AnyRelation; index: number; alias?: string }, Args>(\n\tinnerProcessor: (context: Context) => Promise<MutationResultList | ((args: Args) => Promise<MutationResultList>)>,\n) => {\n\treturn async (context: Context): Promise<MutationResultList | ((args: Args) => Promise<MutationResultList>)> => {\n\t\tconst { relation, index, alias } = context\n\t\tconst path = [{ field: relation.name }, { index, alias }]\n\t\tconst innerResult = await innerProcessor(context)\n\t\tif (typeof innerResult === 'function') {\n\t\t\treturn async (it: Args) => prependPath(path, await innerResult(it))\n\t\t}\n\t\treturn prependPath(path, innerResult)\n\t}\n}\n\nexport const relationFieldProcessor = <Context extends { relation: Model.AnyRelation }, Args>(\n\tinnerProcessor: (context: Context) => Promise<MutationResultList | ((args: Args) => Promise<MutationResultList>)>,\n) => {\n\treturn async (context: Context): Promise<MutationResultList | ((args: Args) => Promise<MutationResultList>)> => {\n\t\tconst { relation } = context\n\t\tconst path = [{ field: relation.name }]\n\t\tconst innerResult = await innerProcessor(context)\n\t\tif (typeof innerResult === 'function') {\n\t\t\treturn async (it: Args) => prependPath(path, await innerResult(it))\n\t\t}\n\t\treturn prependPath(path, innerResult)\n\t}\n}\n\nexport const hasOneProcessor = <Context extends { relation: Model.AnyRelation }, Args>(\n\tinnerProcessor: (context: Context) => Promise<MutationResultList | ((args: Args) => Promise<MutationResultList>)>,\n) => {\n\treturn async (context: Context): Promise<MutationResultList | ((args: Args) => Promise<MutationResultList>)> => {\n\t\tconst { relation } = context\n\t\tconst path = [{ field: relation.name }]\n\t\tconst innerResult = await innerProcessor(context)\n\t\tif (typeof innerResult === 'function') {\n\t\t\treturn async (it: Args) => prependPath(path, await innerResult(it))\n\t\t}\n\t\treturn prependPath(path, innerResult)\n\t}\n}\n"],"names":[],"mappings":";AAGO,MAAM,mBAAmB,CAC/B,mBACI;AACJ,SAAO,OAAO,YAAkG;AAC/G,UAAM,EAAE,UAAU,OAAO,MAAA,IAAU;AACnC,UAAM,OAAO,CAAC,EAAE,OAAO,SAAS,QAAQ,EAAE,OAAO,OAAO;AACxD,UAAM,cAAc,MAAM,eAAe,OAAO;AAChD,QAAI,OAAO,gBAAgB,YAAY;AACtC,aAAO,OAAO,OAAa,YAAY,MAAM,MAAM,YAAY,EAAE,CAAC;AAAA,IACnE;AACA,WAAO,YAAY,MAAM,WAAW;AAAA,EACrC;AACD;AAEO,MAAM,yBAAyB,CACrC,mBACI;AACJ,SAAO,OAAO,YAAkG;AAC/G,UAAM,EAAE,aAAa;AACrB,UAAM,OAAO,CAAC,EAAE,OAAO,SAAS,MAAM;AACtC,UAAM,cAAc,MAAM,eAAe,OAAO;AAChD,QAAI,OAAO,gBAAgB,YAAY;AACtC,aAAO,OAAO,OAAa,YAAY,MAAM,MAAM,YAAY,EAAE,CAAC;AAAA,IACnE;AACA,WAAO,YAAY,MAAM,WAAW;AAAA,EACrC;AACD;AAEO,MAAM,kBAAkB,CAC9B,mBACI;AACJ,SAAO,OAAO,YAAkG;AAC/G,UAAM,EAAE,aAAa;AACrB,UAAM,OAAO,CAAC,EAAE,OAAO,SAAS,MAAM;AACtC,UAAM,cAAc,MAAM,eAAe,OAAO;AAChD,QAAI,OAAO,gBAAgB,YAAY;AACtC,aAAO,OAAO,OAAa,YAAY,MAAM,MAAM,YAAY,EAAE,CAAC;AAAA,IACnE;AACA,WAAO,YAAY,MAAM,WAAW;AAAA,EACrC;AACD;"}
@@ -170,6 +170,7 @@ var ConstraintType = /* @__PURE__ */ ((ConstraintType2) => {
170
170
  ConstraintType2["notNull"] = "notNull";
171
171
  ConstraintType2["uniqueKey"] = "uniqueKey";
172
172
  ConstraintType2["foreignKey"] = "foreignKey";
173
+ ConstraintType2["check"] = "check";
173
174
  return ConstraintType2;
174
175
  })(ConstraintType || {});
175
176
  class MutationConstraintViolationError {
@@ -1 +1 @@
1
- {"version":3,"file":"Result.cjs","sources":["../../../../../packages/engine-content-api/src/mapper/Result.ts"],"sourcesContent":["import { Input, Model, Value } from '@contember/schema'\nimport { MapperInput } from './types.js'\n\nexport enum MutationResultType {\n\tok = 'ok',\n\tnothingToDo = 'nothingToDo',\n\tnotFoundError = 'notFoundError',\n\tconstraintViolationError = 'constraintViolationError',\n\tnoResultError = 'noResultError',\n\tvalidationError = 'validationError',\n\tinputError = 'inputError',\n\tsqlError = 'sqlError',\n}\n\nexport enum MutationResultHint {\n\tsqlError = 'sqlError',\n\tsubSequentSqlError = 'subsequentSqlError',\n}\n\nexport enum ModificationType {\n\tcreate = 'create',\n\tupdate = 'update',\n\tdelete = 'delete',\n\tjunctionUpdate = 'junctionUpdate',\n}\n\nexport type MutationResult =\n\t| MutationUpdateOk\n\t| MutationCreateOk\n\t| MutationDeleteOk\n\t| MutationJunctionUpdateOk\n\t| MutationEntryNotFoundError\n\t| MutationNothingToDo\n\t| MutationConstraintViolationError\n\t| MutationNoResultError\n\t| MutationInputError\n\t| MutationSqlError\n\nexport type MutationResultList = MutationResult[]\n\ntype Path = ({ field: string } | { index: number; alias?: string })[]\n\ninterface MutationResultInterface {\n\terror: boolean\n\tresult: MutationResultType\n\tpaths: Path[]\n\tmessage?: string\n\thints: MutationResultHint[]\n}\n\nexport type RowValues = { [fieldName: string]: Value.FieldValue }\n\nexport class MutationUpdateOk implements MutationResultInterface {\n\terror = false\n\tresult = MutationResultType.ok as const\n\ttype = ModificationType.update as const\n\thints: MutationResultHint[] = []\n\n\tconstructor(\n\t\tpublic readonly paths: Path[],\n\t\tpublic readonly entity: Model.Entity,\n\t\tpublic readonly primary: Value.PrimaryValue,\n\t\tpublic readonly input: MapperInput.UpdateDataInput,\n\t\tpublic readonly values: RowValues,\n\t\tpublic readonly oldValues?: RowValues,\n\t) {}\n}\n\nexport class MutationCreateOk implements MutationResultInterface {\n\terror = false\n\tresult = MutationResultType.ok as const\n\ttype = ModificationType.create as const\n\thints: MutationResultHint[] = []\n\n\tconstructor(\n\t\tpublic readonly paths: Path[],\n\t\tpublic readonly entity: Model.Entity,\n\t\tpublic readonly primary: Value.PrimaryValue,\n\t\tpublic readonly input: MapperInput.CreateDataInput,\n\t\tpublic readonly values: RowValues,\n\t) {}\n}\n\nexport class MutationDeleteOk implements MutationResultInterface {\n\terror = false\n\tresult = MutationResultType.ok as const\n\ttype = ModificationType.delete as const\n\thints: MutationResultHint[] = []\n\n\tconstructor(\n\t\tpublic readonly paths: Path[],\n\t\tpublic readonly entity: Model.Entity,\n\t\tpublic readonly primary: Value.PrimaryValue,\n\t) {}\n}\n\nexport class MutationJunctionUpdateOk implements MutationResultInterface {\n\terror = false\n\tresult = MutationResultType.ok as const\n\ttype = ModificationType.junctionUpdate as const\n\thints: MutationResultHint[] = []\n\n\tconstructor(\n\t\tpublic readonly paths: Path[],\n\t\tpublic readonly entity: Model.Entity,\n\t\tpublic readonly relation: Model.ManyHasManyOwningRelation,\n\t\tpublic readonly owningUnique: Input.PrimaryValue,\n\t\tpublic readonly inverseUnique: Input.PrimaryValue,\n\t) {}\n}\n\nexport enum NothingToDoReason {\n\tnoData = 'noData',\n\temptyRelation = 'emptyRelation',\n\talreadyExists = 'alreadyExists',\n\taborted = 'aborted',\n\talreadyDeleted = 'alreadyDeleted',\n}\n\nexport class MutationNothingToDo implements MutationResultInterface {\n\terror = false\n\tresult = MutationResultType.nothingToDo as const\n\thints: MutationResultHint[] = []\n\n\tconstructor(public readonly paths: Path[], public readonly reason: NothingToDoReason) {}\n}\n\nexport enum InputErrorKind {\n\tnonUniqueWhere = 'nonUniqueWhere',\n\tinvalidData = 'invalidData',\n}\n\nexport class MutationInputError implements MutationResultInterface {\n\terror = true\n\tresult = MutationResultType.inputError as const\n\n\tconstructor(\n\t\tpublic readonly paths: Path[],\n\t\tpublic readonly kind: InputErrorKind,\n\t\tpublic readonly message?: string,\n\t\tpublic readonly hints: MutationResultHint[] = [],\n\t) {}\n}\n\nexport class MutationSqlError implements MutationResultInterface {\n\terror = true\n\tresult = MutationResultType.sqlError as const\n\n\tconstructor(\n\t\tpublic readonly paths: Path[],\n\t\tpublic readonly message?: string,\n\t\tpublic readonly hints: MutationResultHint[] = [],\n\t) {}\n}\n\nexport enum ConstraintType {\n\tnotNull = 'notNull',\n\tuniqueKey = 'uniqueKey',\n\tforeignKey = 'foreignKey',\n}\n\nexport class MutationConstraintViolationError implements MutationResultInterface {\n\terror = true\n\tresult = MutationResultType.constraintViolationError as const\n\n\tconstructor(\n\t\tpublic readonly paths: Path[],\n\t\tpublic readonly constraint: ConstraintType,\n\t\tpublic readonly message?: string,\n\t\tpublic readonly hints: MutationResultHint[] = [],\n\t) {}\n}\n\n// maybe denied by acl\nexport class MutationEntryNotFoundError implements MutationResultInterface {\n\terror = true\n\tresult = MutationResultType.notFoundError as const\n\thints: MutationResultHint[] = []\n\tmessage: string\n\n\tconstructor(public readonly paths: Path[], public readonly where: Input.UniqueWhere | Input.OptionalWhere) {\n\t\tthis.message = 'for input ' + JSON.stringify(where)\n\t}\n}\n\n// possibly denied by acl\nexport class MutationNoResultError implements MutationResultInterface {\n\terror = true\n\tresult = MutationResultType.noResultError as const\n\n\tconstructor(\n\t\tpublic readonly paths: Path[],\n\t\tpublic readonly message?: string,\n\t\tpublic readonly hints: MutationResultHint[] = [],\n\t) {}\n}\n\nexport const prependPath = (path: Path, results: MutationResultList): MutationResultList =>\n\tresults.map(it => ({\n\t\t...it,\n\t\tpaths: (it.paths.length === 0 ? [[]] : it.paths).map(it => [...path, ...it]),\n\t}))\n\nexport const getInsertPrimary = (result: MutationResultList) =>\n\t!result.some(it => it.error) && result[0] && result[0].result === MutationResultType.ok && result[0].type === ModificationType.create\n\t\t? result[0].primary\n\t\t: undefined\n"],"names":["MutationResultType","MutationResultHint","NothingToDoReason","InputErrorKind","ConstraintType","it"],"mappings":";;;;;AAGO,IAAK,uCAAAA,wBAAL;AACNA,sBAAA,IAAA,IAAK;AACLA,sBAAA,aAAA,IAAc;AACdA,sBAAA,eAAA,IAAgB;AAChBA,sBAAA,0BAAA,IAA2B;AAC3BA,sBAAA,eAAA,IAAgB;AAChBA,sBAAA,iBAAA,IAAkB;AAClBA,sBAAA,YAAA,IAAa;AACbA,sBAAA,UAAA,IAAW;AARA,SAAAA;AAAA,GAAA,sBAAA,CAAA,CAAA;AAWL,IAAK,uCAAAC,wBAAL;AACNA,sBAAA,UAAA,IAAW;AACXA,sBAAA,oBAAA,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AA,OAAM,GAAG,KAAK,KAAK,OAAO,CAAC,KAAK,OAAO,CAAC,EAAE,WAAW,QAAyB,OAAO,CAAC,EAAE,SAAS,WAC3G,OAAO,CAAC,EAAE,UACV;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"Result.cjs","sources":["../../../../../packages/engine-content-api/src/mapper/Result.ts"],"sourcesContent":["import { Input, Model, Value } from '@contember/schema'\nimport { MapperInput } from './types.js'\n\nexport enum MutationResultType {\n\tok = 'ok',\n\tnothingToDo = 'nothingToDo',\n\tnotFoundError = 'notFoundError',\n\tconstraintViolationError = 'constraintViolationError',\n\tnoResultError = 'noResultError',\n\tvalidationError = 'validationError',\n\tinputError = 'inputError',\n\tsqlError = 'sqlError',\n}\n\nexport enum MutationResultHint {\n\tsqlError = 'sqlError',\n\tsubSequentSqlError = 'subsequentSqlError',\n}\n\nexport enum ModificationType {\n\tcreate = 'create',\n\tupdate = 'update',\n\tdelete = 'delete',\n\tjunctionUpdate = 'junctionUpdate',\n}\n\nexport type MutationResult =\n\t| MutationUpdateOk\n\t| MutationCreateOk\n\t| MutationDeleteOk\n\t| MutationJunctionUpdateOk\n\t| MutationEntryNotFoundError\n\t| MutationNothingToDo\n\t| MutationConstraintViolationError\n\t| MutationNoResultError\n\t| MutationInputError\n\t| MutationSqlError\n\nexport type MutationResultList = MutationResult[]\n\ntype Path = ({ field: string } | { index: number; alias?: string })[]\n\ninterface MutationResultInterface {\n\terror: boolean\n\tresult: MutationResultType\n\tpaths: Path[]\n\tmessage?: string\n\thints: MutationResultHint[]\n}\n\nexport type RowValues = { [fieldName: string]: Value.FieldValue }\n\nexport class MutationUpdateOk implements MutationResultInterface {\n\terror = false\n\tresult = MutationResultType.ok as const\n\ttype = ModificationType.update as const\n\thints: MutationResultHint[] = []\n\n\tconstructor(\n\t\tpublic readonly paths: Path[],\n\t\tpublic readonly entity: Model.Entity,\n\t\tpublic readonly primary: Value.PrimaryValue,\n\t\tpublic readonly input: MapperInput.UpdateDataInput,\n\t\tpublic readonly values: RowValues,\n\t\tpublic readonly oldValues?: RowValues,\n\t) {}\n}\n\nexport class MutationCreateOk implements MutationResultInterface {\n\terror = false\n\tresult = MutationResultType.ok as const\n\ttype = ModificationType.create as const\n\thints: MutationResultHint[] = []\n\n\tconstructor(\n\t\tpublic readonly paths: Path[],\n\t\tpublic readonly entity: Model.Entity,\n\t\tpublic readonly primary: Value.PrimaryValue,\n\t\tpublic readonly input: MapperInput.CreateDataInput,\n\t\tpublic readonly values: RowValues,\n\t) {}\n}\n\nexport class MutationDeleteOk implements MutationResultInterface {\n\terror = false\n\tresult = MutationResultType.ok as const\n\ttype = ModificationType.delete as const\n\thints: MutationResultHint[] = []\n\n\tconstructor(\n\t\tpublic readonly paths: Path[],\n\t\tpublic readonly entity: Model.Entity,\n\t\tpublic readonly primary: Value.PrimaryValue,\n\t) {}\n}\n\nexport class MutationJunctionUpdateOk implements MutationResultInterface {\n\terror = false\n\tresult = MutationResultType.ok as const\n\ttype = ModificationType.junctionUpdate as const\n\thints: MutationResultHint[] = []\n\n\tconstructor(\n\t\tpublic readonly paths: Path[],\n\t\tpublic readonly entity: Model.Entity,\n\t\tpublic readonly relation: Model.ManyHasManyOwningRelation,\n\t\tpublic readonly owningUnique: Input.PrimaryValue,\n\t\tpublic readonly inverseUnique: Input.PrimaryValue,\n\t) {}\n}\n\nexport enum NothingToDoReason {\n\tnoData = 'noData',\n\temptyRelation = 'emptyRelation',\n\talreadyExists = 'alreadyExists',\n\taborted = 'aborted',\n\talreadyDeleted = 'alreadyDeleted',\n}\n\nexport class MutationNothingToDo implements MutationResultInterface {\n\terror = false\n\tresult = MutationResultType.nothingToDo as const\n\thints: MutationResultHint[] = []\n\n\tconstructor(public readonly paths: Path[], public readonly reason: NothingToDoReason) {}\n}\n\nexport enum InputErrorKind {\n\tnonUniqueWhere = 'nonUniqueWhere',\n\tinvalidData = 'invalidData',\n}\n\nexport class MutationInputError implements MutationResultInterface {\n\terror = true\n\tresult = MutationResultType.inputError as const\n\n\tconstructor(\n\t\tpublic readonly paths: Path[],\n\t\tpublic readonly kind: InputErrorKind,\n\t\tpublic readonly message?: string,\n\t\tpublic readonly hints: MutationResultHint[] = [],\n\t) {}\n}\n\nexport class MutationSqlError implements MutationResultInterface {\n\terror = true\n\tresult = MutationResultType.sqlError as const\n\n\tconstructor(\n\t\tpublic readonly paths: Path[],\n\t\tpublic readonly message?: string,\n\t\tpublic readonly hints: MutationResultHint[] = [],\n\t) {}\n}\n\nexport enum ConstraintType {\n\tnotNull = 'notNull',\n\tuniqueKey = 'uniqueKey',\n\tforeignKey = 'foreignKey',\n\tcheck = 'check',\n}\n\nexport class MutationConstraintViolationError implements MutationResultInterface {\n\terror = true\n\tresult = MutationResultType.constraintViolationError as const\n\n\tconstructor(\n\t\tpublic readonly paths: Path[],\n\t\tpublic readonly constraint: ConstraintType,\n\t\tpublic readonly message?: string,\n\t\tpublic readonly hints: MutationResultHint[] = [],\n\t) {}\n}\n\n// maybe denied by acl\nexport class MutationEntryNotFoundError implements MutationResultInterface {\n\terror = true\n\tresult = MutationResultType.notFoundError as const\n\thints: MutationResultHint[] = []\n\tmessage: string\n\n\tconstructor(public readonly paths: Path[], public readonly where: Input.UniqueWhere | Input.OptionalWhere) {\n\t\tthis.message = 'for input ' + JSON.stringify(where)\n\t}\n}\n\n// possibly denied by acl\nexport class MutationNoResultError implements MutationResultInterface {\n\terror = true\n\tresult = MutationResultType.noResultError as const\n\n\tconstructor(\n\t\tpublic readonly paths: Path[],\n\t\tpublic readonly message?: string,\n\t\tpublic readonly hints: MutationResultHint[] = [],\n\t) {}\n}\n\nexport const prependPath = (path: Path, results: MutationResultList): MutationResultList =>\n\tresults.map(it => ({\n\t\t...it,\n\t\tpaths: (it.paths.length === 0 ? [[]] : it.paths).map(it => [...path, ...it]),\n\t}))\n\nexport const getInsertPrimary = (result: MutationResultList) =>\n\t!result.some(it => it.error) && result[0] && result[0].result === MutationResultType.ok && result[0].type === ModificationType.create\n\t\t? result[0].primary\n\t\t: undefined\n"],"names":["MutationResultType","MutationResultHint","NothingToDoReason","InputErrorKind","ConstraintType","it"],"mappings":";;;;;AAGO,IAAK,uCAAAA,wBAAL;AACNA,sBAAA,IAAA,IAAK;AACLA,sBAAA,aAAA,IAAc;AACdA,sBAAA,eAAA,IAAgB;AAChBA,sBAAA,0BAAA,IAA2B;AAC3BA,sBAAA,eAAA,IAAgB;AAChBA,sBAAA,iBAAA,IAAkB;AAClBA,sBAAA,YAAA,IAAa;AACbA,sBAAA,UAAA,IAAW;AARA,SAAAA;AAAA,GAAA,sBAAA,CAAA,CAAA;AAWL,IAAK,uCAAAC,wBAAL;AACNA,sBAAA,UAAA,IAAW;AACXA,sBAAA,oBAAA,IAAqB;AAFV,SAAAA;AAAA,GAAA,sBAAA,CAAA,CAAA;AAsCL,MAAM,iBAAoD;AAAA,EAMhE,YACiB,OACA,QACA,SACA,OACA,QACA,WACf;AANe,SAAA,QAAA;AACA,SAAA,SAAA;AACA,SAAA,UAAA;AACA,SAAA,QAAA;AACA,SAAA,SAAA;AACA,SAAA,YAAA;AAXjB,kBAAA,MAAA,SAAQ,KAAA;AACR;AAAA,MAAA;AAAA,MAAA;AAAA,MAAS;AAAA;AAAA,IAAA;AACT;AAAA,MAAA;AAAA,MAAA;AAAA,MAAO;AAAA;AAAA,IAAA;AACP,kBAAA,MAAA,SAA8B,EAAC;AAAA,EAS5B;AACJ;AAEO,MAAM,iBAAoD;AAAA,EAMhE,YACiB,OACA,QACA,SACA,OACA,QACf;AALe,SAAA,QAAA;AACA,SAAA,SAAA;AACA,SAAA,UAAA;AACA,SAAA,QAAA;AACA,SAAA,SAAA;AAVjB,kBAAA,MAAA,SAAQ,KAAA;AACR;AAAA,MAAA;AAAA,MAAA;AAAA,MAAS;AAAA;AAAA,IAAA;AACT;AAAA,MAAA;AAAA,MAAA;AAAA,MAAO;AAAA;AAAA,IAAA;AACP,kBAAA,MAAA,SAA8B,EAAC;AAAA,EAQ5B;AACJ;AAEO,M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IrE,YACiB,OACA,SACA,QAA8B,CAAA,GAC7C;AAHe,SAAA,QAAA;AACA,SAAA,UAAA;AACA,SAAA,QAAA;AANjB,kBAAA,MAAA,SAAQ,IAAA;AACR;AAAA,MAAA;AAAA,MAAA;AAAA,MAAS;AAAA;AAAA,IAAA;AAAA,EAMN;AACJ;AAEO,MAAM,cAAc,CAAC,MAAY,YACvC,QAAQ,IAAI,CAAA,QAAO;AAAA,EAClB,GAAG;AAAA,EACH,QAAQ,GAAG,MAAM,WAAW,IAAI,CAAC,EAAE,IAAI,GAAG,OAAO,IAAI,CAAAC,QAAM,CAAC,GAAG,MAAM,GAAGA,GAAE,CAAC;AAC5E,EAAE;AAEI,MAAM,mBAAmB,CAAC,WAChC,CAAC,OAAO,KAAK,CAAA,OAAM,GAAG,KAAK,KAAK,OAAO,CAAC,KAAK,OAAO,CAAC,EAAE,WAAW,QAAyB,OAAO,CAAC,EAAE,SAAS,WAC3G,OAAO,CAAC,EAAE,UACV;;;;;;;;;;;;;;;;;;"}
@@ -168,6 +168,7 @@ var ConstraintType = /* @__PURE__ */ ((ConstraintType2) => {
168
168
  ConstraintType2["notNull"] = "notNull";
169
169
  ConstraintType2["uniqueKey"] = "uniqueKey";
170
170
  ConstraintType2["foreignKey"] = "foreignKey";
171
+ ConstraintType2["check"] = "check";
171
172
  return ConstraintType2;
172
173
  })(ConstraintType || {});
173
174
  class MutationConstraintViolationError {