@payloadcms/drizzle 4.0.0-internal.e7d4ebc → 4.0.0-internal.ea6e8f8

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 (280) hide show
  1. package/dist/count.d.ts.map +1 -1
  2. package/dist/count.js +25 -3
  3. package/dist/count.js.map +1 -1
  4. package/dist/countVersions.d.ts.map +1 -1
  5. package/dist/countVersions.js +28 -4
  6. package/dist/countVersions.js.map +1 -1
  7. package/dist/createGlobalVersion.d.ts.map +1 -1
  8. package/dist/createGlobalVersion.js +15 -2
  9. package/dist/createGlobalVersion.js.map +1 -1
  10. package/dist/createTableName.d.ts.map +1 -1
  11. package/dist/createTableName.js +2 -7
  12. package/dist/createTableName.js.map +1 -1
  13. package/dist/createVersion.d.ts.map +1 -1
  14. package/dist/createVersion.js +12 -1
  15. package/dist/createVersion.js.map +1 -1
  16. package/dist/deleteBranchGlobal.d.ts +10 -0
  17. package/dist/deleteBranchGlobal.d.ts.map +1 -0
  18. package/dist/deleteBranchGlobal.js +27 -0
  19. package/dist/deleteBranchGlobal.js.map +1 -0
  20. package/dist/deleteOne.d.ts.map +1 -1
  21. package/dist/deleteOne.js +18 -1
  22. package/dist/deleteOne.js.map +1 -1
  23. package/dist/exports/postgres.d.ts +3 -0
  24. package/dist/exports/postgres.d.ts.map +1 -1
  25. package/dist/exports/postgres.js +3 -0
  26. package/dist/exports/postgres.js.map +1 -1
  27. package/dist/exports/sqlite.d.ts +1 -0
  28. package/dist/exports/sqlite.d.ts.map +1 -1
  29. package/dist/exports/sqlite.js +1 -0
  30. package/dist/exports/sqlite.js.map +1 -1
  31. package/dist/find/buildFindManyArgs.d.ts +3 -2
  32. package/dist/find/buildFindManyArgs.d.ts.map +1 -1
  33. package/dist/find/buildFindManyArgs.js +2 -1
  34. package/dist/find/buildFindManyArgs.js.map +1 -1
  35. package/dist/find/buildPolymorphicJoinQuery.d.ts +39 -0
  36. package/dist/find/buildPolymorphicJoinQuery.d.ts.map +1 -0
  37. package/dist/find/buildPolymorphicJoinQuery.js +152 -0
  38. package/dist/find/buildPolymorphicJoinQuery.js.map +1 -0
  39. package/dist/find/buildPolymorphicJoinWhere.d.ts +20 -0
  40. package/dist/find/buildPolymorphicJoinWhere.d.ts.map +1 -0
  41. package/dist/find/buildPolymorphicJoinWhere.js +301 -0
  42. package/dist/find/buildPolymorphicJoinWhere.js.map +1 -0
  43. package/dist/find/createPolymorphicJoinWherePlan.d.ts +37 -0
  44. package/dist/find/createPolymorphicJoinWherePlan.d.ts.map +1 -0
  45. package/dist/find/createPolymorphicJoinWherePlan.js +191 -0
  46. package/dist/find/createPolymorphicJoinWherePlan.js.map +1 -0
  47. package/dist/find/findMany.d.ts +6 -1
  48. package/dist/find/findMany.d.ts.map +1 -1
  49. package/dist/find/findMany.js +16 -3
  50. package/dist/find/findMany.js.map +1 -1
  51. package/dist/find/traverseFields.d.ts +3 -2
  52. package/dist/find/traverseFields.d.ts.map +1 -1
  53. package/dist/find/traverseFields.js +72 -197
  54. package/dist/find/traverseFields.js.map +1 -1
  55. package/dist/find.d.ts.map +1 -1
  56. package/dist/find.js +32 -4
  57. package/dist/find.js.map +1 -1
  58. package/dist/findDistinct.d.ts.map +1 -1
  59. package/dist/findDistinct.js +107 -8
  60. package/dist/findDistinct.js.map +1 -1
  61. package/dist/findGlobal.d.ts.map +1 -1
  62. package/dist/findGlobal.js +22 -5
  63. package/dist/findGlobal.js.map +1 -1
  64. package/dist/findGlobalVersions.js +8 -3
  65. package/dist/findGlobalVersions.js.map +1 -1
  66. package/dist/findOne.d.ts +1 -1
  67. package/dist/findOne.d.ts.map +1 -1
  68. package/dist/findOne.js +30 -3
  69. package/dist/findOne.js.map +1 -1
  70. package/dist/findVersions.d.ts.map +1 -1
  71. package/dist/findVersions.js +32 -5
  72. package/dist/findVersions.js.map +1 -1
  73. package/dist/index.d.ts +6 -2
  74. package/dist/index.d.ts.map +1 -1
  75. package/dist/index.js +4 -0
  76. package/dist/index.js.map +1 -1
  77. package/dist/migrate.d.ts.map +1 -1
  78. package/dist/migrate.js +41 -15
  79. package/dist/migrate.js.map +1 -1
  80. package/dist/migrateDown.d.ts +2 -1
  81. package/dist/migrateDown.d.ts.map +1 -1
  82. package/dist/migrateDown.js +17 -4
  83. package/dist/migrateDown.js.map +1 -1
  84. package/dist/migrateFresh.d.ts +4 -2
  85. package/dist/migrateFresh.d.ts.map +1 -1
  86. package/dist/migrateFresh.js +26 -9
  87. package/dist/migrateFresh.js.map +1 -1
  88. package/dist/migrateRefresh.d.ts +2 -1
  89. package/dist/migrateRefresh.d.ts.map +1 -1
  90. package/dist/migrateRefresh.js +20 -5
  91. package/dist/migrateRefresh.js.map +1 -1
  92. package/dist/migrateReset.d.ts +2 -1
  93. package/dist/migrateReset.d.ts.map +1 -1
  94. package/dist/migrateReset.js +18 -4
  95. package/dist/migrateReset.js.map +1 -1
  96. package/dist/migrateStatus.d.ts +2 -1
  97. package/dist/migrateStatus.d.ts.map +1 -1
  98. package/dist/migrateStatus.js +11 -6
  99. package/dist/migrateStatus.js.map +1 -1
  100. package/dist/postgres/createJSONQuery/index.js +3 -3
  101. package/dist/postgres/createJSONQuery/index.js.map +1 -1
  102. package/dist/postgres/init.d.ts.map +1 -1
  103. package/dist/postgres/init.js +6 -0
  104. package/dist/postgres/init.js.map +1 -1
  105. package/dist/postgres/insert.d.ts.map +1 -1
  106. package/dist/postgres/insert.js +4 -2
  107. package/dist/postgres/insert.js.map +1 -1
  108. package/dist/postgres/predefinedMigrations/sizes-to-variants/index.d.ts +35 -0
  109. package/dist/postgres/predefinedMigrations/sizes-to-variants/index.d.ts.map +1 -0
  110. package/dist/postgres/predefinedMigrations/sizes-to-variants/index.js +185 -0
  111. package/dist/postgres/predefinedMigrations/sizes-to-variants/index.js.map +1 -0
  112. package/dist/postgres/predefinedMigrations/v2-v3/fetchAndResave/index.d.ts.map +1 -1
  113. package/dist/postgres/predefinedMigrations/v2-v3/fetchAndResave/index.js +8 -4
  114. package/dist/postgres/predefinedMigrations/v2-v3/fetchAndResave/index.js.map +1 -1
  115. package/dist/postgres/predefinedMigrations/v2-v3/index.js +1 -1
  116. package/dist/postgres/predefinedMigrations/v2-v3/index.js.map +1 -1
  117. package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.d.ts +15 -0
  118. package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.d.ts.map +1 -0
  119. package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.js +25 -0
  120. package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.js.map +1 -0
  121. package/dist/postgres/query/postgresUnaccent.d.ts +13 -0
  122. package/dist/postgres/query/postgresUnaccent.d.ts.map +1 -0
  123. package/dist/postgres/query/postgresUnaccent.js +40 -0
  124. package/dist/postgres/query/postgresUnaccent.js.map +1 -0
  125. package/dist/postgres/types.d.ts +17 -2
  126. package/dist/postgres/types.d.ts.map +1 -1
  127. package/dist/postgres/types.js.map +1 -1
  128. package/dist/queries/buildAndOrConditions.d.ts +3 -2
  129. package/dist/queries/buildAndOrConditions.d.ts.map +1 -1
  130. package/dist/queries/buildAndOrConditions.js +2 -1
  131. package/dist/queries/buildAndOrConditions.js.map +1 -1
  132. package/dist/queries/buildBranchVisibility.d.ts +11 -0
  133. package/dist/queries/buildBranchVisibility.d.ts.map +1 -0
  134. package/dist/queries/buildBranchVisibility.js +48 -0
  135. package/dist/queries/buildBranchVisibility.js.map +1 -0
  136. package/dist/queries/buildOperatorConstraint.d.ts +22 -0
  137. package/dist/queries/buildOperatorConstraint.d.ts.map +1 -0
  138. package/dist/queries/buildOperatorConstraint.js +63 -0
  139. package/dist/queries/buildOperatorConstraint.js.map +1 -0
  140. package/dist/queries/buildOrderBy.d.ts +3 -2
  141. package/dist/queries/buildOrderBy.d.ts.map +1 -1
  142. package/dist/queries/buildOrderBy.js +2 -1
  143. package/dist/queries/buildOrderBy.js.map +1 -1
  144. package/dist/queries/buildQuery.d.ts +3 -2
  145. package/dist/queries/buildQuery.d.ts.map +1 -1
  146. package/dist/queries/buildQuery.js +4 -2
  147. package/dist/queries/buildQuery.js.map +1 -1
  148. package/dist/queries/getTableColumnFromPath.d.ts +15 -5
  149. package/dist/queries/getTableColumnFromPath.d.ts.map +1 -1
  150. package/dist/queries/getTableColumnFromPath.js +225 -54
  151. package/dist/queries/getTableColumnFromPath.js.map +1 -1
  152. package/dist/queries/operatorMap.d.ts +7 -3
  153. package/dist/queries/operatorMap.d.ts.map +1 -1
  154. package/dist/queries/operatorMap.js.map +1 -1
  155. package/dist/queries/parseParams.d.ts +3 -2
  156. package/dist/queries/parseParams.d.ts.map +1 -1
  157. package/dist/queries/parseParams.js +266 -11
  158. package/dist/queries/parseParams.js.map +1 -1
  159. package/dist/queries/resolveRelationshipPath.d.ts +36 -0
  160. package/dist/queries/resolveRelationshipPath.d.ts.map +1 -0
  161. package/dist/queries/resolveRelationshipPath.js +66 -0
  162. package/dist/queries/resolveRelationshipPath.js.map +1 -0
  163. package/dist/queries/validateOperatorHandlers.d.ts +8 -0
  164. package/dist/queries/validateOperatorHandlers.d.ts.map +1 -0
  165. package/dist/queries/validateOperatorHandlers.js +30 -0
  166. package/dist/queries/validateOperatorHandlers.js.map +1 -0
  167. package/dist/queryDrafts.d.ts.map +1 -1
  168. package/dist/queryDrafts.js +23 -4
  169. package/dist/queryDrafts.js.map +1 -1
  170. package/dist/schema/build.d.ts.map +1 -1
  171. package/dist/schema/build.js +20 -17
  172. package/dist/schema/build.js.map +1 -1
  173. package/dist/schema/traverseFields.js +5 -5
  174. package/dist/schema/traverseFields.js.map +1 -1
  175. package/dist/sqlite/createJSONQuery/convertPathToJSONTraversal.js +3 -2
  176. package/dist/sqlite/createJSONQuery/convertPathToJSONTraversal.js.map +1 -1
  177. package/dist/sqlite/createJSONQuery/index.d.ts.map +1 -1
  178. package/dist/sqlite/createJSONQuery/index.js +6 -5
  179. package/dist/sqlite/createJSONQuery/index.js.map +1 -1
  180. package/dist/sqlite/insert.d.ts.map +1 -1
  181. package/dist/sqlite/insert.js +9 -4
  182. package/dist/sqlite/insert.js.map +1 -1
  183. package/dist/sqlite/predefinedMigrations/sizes-to-variants/index.d.ts +15 -0
  184. package/dist/sqlite/predefinedMigrations/sizes-to-variants/index.d.ts.map +1 -0
  185. package/dist/sqlite/predefinedMigrations/sizes-to-variants/index.js +114 -0
  186. package/dist/sqlite/predefinedMigrations/sizes-to-variants/index.js.map +1 -0
  187. package/dist/sqlite/types.d.ts +4 -0
  188. package/dist/sqlite/types.d.ts.map +1 -1
  189. package/dist/sqlite/types.js.map +1 -1
  190. package/dist/transactions/beginTransaction.d.ts.map +1 -1
  191. package/dist/transactions/beginTransaction.js +13 -5
  192. package/dist/transactions/beginTransaction.js.map +1 -1
  193. package/dist/transactions/commitTransaction.d.ts.map +1 -1
  194. package/dist/transactions/commitTransaction.js +1 -5
  195. package/dist/transactions/commitTransaction.js.map +1 -1
  196. package/dist/transform/write/array.d.ts +3 -2
  197. package/dist/transform/write/array.d.ts.map +1 -1
  198. package/dist/transform/write/array.js +2 -1
  199. package/dist/transform/write/array.js.map +1 -1
  200. package/dist/transform/write/blocks.d.ts +3 -2
  201. package/dist/transform/write/blocks.d.ts.map +1 -1
  202. package/dist/transform/write/blocks.js +2 -1
  203. package/dist/transform/write/blocks.js.map +1 -1
  204. package/dist/transform/write/index.d.ts.map +1 -1
  205. package/dist/transform/write/index.js +2 -0
  206. package/dist/transform/write/index.js.map +1 -1
  207. package/dist/transform/write/traverseFields.d.ts +2 -1
  208. package/dist/transform/write/traverseFields.d.ts.map +1 -1
  209. package/dist/transform/write/traverseFields.js +40 -20
  210. package/dist/transform/write/traverseFields.js.map +1 -1
  211. package/dist/transform/write/types.d.ts +7 -0
  212. package/dist/transform/write/types.d.ts.map +1 -1
  213. package/dist/transform/write/types.js.map +1 -1
  214. package/dist/types.d.ts +51 -2
  215. package/dist/types.d.ts.map +1 -1
  216. package/dist/types.js.map +1 -1
  217. package/dist/updateGlobal.d.ts +5 -1
  218. package/dist/updateGlobal.d.ts.map +1 -1
  219. package/dist/updateGlobal.js +96 -4
  220. package/dist/updateGlobal.js.map +1 -1
  221. package/dist/updateJobs.d.ts.map +1 -1
  222. package/dist/updateJobs.js +37 -0
  223. package/dist/updateJobs.js.map +1 -1
  224. package/dist/updateOne.d.ts.map +1 -1
  225. package/dist/updateOne.js +86 -4
  226. package/dist/updateOne.js.map +1 -1
  227. package/dist/upsertBranchGlobalChange.d.ts +3 -0
  228. package/dist/upsertBranchGlobalChange.d.ts.map +1 -0
  229. package/dist/upsertBranchGlobalChange.js +35 -0
  230. package/dist/upsertBranchGlobalChange.js.map +1 -0
  231. package/dist/upsertRow/deleteExistingRowsByPath.d.ts.map +1 -1
  232. package/dist/upsertRow/deleteExistingRowsByPath.js +17 -12
  233. package/dist/upsertRow/deleteExistingRowsByPath.js.map +1 -1
  234. package/dist/upsertRow/index.d.ts +1 -1
  235. package/dist/upsertRow/index.d.ts.map +1 -1
  236. package/dist/upsertRow/index.js +156 -46
  237. package/dist/upsertRow/index.js.map +1 -1
  238. package/dist/upsertRow/types.d.ts +3 -0
  239. package/dist/upsertRow/types.d.ts.map +1 -1
  240. package/dist/upsertRow/types.js.map +1 -1
  241. package/dist/utilities/buildCreateMigration.d.ts.map +1 -1
  242. package/dist/utilities/buildCreateMigration.js +12 -8
  243. package/dist/utilities/buildCreateMigration.js.map +1 -1
  244. package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.d.ts +15 -0
  245. package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.d.ts.map +1 -0
  246. package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.js +110 -0
  247. package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.js.map +1 -0
  248. package/dist/utilities/buildForeignKeyName.d.ts.map +1 -1
  249. package/dist/utilities/buildForeignKeyName.js +3 -2
  250. package/dist/utilities/buildForeignKeyName.js.map +1 -1
  251. package/dist/utilities/buildIndexName.d.ts.map +1 -1
  252. package/dist/utilities/buildIndexName.js +3 -2
  253. package/dist/utilities/buildIndexName.js.map +1 -1
  254. package/dist/utilities/checkTruncatedIdentifiers.d.ts +13 -0
  255. package/dist/utilities/checkTruncatedIdentifiers.d.ts.map +1 -0
  256. package/dist/utilities/checkTruncatedIdentifiers.js +56 -0
  257. package/dist/utilities/checkTruncatedIdentifiers.js.map +1 -0
  258. package/dist/utilities/createSchemaGenerator.d.ts.map +1 -1
  259. package/dist/utilities/createSchemaGenerator.js +3 -0
  260. package/dist/utilities/createSchemaGenerator.js.map +1 -1
  261. package/dist/utilities/getSizesToVariantsRenames.d.ts +54 -0
  262. package/dist/utilities/getSizesToVariantsRenames.d.ts.map +1 -0
  263. package/dist/utilities/getSizesToVariantsRenames.js +251 -0
  264. package/dist/utilities/getSizesToVariantsRenames.js.map +1 -0
  265. package/dist/utilities/parseJSONPathSegment.d.ts +9 -0
  266. package/dist/utilities/parseJSONPathSegment.d.ts.map +1 -0
  267. package/dist/utilities/parseJSONPathSegment.js +17 -0
  268. package/dist/utilities/parseJSONPathSegment.js.map +1 -0
  269. package/dist/utilities/validateExistingBlockIsIdentical.d.ts +1 -5
  270. package/dist/utilities/validateExistingBlockIsIdentical.d.ts.map +1 -1
  271. package/dist/utilities/validateExistingBlockIsIdentical.js.map +1 -1
  272. package/dist/utilities/validateIdentifierLength.d.ts +12 -0
  273. package/dist/utilities/validateIdentifierLength.d.ts.map +1 -0
  274. package/dist/utilities/validateIdentifierLength.js +18 -0
  275. package/dist/utilities/validateIdentifierLength.js.map +1 -0
  276. package/package.json +3 -3
  277. package/dist/upsertRow/handleUpsertError.spec.js +0 -42
  278. package/dist/upsertRow/handleUpsertError.spec.js.map +0 -1
  279. package/dist/utilities/isValidStringID.spec.js +0 -15
  280. package/dist/utilities/isValidStringID.spec.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/find/buildFindManyArgs.ts"],"sourcesContent":["import type { DBQueryConfig } from 'drizzle-orm'\nimport type { FlattenedField, JoinQuery, SelectType } from 'payload'\n\nimport { getSelectMode } from 'payload/shared'\n\nimport type { BuildQueryJoinAliases, DrizzleAdapter } from '../types.js'\n\nimport { traverseFields } from './traverseFields.js'\n\ntype BuildFindQueryArgs = {\n adapter: DrizzleAdapter\n collectionSlug?: string\n depth: number\n draftsEnabled?: boolean\n fields: FlattenedField[]\n joinQuery?: JoinQuery\n /**\n * The joins array will be mutated by pushing any joins needed for the where queries of join field joins\n */\n joins?: BuildQueryJoinAliases\n locale?: string\n select?: SelectType\n tableName: string\n versions?: boolean\n}\n\nexport type Result = {\n with?: {\n _locales?: DBQueryConfig<'many', true, any, any>\n } & DBQueryConfig<'many', true, any, any>\n} & DBQueryConfig<'many', true, any, any>\n\n// Generate the Drizzle query for findMany based on\n// a collection field structure\nexport const buildFindManyArgs = ({\n adapter,\n collectionSlug,\n depth,\n draftsEnabled,\n fields,\n joinQuery,\n joins = [],\n locale,\n select,\n tableName,\n versions,\n}: BuildFindQueryArgs): Result => {\n const result: Result = {\n extras: {},\n with: {},\n }\n\n if (select) {\n result.columns = {\n id: true,\n }\n }\n\n const _locales: Result = {\n columns: select\n ? { _locale: true }\n : {\n id: false,\n _parentID: false,\n },\n extras: {},\n with: {},\n }\n\n const withTabledFields = select\n ? {}\n : {\n numbers: true,\n rels: true,\n texts: true,\n }\n\n traverseFields({\n _locales,\n adapter,\n collectionSlug,\n currentArgs: result,\n currentTableName: tableName,\n depth,\n draftsEnabled,\n fields,\n joinQuery,\n joins,\n locale,\n path: '',\n select,\n selectMode: select ? getSelectMode(select) : undefined,\n tablePath: '',\n topLevelArgs: result,\n topLevelTableName: tableName,\n versions,\n withTabledFields,\n })\n\n if (adapter.tables[`${tableName}_texts`] && withTabledFields.texts) {\n result.with._texts = {\n columns: {\n id: false,\n parent: false,\n },\n orderBy: ({ order }, { asc: ASC }) => [ASC(order)],\n }\n }\n\n if (adapter.tables[`${tableName}_numbers`] && withTabledFields.numbers) {\n result.with._numbers = {\n columns: {\n id: false,\n parent: false,\n },\n orderBy: ({ order }, { asc: ASC }) => [ASC(order)],\n }\n }\n\n if (adapter.tables[`${tableName}${adapter.relationshipsSuffix}`] && withTabledFields.rels) {\n result.with._rels = {\n columns: {\n id: false,\n parent: false,\n },\n orderBy: ({ order }, { asc: ASC }) => [ASC(order)],\n }\n }\n\n if (\n adapter.tables[`${tableName}${adapter.localesSuffix}`] &&\n (!select || Object.keys(_locales.columns).length > 1)\n ) {\n result.with._locales = _locales\n }\n\n // Delete properties that are empty\n for (const key of Object.keys(result)) {\n if (!Object.keys(result[key]).length) {\n delete result[key]\n }\n }\n\n return result\n}\n"],"names":["getSelectMode","traverseFields","buildFindManyArgs","adapter","collectionSlug","depth","draftsEnabled","fields","joinQuery","joins","locale","select","tableName","versions","result","extras","with","columns","id","_locales","_locale","_parentID","withTabledFields","numbers","rels","texts","currentArgs","currentTableName","path","selectMode","undefined","tablePath","topLevelArgs","topLevelTableName","tables","_texts","parent","orderBy","order","asc","ASC","_numbers","relationshipsSuffix","_rels","localesSuffix","Object","keys","length","key"],"mappings":"AAGA,SAASA,aAAa,QAAQ,iBAAgB;AAI9C,SAASC,cAAc,QAAQ,sBAAqB;AAyBpD,mDAAmD;AACnD,+BAA+B;AAC/B,OAAO,MAAMC,oBAAoB,CAAC,EAChCC,OAAO,EACPC,cAAc,EACdC,KAAK,EACLC,aAAa,EACbC,MAAM,EACNC,SAAS,EACTC,QAAQ,EAAE,EACVC,MAAM,EACNC,MAAM,EACNC,SAAS,EACTC,QAAQ,EACW;IACnB,MAAMC,SAAiB;QACrBC,QAAQ,CAAC;QACTC,MAAM,CAAC;IACT;IAEA,IAAIL,QAAQ;QACVG,OAAOG,OAAO,GAAG;YACfC,IAAI;QACN;IACF;IAEA,MAAMC,WAAmB;QACvBF,SAASN,SACL;YAAES,SAAS;QAAK,IAChB;YACEF,IAAI;YACJG,WAAW;QACb;QACJN,QAAQ,CAAC;QACTC,MAAM,CAAC;IACT;IAEA,MAAMM,mBAAmBX,SACrB,CAAC,IACD;QACE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ACrD,CAAA,CAACjC,UAAUkC,OAAOC,IAAI,CAAC3B,SAASF,OAAO,EAAE8B,MAAM,GAAG,CAAA,GACnD;QACAjC,OAAOE,IAAI,CAACG,QAAQ,GAAGA;IACzB;IAEA,mCAAmC;IACnC,KAAK,MAAM6B,OAAOH,OAAOC,IAAI,CAAChC,QAAS;QACrC,IAAI,CAAC+B,OAAOC,IAAI,CAAChC,MAAM,CAACkC,IAAI,EAAED,MAAM,EAAE;YACpC,OAAOjC,MAAM,CAACkC,IAAI;QACpB;IACF;IAEA,OAAOlC;AACT,EAAC"}
1
+ {"version":3,"sources":["../../src/find/buildFindManyArgs.ts"],"sourcesContent":["import type { DBQueryConfig } from 'drizzle-orm'\nimport type { FlattenedField, JoinQuery, PayloadRequest, SelectType } from 'payload'\n\nimport { getSelectMode } from 'payload/shared'\n\nimport type { BuildQueryJoinAliases, DrizzleAdapter } from '../types.js'\n\nimport { traverseFields } from './traverseFields.js'\n\ntype BuildFindQueryArgs = {\n adapter: DrizzleAdapter\n collectionSlug?: string\n depth: number\n draftsEnabled?: boolean\n fields: FlattenedField[]\n joinQuery?: JoinQuery\n /**\n * The joins array will be mutated by pushing any joins needed for the where queries of join field joins\n */\n joins?: BuildQueryJoinAliases\n locale?: string\n req?: Partial<PayloadRequest>\n select?: SelectType\n tableName: string\n versions?: boolean\n}\n\nexport type Result = {\n with?: {\n _locales?: DBQueryConfig<'many', true, any, any>\n } & DBQueryConfig<'many', true, any, any>\n} & DBQueryConfig<'many', true, any, any>\n\n// Generate the Drizzle query for findMany based on\n// a collection field structure\nexport const buildFindManyArgs = ({\n adapter,\n collectionSlug,\n depth,\n draftsEnabled,\n fields,\n joinQuery,\n joins = [],\n locale,\n req,\n select,\n tableName,\n versions,\n}: BuildFindQueryArgs): Result => {\n const result: Result = {\n extras: {},\n with: {},\n }\n\n if (select) {\n result.columns = {\n id: true,\n }\n }\n\n const _locales: Result = {\n columns: select\n ? { _locale: true }\n : {\n id: false,\n _parentID: false,\n },\n extras: {},\n with: {},\n }\n\n const withTabledFields = select\n ? {}\n : {\n numbers: true,\n rels: true,\n texts: true,\n }\n\n traverseFields({\n _locales,\n adapter,\n collectionSlug,\n currentArgs: result,\n currentTableName: tableName,\n depth,\n draftsEnabled,\n fields,\n joinQuery,\n joins,\n locale,\n path: '',\n req,\n select,\n selectMode: select ? getSelectMode(select) : undefined,\n tablePath: '',\n topLevelArgs: result,\n topLevelTableName: tableName,\n versions,\n withTabledFields,\n })\n\n if (adapter.tables[`${tableName}_texts`] && withTabledFields.texts) {\n result.with._texts = {\n columns: {\n id: false,\n parent: false,\n },\n orderBy: ({ order }, { asc: ASC }) => [ASC(order)],\n }\n }\n\n if (adapter.tables[`${tableName}_numbers`] && withTabledFields.numbers) {\n result.with._numbers = {\n columns: {\n id: false,\n parent: false,\n },\n orderBy: ({ order }, { asc: ASC }) => [ASC(order)],\n }\n }\n\n if (adapter.tables[`${tableName}${adapter.relationshipsSuffix}`] && withTabledFields.rels) {\n result.with._rels = {\n columns: {\n id: false,\n parent: false,\n },\n orderBy: ({ order }, { asc: ASC }) => [ASC(order)],\n }\n }\n\n if (\n adapter.tables[`${tableName}${adapter.localesSuffix}`] &&\n (!select || Object.keys(_locales.columns).length > 1)\n ) {\n result.with._locales = _locales\n }\n\n // Delete properties that are empty\n for (const key of Object.keys(result)) {\n if (!Object.keys(result[key]).length) {\n delete result[key]\n }\n }\n\n return result\n}\n"],"names":["getSelectMode","traverseFields","buildFindManyArgs","adapter","collectionSlug","depth","draftsEnabled","fields","joinQuery","joins","locale","req","select","tableName","versions","result","extras","with","columns","id","_locales","_locale","_parentID","withTabledFields","numbers","rels","texts","currentArgs","currentTableName","path","selectMode","undefined","tablePath","topLevelArgs","topLevelTableName","tables","_texts","parent","orderBy","order","asc","ASC","_numbers","relationshipsSuffix","_rels","localesSuffix","Object","keys","length","key"],"mappings":"AAGA,SAASA,aAAa,QAAQ,iBAAgB;AAI9C,SAASC,cAAc,QAAQ,sBAAqB;AA0BpD,m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AS;gBACPC,IAAI;gBACJkB,QAAQ;YACV;YACAC,SAAS,CAAC,EAAEC,KAAK,EAAE,EAAE,EAAEC,KAAKC,GAAG,EAAE,GAAK;oBAACA,IAAIF;iBAAO;QACpD;IACF;IAEA,IAAIpC,QAAQgC,MAAM,CAAC,GAAGtB,YAAYV,QAAQwC,mBAAmB,EAAE,CAAC,IAAIpB,iBAAiBE,IAAI,EAAE;QACzFV,OAAOE,IAAI,CAAC2B,KAAK,GAAG;YAClB1B,SAAS;gBACPC,IAAI;gBACJkB,QAAQ;YACV;YACAC,SAAS,CAAC,EAAEC,KAAK,EAAE,EAAE,EAAEC,KAAKC,GAAG,EAAE,GAAK;oBAACA,IAAIF;iBAAO;QACpD;IACF;IAEA,IACEpC,QAAQgC,MAAM,CAAC,GAAGtB,YAAYV,QAAQ0C,aAAa,EAAE,CAAC,IACrD,CAAA,CAACjC,UAAUkC,OAAOC,IAAI,CAAC3B,SAASF,OAAO,EAAE8B,MAAM,GAAG,CAAA,GACnD;QACAjC,OAAOE,IAAI,CAACG,QAAQ,GAAGA;IACzB;IAEA,mCAAmC;IACnC,KAAK,MAAM6B,OAAOH,OAAOC,IAAI,CAAChC,QAAS;QACrC,IAAI,CAAC+B,OAAOC,IAAI,CAAChC,MAAM,CAACkC,IAAI,EAAED,MAAM,EAAE;YACpC,OAAOjC,MAAM,CAACkC,IAAI;QACpB;IACF;IAEA,OAAOlC;AACT,EAAC"}
@@ -0,0 +1,39 @@
1
+ import type { SQL } from 'drizzle-orm';
2
+ import { type FlattenedJoinField, type PayloadRequest, type Where } from 'payload';
3
+ import type { DrizzleAdapter } from '../types.js';
4
+ type BuildPolymorphicJoinQueryArgs = {
5
+ adapter: DrizzleAdapter;
6
+ currentTableName: string;
7
+ field: FlattenedJoinField;
8
+ limit: number;
9
+ locale?: string;
10
+ page?: number;
11
+ path: string;
12
+ req?: Partial<PayloadRequest>;
13
+ shouldCount: boolean;
14
+ sort?: string | string[];
15
+ where?: Where;
16
+ };
17
+ type PolymorphicJoinQuery = {
18
+ columnName: string;
19
+ count?: SQL.Aliased;
20
+ documents: SQL.Aliased;
21
+ };
22
+ /**
23
+ * Builds the correlated document and optional count projections for a join that targets multiple
24
+ * collections. Every collection branch exposes the same `id`, parent, `relationTo`, and sort
25
+ * columns before the branches are combined. A missing sort field resolves to SQL NULL so targets
26
+ * with different schemas can still share one ordered union.
27
+ *
28
+ * `field.collection` must contain at least one configured collection. Each mapped table must have
29
+ * an `id` column and the column named by `field.on`. The supplied `limit` is used as-is; callers can
30
+ * include an extra look-ahead row when they calculate pagination.
31
+ *
32
+ * @returns The stable projection name, the document projection, and the count projection when
33
+ * `shouldCount` is true.
34
+ * @throws If the join definition, target collection, mapped table, required columns, or sort shape
35
+ * cannot be represented by the polymorphic query.
36
+ */
37
+ export declare const buildPolymorphicJoinQuery: ({ adapter, currentTableName, field, limit, locale, page, path, req, shouldCount, sort, where, }: BuildPolymorphicJoinQueryArgs) => PolymorphicJoinQuery;
38
+ export {};
39
+ //# sourceMappingURL=buildPolymorphicJoinQuery.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buildPolymorphicJoinQuery.d.ts","sourceRoot":"","sources":["../../src/find/buildPolymorphicJoinQuery.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,aAAa,CAAA;AAKtC,OAAO,EAEL,KAAK,kBAAkB,EAEvB,KAAK,cAAc,EAEnB,KAAK,KAAK,EACX,MAAM,SAAS,CAAA;AAGhB,OAAO,KAAK,EAAE,cAAc,EAAgB,MAAM,aAAa,CAAA;AAQ/D,KAAK,6BAA6B,GAAG;IACnC,OAAO,EAAE,cAAc,CAAA;IACvB,gBAAgB,EAAE,MAAM,CAAA;IACxB,KAAK,EAAE,kBAAkB,CAAA;IACzB,KAAK,EAAE,MAAM,CAAA;IACb,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,IAAI,EAAE,MAAM,CAAA;IACZ,GAAG,CAAC,EAAE,OAAO,CAAC,cAAc,CAAC,CAAA;IAC7B,WAAW,EAAE,OAAO,CAAA;IACpB,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAA;IACxB,KAAK,CAAC,EAAE,KAAK,CAAA;CACd,CAAA;AAED,KAAK,oBAAoB,GAAG;IAC1B,UAAU,EAAE,MAAM,CAAA;IAClB,KAAK,CAAC,EAAE,GAAG,CAAC,OAAO,CAAA;IACnB,SAAS,EAAE,GAAG,CAAC,OAAO,CAAA;CACvB,CAAA;AAED;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,yBAAyB,oGAYnC,6BAA6B,KAAG,oBAgJlC,CAAA"}
@@ -0,0 +1,152 @@
1
+ import { and, asc, count, desc, eq, sql } from 'drizzle-orm';
2
+ import { combineQueries, getBranchPredicateSync, resolveBranchReadState } from 'payload';
3
+ import toSnakeCase from 'to-snake-case';
4
+ import { buildBranchVisibility } from '../queries/buildBranchVisibility.js';
5
+ import { jsonAggBuildObject } from '../utilities/json.js';
6
+ import { buildPolymorphicJoinWhere } from './buildPolymorphicJoinWhere.js';
7
+ import { createPolymorphicJoinWherePlan } from './createPolymorphicJoinWherePlan.js';
8
+ /**
9
+ * Builds the correlated document and optional count projections for a join that targets multiple
10
+ * collections. Every collection branch exposes the same `id`, parent, `relationTo`, and sort
11
+ * columns before the branches are combined. A missing sort field resolves to SQL NULL so targets
12
+ * with different schemas can still share one ordered union.
13
+ *
14
+ * `field.collection` must contain at least one configured collection. Each mapped table must have
15
+ * an `id` column and the column named by `field.on`. The supplied `limit` is used as-is; callers can
16
+ * include an extra look-ahead row when they calculate pagination.
17
+ *
18
+ * @returns The stable projection name, the document projection, and the count projection when
19
+ * `shouldCount` is true.
20
+ * @throws If the join definition, target collection, mapped table, required columns, or sort shape
21
+ * cannot be represented by the polymorphic query.
22
+ */ export const buildPolymorphicJoinQuery = ({ adapter, currentTableName, field, limit, locale, page, path, req, shouldCount, sort, where })=>{
23
+ if (!Array.isArray(field.collection)) {
24
+ throw new Error('A polymorphic join requires a collection array');
25
+ }
26
+ if (field.collection.length === 0) {
27
+ throw new Error('A polymorphic join requires at least one collection');
28
+ }
29
+ if (Array.isArray(sort)) {
30
+ throw new Error('Polymorphic joins do not support multiple sort fields');
31
+ }
32
+ const collections = field.collection;
33
+ const columnName = `${path.replaceAll('.', '_')}${field.name}`;
34
+ const db = adapter.drizzle;
35
+ const onPath = field.on.split('.').join('_');
36
+ const collectionTables = collections.map((collection)=>{
37
+ if (!adapter.payload.collections[collection]) {
38
+ throw new Error(`Unknown polymorphic join collection "${collection}"`);
39
+ }
40
+ const tableName = adapter.tableNameMap.get(toSnakeCase(collection));
41
+ const table = tableName ? adapter.tables[tableName] : undefined;
42
+ if (!table) {
43
+ throw new Error(`Polymorphic join collection "${collection}" has no database table`);
44
+ }
45
+ if (!table['id']) {
46
+ throw new Error(`Polymorphic join collection "${collection}" has no "id" column`);
47
+ }
48
+ if (!table[onPath]) {
49
+ throw new Error(`Polymorphic join collection "${collection}" has no "${onPath}" column`);
50
+ }
51
+ return {
52
+ collection,
53
+ table
54
+ };
55
+ });
56
+ const sortField = getSortField({
57
+ adapter,
58
+ collections,
59
+ sort
60
+ });
61
+ const sortOrder = sortField.startsWith('-') ? desc : asc;
62
+ const sortPath = sortField.replace('-', '').split('.').join('_');
63
+ let unionQuery = null;
64
+ for (const { collection, table } of collectionTables){
65
+ const branchReadState = resolveBranchReadState({
66
+ collectionSlug: collection,
67
+ req
68
+ });
69
+ const branchPredicate = branchReadState.useBranching ? null : getBranchPredicateSync({
70
+ collectionSlug: collection,
71
+ req
72
+ });
73
+ const collectionWhere = branchPredicate ? combineQueries(where ?? {}, branchPredicate) : where;
74
+ const wherePlan = collectionWhere ? createPolymorphicJoinWherePlan({
75
+ adapter,
76
+ collections,
77
+ where: collectionWhere
78
+ }) : new Map();
79
+ const sortColumn = table[sortPath];
80
+ const selectFields = {
81
+ id: (branchReadState.useBranching || branchPredicate) && table['_branchDocID'] ? sql`COALESCE(${table['_branchDocID']}, ${table['id']})`.as('id') : table['id'],
82
+ parent: sql`${table[onPath]}`.as(onPath),
83
+ relationTo: sql`${collection}`.as('relationTo'),
84
+ sortPath: sql`${sortColumn ?? null}`.as('sortPath')
85
+ };
86
+ const parsedCollectionWhere = collectionWhere && Object.keys(collectionWhere).length > 0 ? buildPolymorphicJoinWhere({
87
+ adapter,
88
+ collection,
89
+ locale,
90
+ table,
91
+ where: collectionWhere,
92
+ wherePlan
93
+ }) : undefined;
94
+ const collectionWhereSQL = branchReadState.useBranching ? and(parsedCollectionWhere, buildBranchVisibility({
95
+ adapter,
96
+ branch: branchReadState.branch,
97
+ collectionSlug: collection,
98
+ table
99
+ })) : parsedCollectionWhere;
100
+ let collectionQuery = db.select(selectFields).from(table).$dynamic();
101
+ if (collectionWhereSQL) {
102
+ collectionQuery = collectionQuery.where(collectionWhereSQL);
103
+ }
104
+ if (unionQuery === null) {
105
+ unionQuery = collectionQuery;
106
+ } else {
107
+ unionQuery = unionQuery.unionAll(collectionQuery);
108
+ }
109
+ }
110
+ const subQueryAlias = `${columnName}_subquery`;
111
+ const parentConstraint = eq(sql.raw(`"${currentTableName}"."id"`), sql.raw(`"${subQueryAlias}"."${onPath}"`));
112
+ const countExpression = shouldCount ? sql`${db.select({
113
+ count: count()
114
+ }).from(sql`${unionQuery.as(subQueryAlias)}`).where(parentConstraint)}`.as(`${columnName}_count`) : undefined;
115
+ unionQuery = unionQuery.orderBy(sortOrder(sql`"sortPath"`));
116
+ const sortedUnionAlias = `${columnName}_sorted`;
117
+ let limitOffsetSQL = sql.empty();
118
+ if (limit) {
119
+ limitOffsetSQL = sql` LIMIT ${limit}`;
120
+ }
121
+ if (page && limit !== 0) {
122
+ const offset = (page - 1) * limit;
123
+ if (offset > 0) {
124
+ limitOffsetSQL = sql`${limitOffsetSQL} OFFSET ${offset}`;
125
+ }
126
+ }
127
+ const parentWhere = sql.raw(`"${sortedUnionAlias}"."${onPath}" = "${currentTableName}"."id"`);
128
+ const documents = sql`(
129
+ SELECT ${jsonAggBuildObject(adapter, {
130
+ id: sql.raw(`"${subQueryAlias}"."id"`),
131
+ relationTo: sql.raw(`"${subQueryAlias}"."relationTo"`)
132
+ })}
133
+ FROM (
134
+ SELECT * FROM ${sql`${unionQuery.as(sortedUnionAlias)}`}
135
+ WHERE ${parentWhere}${limitOffsetSQL}
136
+ ) AS ${sql.raw(`"${subQueryAlias}"`)}
137
+ )`.as(columnName);
138
+ return {
139
+ columnName,
140
+ count: countExpression,
141
+ documents
142
+ };
143
+ };
144
+ const getSortField = ({ adapter, collections, sort })=>{
145
+ if (sort) {
146
+ return sort;
147
+ }
148
+ const hasCreatedAt = collections.some((collection)=>adapter.payload.collections[collection].config.fields.some((field)=>field.type === 'date' && field.name === 'createdAt'));
149
+ return hasCreatedAt ? '-createdAt' : 'id';
150
+ };
151
+
152
+ //# sourceMappingURL=buildPolymorphicJoinQuery.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/find/buildPolymorphicJoinQuery.ts"],"sourcesContent":["import type { SQL } from 'drizzle-orm'\nimport type { LibSQLDatabase } from 'drizzle-orm/libsql'\nimport type { SQLiteSelect } from 'drizzle-orm/sqlite-core'\n\nimport { and, asc, count, desc, eq, sql } from 'drizzle-orm'\nimport {\n combineQueries,\n type FlattenedJoinField,\n getBranchPredicateSync,\n type PayloadRequest,\n resolveBranchReadState,\n type Where,\n} from 'payload'\nimport toSnakeCase from 'to-snake-case'\n\nimport type { DrizzleAdapter, GenericTable } from '../types.js'\nimport type { PolymorphicJoinWherePlan } from './createPolymorphicJoinWherePlan.js'\n\nimport { buildBranchVisibility } from '../queries/buildBranchVisibility.js'\nimport { jsonAggBuildObject } from '../utilities/json.js'\nimport { buildPolymorphicJoinWhere } from './buildPolymorphicJoinWhere.js'\nimport { createPolymorphicJoinWherePlan } from './createPolymorphicJoinWherePlan.js'\n\ntype BuildPolymorphicJoinQueryArgs = {\n adapter: DrizzleAdapter\n currentTableName: string\n field: FlattenedJoinField\n limit: number\n locale?: string\n page?: number\n path: string\n req?: Partial<PayloadRequest>\n shouldCount: boolean\n sort?: string | string[]\n where?: Where\n}\n\ntype PolymorphicJoinQuery = {\n columnName: string\n count?: SQL.Aliased\n documents: SQL.Aliased\n}\n\n/**\n * Builds the correlated document and optional count projections for a join that targets multiple\n * collections. Every collection branch exposes the same `id`, parent, `relationTo`, and sort\n * columns before the branches are combined. A missing sort field resolves to SQL NULL so targets\n * with different schemas can still share one ordered union.\n *\n * `field.collection` must contain at least one configured collection. Each mapped table must have\n * an `id` column and the column named by `field.on`. The supplied `limit` is used as-is; callers can\n * include an extra look-ahead row when they calculate pagination.\n *\n * @returns The stable projection name, the document projection, and the count projection when\n * `shouldCount` is true.\n * @throws If the join definition, target collection, mapped table, required columns, or sort shape\n * cannot be represented by the polymorphic query.\n */\nexport const buildPolymorphicJoinQuery = ({\n adapter,\n currentTableName,\n field,\n limit,\n locale,\n page,\n path,\n req,\n shouldCount,\n sort,\n where,\n}: BuildPolymorphicJoinQueryArgs): PolymorphicJoinQuery => {\n if (!Array.isArray(field.collection)) {\n throw new Error('A polymorphic join requires a collection array')\n }\n\n if (field.collection.length === 0) {\n throw new Error('A polymorphic join requires at least one collection')\n }\n\n if (Array.isArray(sort)) {\n throw new Error('Polymorphic joins do not support multiple sort fields')\n }\n\n const collections = field.collection\n const columnName = `${path.replaceAll('.', '_')}${field.name}`\n const db = adapter.drizzle as LibSQLDatabase\n const onPath = field.on.split('.').join('_')\n const collectionTables = collections.map((collection) => {\n if (!adapter.payload.collections[collection]) {\n throw new Error(`Unknown polymorphic join collection \"${collection}\"`)\n }\n\n const tableName = adapter.tableNameMap.get(toSnakeCase(collection))\n const table = tableName ? (adapter.tables[tableName] as GenericTable | undefined) : undefined\n\n if (!table) {\n throw new Error(`Polymorphic join collection \"${collection}\" has no database table`)\n }\n\n if (!table['id']) {\n throw new Error(`Polymorphic join collection \"${collection}\" has no \"id\" column`)\n }\n\n if (!table[onPath]) {\n throw new Error(`Polymorphic join collection \"${collection}\" has no \"${onPath}\" column`)\n }\n\n return { collection, table }\n })\n const sortField = getSortField({ adapter, collections, sort })\n const sortOrder = sortField.startsWith('-') ? desc : asc\n const sortPath = sortField.replace('-', '').split('.').join('_')\n let unionQuery: null | SQLiteSelect = null\n\n for (const { collection, table } of collectionTables) {\n const branchReadState = resolveBranchReadState({ collectionSlug: collection, req })\n const branchPredicate = branchReadState.useBranching\n ? null\n : getBranchPredicateSync({ collectionSlug: collection, req })\n const collectionWhere = branchPredicate ? combineQueries(where ?? {}, branchPredicate) : where\n const wherePlan: PolymorphicJoinWherePlan = collectionWhere\n ? createPolymorphicJoinWherePlan({ adapter, collections, where: collectionWhere })\n : new Map()\n const sortColumn = table[sortPath]\n const selectFields = {\n id:\n (branchReadState.useBranching || branchPredicate) && table['_branchDocID']\n ? sql`COALESCE(${table['_branchDocID']}, ${table['id']})`.as('id')\n : table['id'],\n parent: sql`${table[onPath]}`.as(onPath),\n relationTo: sql`${collection}`.as('relationTo'),\n sortPath: sql`${sortColumn ?? null}`.as('sortPath'),\n }\n const parsedCollectionWhere =\n collectionWhere && Object.keys(collectionWhere).length > 0\n ? buildPolymorphicJoinWhere({\n adapter,\n collection,\n locale,\n table,\n where: collectionWhere,\n wherePlan,\n })\n : undefined\n const collectionWhereSQL = branchReadState.useBranching\n ? and(\n parsedCollectionWhere,\n buildBranchVisibility({\n adapter,\n branch: branchReadState.branch,\n collectionSlug: collection,\n table,\n }),\n )\n : parsedCollectionWhere\n let collectionQuery = db.select(selectFields).from(table).$dynamic()\n\n if (collectionWhereSQL) {\n collectionQuery = collectionQuery.where(collectionWhereSQL)\n }\n\n if (unionQuery === null) {\n unionQuery = collectionQuery as unknown as SQLiteSelect\n } else {\n unionQuery = unionQuery.unionAll(collectionQuery)\n }\n }\n\n const subQueryAlias = `${columnName}_subquery`\n const parentConstraint = eq(\n sql.raw(`\"${currentTableName}\".\"id\"`),\n sql.raw(`\"${subQueryAlias}\".\"${onPath}\"`),\n )\n const countExpression = shouldCount\n ? sql`${db\n .select({ count: count() })\n .from(sql`${unionQuery.as(subQueryAlias)}`)\n .where(parentConstraint)}`.as(`${columnName}_count`)\n : undefined\n\n unionQuery = unionQuery.orderBy(sortOrder(sql`\"sortPath\"`))\n\n const sortedUnionAlias = `${columnName}_sorted`\n let limitOffsetSQL = sql.empty()\n\n if (limit) {\n limitOffsetSQL = sql` LIMIT ${limit}`\n }\n\n if (page && limit !== 0) {\n const offset = (page - 1) * limit\n\n if (offset > 0) {\n limitOffsetSQL = sql`${limitOffsetSQL} OFFSET ${offset}`\n }\n }\n\n const parentWhere = sql.raw(`\"${sortedUnionAlias}\".\"${onPath}\" = \"${currentTableName}\".\"id\"`)\n const documents = sql`(\n SELECT ${jsonAggBuildObject(adapter, {\n id: sql.raw(`\"${subQueryAlias}\".\"id\"`),\n relationTo: sql.raw(`\"${subQueryAlias}\".\"relationTo\"`),\n })}\n FROM (\n SELECT * FROM ${sql`${unionQuery.as(sortedUnionAlias)}`}\n WHERE ${parentWhere}${limitOffsetSQL}\n ) AS ${sql.raw(`\"${subQueryAlias}\"`)}\n )`.as(columnName)\n\n return {\n columnName,\n count: countExpression,\n documents,\n }\n}\n\nconst getSortField = ({\n adapter,\n collections,\n sort,\n}: {\n adapter: DrizzleAdapter\n collections: string[]\n sort?: string\n}): string => {\n if (sort) {\n return sort\n }\n\n const hasCreatedAt = collections.some((collection) =>\n adapter.payload.collections[collection].config.fields.some(\n (field) => field.type === 'date' && field.name === 'createdAt',\n ),\n )\n\n return hasCreatedAt ? '-createdAt' : 'id'\n}\n"],"names":["and","asc","count","desc","eq","sql","combineQueries","getBranchPredicateSync","resolveBranchReadState","toSnakeCase","buildBranchVisibility","jsonAggBuildObject","buildPolymorphicJoinWhere","createPolymorphicJoinWherePlan","buildPolymorphicJoinQuery","adapter","currentTableName","field","limit","locale","page","path","req","shouldCount","sort","where","Array","isArray","collection","Error","length","collections","columnName","replaceAll","name","db","drizzle","onPath","on","split","join","collectionTables","map","payload","tableName","tableNameMap","get","table","tables","undefined","sortField","getSortField","sortOrder","startsWith","sortPath","replace","unionQuery","branchReadState","collectionSlug","branchPredicate","useBranching","collectionWhere","wherePlan","Map","sortColumn","selectFields","id","as","parent","relationTo","parsedCollectionWhere","Object","keys","collectionWhereSQL","branch","collectionQuery","select","from","$dynamic","unionAll","subQueryAlias","parentConstraint","raw","countExpression","orderBy","sortedUnionAlias","limitOffsetSQL","empty","offset","parentWhere","documents","hasCreatedAt","some","config","fields","type"],"mappings":"AAIA,SAASA,GAAG,EAAEC,GAAG,EAAEC,KAAK,EAAEC,IAAI,EAAEC,EAAE,EAAEC,GAAG,QAAQ,cAAa;AAC5D,SACEC,cAAc,EAEdC,sBAAsB,EAEtBC,sBAAsB,QAEjB,UAAS;AAChB,OAAOC,iBAAiB,gBAAe;AAKvC,SAASC,qBAAqB,QAAQ,sCAAqC;AAC3E,SAASC,kBAAkB,QAAQ,uBAAsB;AACzD,SAASC,yBAAyB,QAAQ,iCAAgC;AAC1E,SAASC,8BAA8B,QAAQ,sCAAqC;AAsBpF;;;;;;;;;;;;;;CAcC,GACD,OAAO,MAAMC,4BAA4B,CAAC,EACxCC,OAAO,EACPC,gBAAgB,EAChBC,KAAK,EACLC,KAAK,EACLC,MAAM,EACNC,IAAI,EACJC,IAAI,EACJC,GAAG,EACHC,WAAW,EACXC,IAAI,EACJC,KAAK,EACyB;IAC9B,IAAI,CAACC,MAAMC,OAAO,CAACV,MAAMW,UAAU,GAAG;QACpC,MAAM,IAAIC,MAAM;IAClB;IAEA,IAAIZ,MAAMW,UAAU,CAACE,MAAM,KAAK,GAAG;QACjC,MAAM,IAAID,MAAM;IAClB;IAEA,IAAIH,MAAMC,OAAO,CAACH,OAAO;QACvB,MAAM,IAAIK,MAAM;IAClB;IAEA,MAAME,cAAcd,MAAMW,UAAU;IACpC,MAAMI,aAAa,GAAGX,KAAKY,UAAU,CAAC,KAAK,OAAOhB,MAAMi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,cAAc,MAAM,CAAC;QACrCX,YAAYhE,IAAI6E,GAAG,CAAC,CAAC,CAAC,EAAEF,cAAc,cAAc,CAAC;IACvD,GAAG;;oBAEa,EAAE3E,GAAG,CAAC,EAAEmD,WAAWW,EAAE,CAACkB,kBAAkB,CAAC,CAAC;YAClD,EAAEI,YAAY,EAAEH,eAAe;SAClC,EAAEjF,IAAI6E,GAAG,CAAC,CAAC,CAAC,EAAEF,cAAc,CAAC,CAAC,EAAE;GACtC,CAAC,CAACb,EAAE,CAACnC;IAEN,OAAO;QACLA;QACA9B,OAAOiF;QACPO;IACF;AACF,EAAC;AAED,MAAMvC,eAAe,CAAC,EACpBpC,OAAO,EACPgB,WAAW,EACXP,IAAI,EAKL;IACC,IAAIA,MAAM;QACR,OAAOA;IACT;IAEA,MAAMmE,eAAe5D,YAAY6D,IAAI,CAAC,CAAChE,aACrCb,QAAQ4B,OAAO,CAACZ,WAAW,CAACH,WAAW,CAACiE,MAAM,CAACC,MAAM,CAACF,IAAI,CACxD,CAAC3E,QAAUA,MAAM8E,IAAI,KAAK,UAAU9E,MAAMiB,IAAI,KAAK;IAIvD,OAAOyD,eAAe,eAAe;AACvC"}
@@ -0,0 +1,20 @@
1
+ import type { SQL } from 'drizzle-orm';
2
+ import { type Where } from 'payload';
3
+ import type { DrizzleAdapter, GenericTable } from '../types.js';
4
+ import type { PolymorphicJoinWherePlan } from './createPolymorphicJoinWherePlan.js';
5
+ type BuildPolymorphicJoinWhereArgs = {
6
+ adapter: DrizzleAdapter;
7
+ collection: string;
8
+ locale?: string;
9
+ table: GenericTable;
10
+ where: Where;
11
+ wherePlan: PolymorphicJoinWherePlan;
12
+ };
13
+ /**
14
+ * Builds a where clause for one collection before the polymorphic branches are combined. A field
15
+ * that is absent from this collection resolves to SQL NULL, and relationTo resolves to the current
16
+ * collection slug.
17
+ */
18
+ export declare const buildPolymorphicJoinWhere: ({ adapter, collection, locale, table, where, wherePlan, }: BuildPolymorphicJoinWhereArgs) => SQL | undefined;
19
+ export {};
20
+ //# sourceMappingURL=buildPolymorphicJoinWhere.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buildPolymorphicJoinWhere.d.ts","sourceRoot":"","sources":["../../src/find/buildPolymorphicJoinWhere.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAU,GAAG,EAAE,MAAM,aAAa,CAAA;AAG9C,OAAO,EAAkD,KAAK,KAAK,EAAE,MAAM,SAAS,CAAA;AAIpF,OAAO,KAAK,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAC/D,OAAO,KAAK,EACV,wBAAwB,EAGzB,MAAM,qCAAqC,CAAA;AAO5C,KAAK,6BAA6B,GAAG;IACnC,OAAO,EAAE,cAAc,CAAA;IACvB,UAAU,EAAE,MAAM,CAAA;IAClB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,KAAK,EAAE,YAAY,CAAA;IACnB,KAAK,EAAE,KAAK,CAAA;IACZ,SAAS,EAAE,wBAAwB,CAAA;CACpC,CAAA;AAqBD;;;;GAIG;AACH,eAAO,MAAM,yBAAyB,8DAOnC,6BAA6B,KAAG,GAAG,GAAG,SAsMxC,CAAA"}
@@ -0,0 +1,301 @@
1
+ import { and, getTableName, isNotNull, isNull, or, sql } from 'drizzle-orm';
2
+ import { QueryError } from 'payload';
3
+ import toSnakeCase from 'to-snake-case';
4
+ import { buildOperatorConstraint } from '../queries/buildOperatorConstraint.js';
5
+ import { sanitizeQueryValue } from '../queries/sanitizeQueryValue.js';
6
+ const supportedJSONQueryOperators = new Set([
7
+ 'contains',
8
+ 'equals',
9
+ 'exists',
10
+ 'in',
11
+ 'like'
12
+ ]);
13
+ /**
14
+ * Builds a where clause for one collection before the polymorphic branches are combined. A field
15
+ * that is absent from this collection resolves to SQL NULL, and relationTo resolves to the current
16
+ * collection slug.
17
+ */ export const buildPolymorphicJoinWhere = ({ adapter, collection, locale, table, where, wherePlan })=>{
18
+ const constraints = [];
19
+ for(const key in where){
20
+ if ([
21
+ 'AND',
22
+ 'OR'
23
+ ].includes(key.toUpperCase())) {
24
+ if (!Array.isArray(where[key])) {
25
+ throw new QueryError([
26
+ {
27
+ path: key
28
+ }
29
+ ]);
30
+ }
31
+ const combine = key.toUpperCase() === 'AND' ? and : or;
32
+ const nestedConstraints = where[key].map((nestedWhere)=>buildPolymorphicJoinWhere({
33
+ adapter,
34
+ collection,
35
+ locale,
36
+ table,
37
+ where: nestedWhere,
38
+ wherePlan
39
+ }));
40
+ const nestedCondition = combine(...nestedConstraints);
41
+ if (nestedCondition) {
42
+ constraints.push(nestedCondition);
43
+ }
44
+ continue;
45
+ }
46
+ const resolvedPath = resolveWherePath({
47
+ adapter,
48
+ collection,
49
+ schemaPath: key,
50
+ table,
51
+ wherePlan
52
+ });
53
+ for (let payloadOperator of Object.keys(where[key])){
54
+ const originalOperator = payloadOperator;
55
+ let value = where[key][payloadOperator];
56
+ if (resolvedPath.type === 'invalid') {
57
+ throw new QueryError([
58
+ {
59
+ path: `${key}.${payloadOperator}`
60
+ }
61
+ ]);
62
+ }
63
+ if (resolvedPath.type === 'hasManySelect') {
64
+ if (!supportedJSONQueryOperators.has(payloadOperator)) {
65
+ throw new QueryError([
66
+ {
67
+ path: `${key}.${payloadOperator}`
68
+ }
69
+ ]);
70
+ }
71
+ const sanitizedQueryValue = sanitizeQueryValue({
72
+ adapter,
73
+ field: resolvedPath.fieldContext,
74
+ isUUID: false,
75
+ operator: payloadOperator,
76
+ relationOrPath: key,
77
+ val: value
78
+ });
79
+ if (sanitizedQueryValue === null) {
80
+ throw new QueryError([
81
+ {
82
+ path: `${key}.${originalOperator}`
83
+ }
84
+ ]);
85
+ }
86
+ if (sanitizedQueryValue.columns) {
87
+ throw new QueryError([
88
+ {
89
+ path: `${key}.${originalOperator}`
90
+ }
91
+ ]);
92
+ }
93
+ value = sanitizedQueryValue.value;
94
+ if (payloadOperator === 'in' && Array.isArray(value) && value.length === 0) {
95
+ constraints.push(sql.raw('false'));
96
+ continue;
97
+ }
98
+ const jsonQueryOperator = payloadOperator === 'exists' ? 'exists' : sanitizedQueryValue.operator;
99
+ constraints.push(sql.raw(adapter.createJSONQuery({
100
+ column: resolvedPath.jsonExpression,
101
+ operator: jsonQueryOperator,
102
+ pathSegments: [
103
+ resolvedPath.pathPlan.columnPath
104
+ ],
105
+ value
106
+ })));
107
+ continue;
108
+ }
109
+ if (payloadOperator === '$raw') {
110
+ if (typeof value !== 'string') {
111
+ throw new QueryError([
112
+ {
113
+ path: `${key}.${payloadOperator}`
114
+ }
115
+ ]);
116
+ }
117
+ constraints.push(sql.raw(value));
118
+ continue;
119
+ }
120
+ const { column, fieldContext, queryValueContext } = resolvedPath;
121
+ if (payloadOperator === 'like' && (queryValueContext.field.type === 'number' || queryValueContext.field.type === 'relationship' || queryValueContext.field.type === 'upload' || queryValueContext.isUUID)) {
122
+ payloadOperator = 'equals';
123
+ }
124
+ const sanitizedQueryValue = sanitizeQueryValue({
125
+ adapter,
126
+ field: queryValueContext.field,
127
+ isUUID: queryValueContext.isUUID,
128
+ operator: payloadOperator,
129
+ relationOrPath: key,
130
+ val: value
131
+ });
132
+ if (sanitizedQueryValue === null) {
133
+ throw new QueryError([
134
+ {
135
+ path: `${key}.${originalOperator}`
136
+ }
137
+ ]);
138
+ }
139
+ if (sanitizedQueryValue.columns) {
140
+ throw new QueryError([
141
+ {
142
+ path: `${key}.${originalOperator}`
143
+ }
144
+ ]);
145
+ }
146
+ payloadOperator = sanitizedQueryValue.operator;
147
+ value = sanitizedQueryValue.value;
148
+ if (!(payloadOperator in adapter.operators)) {
149
+ throw new QueryError([
150
+ {
151
+ path: `${key}.${originalOperator}`
152
+ }
153
+ ]);
154
+ }
155
+ const resolvedOperator = payloadOperator;
156
+ const operator = adapter.operators[resolvedOperator];
157
+ const buildColumnConstraint = (constraintValue)=>{
158
+ if (!fieldContext) {
159
+ return operator(column, constraintValue);
160
+ }
161
+ return buildOperatorConstraint({
162
+ adapter,
163
+ column,
164
+ field: fieldContext.field,
165
+ locale,
166
+ originalOperator,
167
+ path: key,
168
+ resolvedOperator,
169
+ value: constraintValue
170
+ });
171
+ };
172
+ if (originalOperator === 'equals' && value === null) {
173
+ constraints.push(isNull(column));
174
+ continue;
175
+ }
176
+ if (originalOperator === 'not_equals') {
177
+ if (value === null) {
178
+ constraints.push(isNotNull(column));
179
+ } else {
180
+ const notEqualsConstraint = or(isNull(column), buildColumnConstraint(value));
181
+ if (notEqualsConstraint) {
182
+ constraints.push(notEqualsConstraint);
183
+ }
184
+ }
185
+ continue;
186
+ }
187
+ if (originalOperator === 'in' && Array.isArray(value) && value.includes(null)) {
188
+ const nonNullValues = value.filter((item)=>item !== null);
189
+ const inConstraint = buildColumnConstraint(nonNullValues);
190
+ const nullAwareInConstraint = or(isNull(column), inConstraint);
191
+ if (nullAwareInConstraint) {
192
+ constraints.push(nullAwareInConstraint);
193
+ }
194
+ continue;
195
+ }
196
+ if (payloadOperator === 'like' && typeof value === 'string') {
197
+ const wordConstraints = value.split(' ').map((word)=>buildColumnConstraint(`%${word}%`));
198
+ const wordCondition = and(...wordConstraints);
199
+ if (wordCondition) {
200
+ constraints.push(wordCondition);
201
+ }
202
+ continue;
203
+ }
204
+ constraints.push(buildColumnConstraint(value));
205
+ }
206
+ }
207
+ return and(...constraints);
208
+ };
209
+ const resolveWherePath = ({ adapter, collection, schemaPath, table, wherePlan })=>{
210
+ const pathPlan = wherePlan.get(schemaPath);
211
+ if (!pathPlan) {
212
+ throw new QueryError([
213
+ {
214
+ path: schemaPath
215
+ }
216
+ ]);
217
+ }
218
+ if (pathPlan.type === 'invalid') {
219
+ return {
220
+ type: 'invalid',
221
+ pathPlan
222
+ };
223
+ }
224
+ if (schemaPath === 'relationTo') {
225
+ return {
226
+ type: 'scalar',
227
+ column: sql`${collection}`,
228
+ pathPlan,
229
+ queryValueContext: {
230
+ type: 'scalar',
231
+ field: {
232
+ name: 'relationTo',
233
+ type: 'text'
234
+ },
235
+ isUUID: false
236
+ }
237
+ };
238
+ }
239
+ if (pathPlan.type === 'hasManySelect') {
240
+ const fieldContext = [
241
+ ...pathPlan.fieldsByCollection.values()
242
+ ].find((field)=>field.type === 'hasManySelect')?.field;
243
+ if (!fieldContext) {
244
+ return {
245
+ type: 'invalid',
246
+ pathPlan
247
+ };
248
+ }
249
+ return {
250
+ type: 'hasManySelect',
251
+ fieldContext,
252
+ jsonExpression: getHasManySelectExpression({
253
+ adapter,
254
+ collection,
255
+ pathPlan,
256
+ table
257
+ }),
258
+ pathPlan
259
+ };
260
+ }
261
+ const collectionField = pathPlan.fieldsByCollection.get(collection);
262
+ const fieldContext = collectionField?.type === 'scalar' ? collectionField : undefined;
263
+ const queryValueContext = fieldContext ?? [
264
+ ...pathPlan.fieldsByCollection.values()
265
+ ].find((field)=>field.type === 'scalar');
266
+ if (!queryValueContext) {
267
+ return {
268
+ type: 'invalid',
269
+ pathPlan
270
+ };
271
+ }
272
+ return {
273
+ type: 'scalar',
274
+ column: fieldContext ? table[pathPlan.columnPath] : sql`null`,
275
+ fieldContext,
276
+ pathPlan,
277
+ queryValueContext
278
+ };
279
+ };
280
+ const getHasManySelectExpression = ({ adapter, collection, pathPlan, table })=>{
281
+ if (pathPlan.fieldsByCollection.get(collection)?.type !== 'hasManySelect') {
282
+ return adapter.name === 'postgres' ? `'[]'::jsonb` : `'[]'`;
283
+ }
284
+ const selectTablePath = pathPlan.schemaPath.split('.').map((pathSegment)=>toSnakeCase(pathSegment)).join('_');
285
+ const valuesTableName = adapter.tableNameMap.get(`${toSnakeCase(collection)}_${selectTablePath}`);
286
+ if (!valuesTableName) {
287
+ throw new Error(`Polymorphic join collection "${collection}" has no value table for "${pathPlan.schemaPath}"`);
288
+ }
289
+ let qualifiedValuesTableName = valuesTableName;
290
+ let parentTableName = getTableName(table);
291
+ if (adapter.schemaName) {
292
+ qualifiedValuesTableName = `"${adapter.schemaName}"."${valuesTableName}"`;
293
+ parentTableName = `"${adapter.schemaName}"."${parentTableName}"`;
294
+ }
295
+ if (adapter.name === 'postgres') {
296
+ return `(select coalesce(jsonb_agg(${qualifiedValuesTableName}.value), '[]'::jsonb) from ${qualifiedValuesTableName} where ${qualifiedValuesTableName}.parent_id = ${parentTableName}.id)`;
297
+ }
298
+ return `(select json_group_array(${qualifiedValuesTableName}.value) from ${qualifiedValuesTableName} where ${qualifiedValuesTableName}.parent_id = ${parentTableName}.id)`;
299
+ };
300
+
301
+ //# sourceMappingURL=buildPolymorphicJoinWhere.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/find/buildPolymorphicJoinWhere.ts"],"sourcesContent":["import type { Column, SQL } from 'drizzle-orm'\n\nimport { and, getTableName, isNotNull, isNull, or, sql } from 'drizzle-orm'\nimport { type FlattenedField, type Operator, QueryError, type Where } from 'payload'\nimport toSnakeCase from 'to-snake-case'\n\nimport type { DrizzleResolvedOperator } from '../queries/operatorMap.js'\nimport type { DrizzleAdapter, GenericTable } from '../types.js'\nimport type {\n PolymorphicJoinWherePlan,\n ScalarWhereField,\n WherePathPlan,\n} from './createPolymorphicJoinWherePlan.js'\n\nimport { buildOperatorConstraint } from '../queries/buildOperatorConstraint.js'\nimport { sanitizeQueryValue } from '../queries/sanitizeQueryValue.js'\n\nconst supportedJSONQueryOperators = new Set(['contains', 'equals', 'exists', 'in', 'like'])\n\ntype BuildPolymorphicJoinWhereArgs = {\n adapter: DrizzleAdapter\n collection: string\n locale?: string\n table: GenericTable\n where: Where\n wherePlan: PolymorphicJoinWherePlan\n}\n\ntype ResolvedWherePath =\n | {\n column: Column | SQL\n fieldContext?: ScalarWhereField\n pathPlan: WherePathPlan\n queryValueContext: ScalarWhereField\n type: 'scalar'\n }\n | {\n fieldContext: FlattenedField\n jsonExpression: string\n pathPlan: WherePathPlan\n type: 'hasManySelect'\n }\n | {\n pathPlan: WherePathPlan\n type: 'invalid'\n }\n\n/**\n * Builds a where clause for one collection before the polymorphic branches are combined. A field\n * that is absent from this collection resolves to SQL NULL, and relationTo resolves to the current\n * collection slug.\n */\nexport const buildPolymorphicJoinWhere = ({\n adapter,\n collection,\n locale,\n table,\n where,\n wherePlan,\n}: BuildPolymorphicJoinWhereArgs): SQL | undefined => {\n const constraints: SQL[] = []\n\n for (const key in where) {\n if (['AND', 'OR'].includes(key.toUpperCase())) {\n if (!Array.isArray(where[key])) {\n throw new QueryError([{ path: key }])\n }\n\n const combine = key.toUpperCase() === 'AND' ? and : or\n const nestedConstraints = where[key].map((nestedWhere) =>\n buildPolymorphicJoinWhere({\n adapter,\n collection,\n locale,\n table,\n where: nestedWhere,\n wherePlan,\n }),\n )\n const nestedCondition = combine(...nestedConstraints)\n\n if (nestedCondition) {\n constraints.push(nestedCondition)\n }\n\n continue\n }\n\n const resolvedPath = resolveWherePath({\n adapter,\n collection,\n schemaPath: key,\n table,\n wherePlan,\n })\n\n for (let payloadOperator of Object.keys(where[key])) {\n const originalOperator = payloadOperator as Operator\n let value = where[key][payloadOperator]\n\n if (resolvedPath.type === 'invalid') {\n throw new QueryError([{ path: `${key}.${payloadOperator}` }])\n }\n\n if (resolvedPath.type === 'hasManySelect') {\n if (!supportedJSONQueryOperators.has(payloadOperator)) {\n throw new QueryError([{ path: `${key}.${payloadOperator}` }])\n }\n\n const sanitizedQueryValue = sanitizeQueryValue({\n adapter,\n field: resolvedPath.fieldContext,\n isUUID: false,\n operator: payloadOperator,\n relationOrPath: key,\n val: value,\n })\n\n if (sanitizedQueryValue === null) {\n throw new QueryError([{ path: `${key}.${originalOperator}` }])\n }\n\n if (sanitizedQueryValue.columns) {\n throw new QueryError([{ path: `${key}.${originalOperator}` }])\n }\n\n value = sanitizedQueryValue.value\n\n if (payloadOperator === 'in' && Array.isArray(value) && value.length === 0) {\n constraints.push(sql.raw('false'))\n continue\n }\n\n const jsonQueryOperator =\n payloadOperator === 'exists' ? 'exists' : sanitizedQueryValue.operator\n\n constraints.push(\n sql.raw(\n adapter.createJSONQuery({\n column: resolvedPath.jsonExpression,\n operator: jsonQueryOperator,\n pathSegments: [resolvedPath.pathPlan.columnPath],\n value,\n }),\n ),\n )\n continue\n }\n\n if (payloadOperator === '$raw') {\n if (typeof value !== 'string') {\n throw new QueryError([{ path: `${key}.${payloadOperator}` }])\n }\n\n constraints.push(sql.raw(value))\n continue\n }\n\n const { column, fieldContext, queryValueContext } = resolvedPath\n\n if (\n payloadOperator === 'like' &&\n (queryValueContext.field.type === 'number' ||\n queryValueContext.field.type === 'relationship' ||\n queryValueContext.field.type === 'upload' ||\n queryValueContext.isUUID)\n ) {\n payloadOperator = 'equals'\n }\n\n const sanitizedQueryValue = sanitizeQueryValue({\n adapter,\n field: queryValueContext.field,\n isUUID: queryValueContext.isUUID,\n operator: payloadOperator,\n relationOrPath: key,\n val: value,\n })\n\n if (sanitizedQueryValue === null) {\n throw new QueryError([{ path: `${key}.${originalOperator}` }])\n }\n\n if (sanitizedQueryValue.columns) {\n throw new QueryError([{ path: `${key}.${originalOperator}` }])\n }\n\n payloadOperator = sanitizedQueryValue.operator\n value = sanitizedQueryValue.value\n\n if (!(payloadOperator in adapter.operators)) {\n throw new QueryError([{ path: `${key}.${originalOperator}` }])\n }\n\n const resolvedOperator = payloadOperator as DrizzleResolvedOperator\n const operator = adapter.operators[resolvedOperator]\n const buildColumnConstraint = (constraintValue: unknown) => {\n if (!fieldContext) {\n return operator(column, constraintValue)\n }\n\n return buildOperatorConstraint({\n adapter,\n column,\n field: fieldContext.field,\n locale,\n originalOperator,\n path: key,\n resolvedOperator,\n value: constraintValue,\n })\n }\n\n if (originalOperator === 'equals' && value === null) {\n constraints.push(isNull(column))\n continue\n }\n\n if (originalOperator === 'not_equals') {\n if (value === null) {\n constraints.push(isNotNull(column))\n } else {\n const notEqualsConstraint = or(isNull(column), buildColumnConstraint(value))\n\n if (notEqualsConstraint) {\n constraints.push(notEqualsConstraint)\n }\n }\n continue\n }\n\n if (originalOperator === 'in' && Array.isArray(value) && value.includes(null)) {\n const nonNullValues = value.filter((item) => item !== null)\n const inConstraint = buildColumnConstraint(nonNullValues)\n const nullAwareInConstraint = or(isNull(column), inConstraint)\n\n if (nullAwareInConstraint) {\n constraints.push(nullAwareInConstraint)\n }\n continue\n }\n\n if (payloadOperator === 'like' && typeof value === 'string') {\n const wordConstraints = value.split(' ').map((word) => buildColumnConstraint(`%${word}%`))\n const wordCondition = and(...wordConstraints)\n\n if (wordCondition) {\n constraints.push(wordCondition)\n }\n continue\n }\n\n constraints.push(buildColumnConstraint(value))\n }\n }\n\n return and(...constraints)\n}\n\nconst resolveWherePath = ({\n adapter,\n collection,\n schemaPath,\n table,\n wherePlan,\n}: {\n schemaPath: string\n} & Omit<BuildPolymorphicJoinWhereArgs, 'locale' | 'where'>): ResolvedWherePath => {\n const pathPlan = wherePlan.get(schemaPath)\n\n if (!pathPlan) {\n throw new QueryError([{ path: schemaPath }])\n }\n\n if (pathPlan.type === 'invalid') {\n return { type: 'invalid', pathPlan }\n }\n\n if (schemaPath === 'relationTo') {\n return {\n type: 'scalar',\n column: sql`${collection}`,\n pathPlan,\n queryValueContext: {\n type: 'scalar',\n field: { name: 'relationTo', type: 'text' },\n isUUID: false,\n },\n }\n }\n\n if (pathPlan.type === 'hasManySelect') {\n const fieldContext = [...pathPlan.fieldsByCollection.values()].find(\n (field) => field.type === 'hasManySelect',\n )?.field\n\n if (!fieldContext) {\n return { type: 'invalid', pathPlan }\n }\n\n return {\n type: 'hasManySelect',\n fieldContext,\n jsonExpression: getHasManySelectExpression({\n adapter,\n collection,\n pathPlan,\n table,\n }),\n pathPlan,\n }\n }\n\n const collectionField = pathPlan.fieldsByCollection.get(collection)\n const fieldContext = collectionField?.type === 'scalar' ? collectionField : undefined\n const queryValueContext =\n fieldContext ??\n [...pathPlan.fieldsByCollection.values()].find(\n (field): field is ScalarWhereField => field.type === 'scalar',\n )\n\n if (!queryValueContext) {\n return { type: 'invalid', pathPlan }\n }\n\n return {\n type: 'scalar',\n column: fieldContext ? table[pathPlan.columnPath] : sql`null`,\n fieldContext,\n pathPlan,\n queryValueContext,\n }\n}\n\nconst getHasManySelectExpression = ({\n adapter,\n collection,\n pathPlan,\n table,\n}: {\n adapter: DrizzleAdapter\n collection: string\n pathPlan: WherePathPlan\n table: GenericTable\n}): string => {\n if (pathPlan.fieldsByCollection.get(collection)?.type !== 'hasManySelect') {\n return adapter.name === 'postgres' ? `'[]'::jsonb` : `'[]'`\n }\n\n const selectTablePath = pathPlan.schemaPath\n .split('.')\n .map((pathSegment) => toSnakeCase(pathSegment))\n .join('_')\n const valuesTableName = adapter.tableNameMap.get(`${toSnakeCase(collection)}_${selectTablePath}`)\n\n if (!valuesTableName) {\n throw new Error(\n `Polymorphic join collection \"${collection}\" has no value table for \"${pathPlan.schemaPath}\"`,\n )\n }\n\n let qualifiedValuesTableName = valuesTableName\n let parentTableName = getTableName(table)\n\n if (adapter.schemaName) {\n qualifiedValuesTableName = `\"${adapter.schemaName}\".\"${valuesTableName}\"`\n parentTableName = `\"${adapter.schemaName}\".\"${parentTableName}\"`\n }\n\n if (adapter.name === 'postgres') {\n return `(select coalesce(jsonb_agg(${qualifiedValuesTableName}.value), '[]'::jsonb) from ${qualifiedValuesTableName} where ${qualifiedValuesTableName}.parent_id = ${parentTableName}.id)`\n }\n\n return `(select json_group_array(${qualifiedValuesTableName}.value) from ${qualifiedValuesTableName} where ${qualifiedValuesTableName}.parent_id = ${parentTableName}.id)`\n}\n"],"names":["and","getTableName","isNotNull","isNull","or","sql","QueryError","toSnakeCase","buildOperatorConstraint","sanitizeQueryValue","supportedJSONQueryOperators","Set","buildPolymorphicJoinWhere","adapter","collection","locale","table","where","wherePlan","constraints","key","includes","toUpperCase","Array","isArray","path","combine","nestedConstraints","map","nestedWhere","nestedCondition","push","resolvedPath","resolveWherePath","schemaPath","payloadOperator","Object","keys","originalOperator","value","type","has","sanitizedQueryValue","field","fieldContext","isUUID","operator","relationOrPath","val","columns","length","raw","jsonQueryOperator","createJSONQuery","column","jsonExpression","pathSegments","pathPlan","columnPath","queryValueContext","operators","resolvedOperator","buildColumnConstraint","constraintValue","notEqualsConstraint","nonNullValues","filter","item","inConstraint","nullAwareInConstraint","wordConstraints","split","word","wordCondition","get","name","fieldsByCollection","values","find","getHasManySelectExpression","collectionField","undefined","selectTablePath","pathSegment","join","valuesTableName","tableNameMap","Error","qualifiedValuesTableName","parentTableName","schemaName"],"mappings":"AAEA,SAASA,GAAG,EAAEC,YAAY,EAAEC,SAAS,EAAEC,MAAM,EAAEC,EAAE,EAAEC,GAAG,QAAQ,cAAa;AAC3E,SAA6CC,UAAU,QAAoB,UAAS;AACpF,OAAOC,iBAAiB,gBAAe;AAUvC,SAASC,uBAAuB,QAAQ,wCAAuC;AAC/E,SAASC,kBAAkB,QAAQ,mCAAkC;AAErE,MAAMC,8BAA8B,IAAIC,IAAI;IAAC;IAAY;IAAU;IAAU;IAAM;CAAO;AA8B1F;;;;CAIC,GACD,OAAO,MAAMC,4BAA4B,CAAC,EACxCC,OAAO,EACPC,UAAU,EACVC,MAAM,EACNC,KAAK,EACLC,KAAK,EACLC,SAAS,EACqB;IAC9B,MAAMC,cAAqB,EAAE;IAE7B,IAAK,MAAMC,OAAOH,MAAO;QACvB,IAAI;YAAC;YAAO;SAAK,CAACI,QAAQ,CAACD,IAAIE,WAAW,KAAK;YAC7C,IAAI,CAACC,MAAMC,OAAO,CAACP,KAAK,CAACG,IAAI,GAAG;gBAC9B,MAAM,IAAId,WAAW;oBAAC;wBAAEmB,MAAML;oBAAI;iBAAE;YACtC;YAEA,MAAMM,UAAUN,IAAIE,WAAW,OAAO,QAAQtB,MAAMI;YACpD,MAAMuB,oBAAoBV,KAAK,CAACG,IAAI,CAACQ,GAAG,CAAC,CAACC,cACxCjB,0BAA0B;oBACxBC;oBACAC;oBACAC;oBACAC;oBACAC,OAAOY;oBACPX;gBACF;YAEF,MAAMY,kBAAkBJ,WAAWC;YAEnC,IAAIG,iBAAiB;gBACnBX,YAAYY,IAAI,CAACD;YACnB;YAEA;QACF;QAEA,MAAME,eAAeC,iBAAiB;YACpCpB;YACAC;YACAoB,YAAYd;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