@payloadcms/drizzle 3.91.0-internal.6e3dc85 → 4.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/LICENSE.md +1 -1
  2. package/dist/exports/postgres.d.ts +4 -0
  3. package/dist/exports/postgres.d.ts.map +1 -1
  4. package/dist/exports/postgres.js +4 -0
  5. package/dist/exports/postgres.js.map +1 -1
  6. package/dist/exports/sqlite.d.ts +2 -0
  7. package/dist/exports/sqlite.d.ts.map +1 -1
  8. package/dist/exports/sqlite.js +2 -0
  9. package/dist/exports/sqlite.js.map +1 -1
  10. package/dist/find/buildPolymorphicJoinQuery.d.ts +2 -1
  11. package/dist/find/buildPolymorphicJoinQuery.d.ts.map +1 -1
  12. package/dist/find/buildPolymorphicJoinQuery.js +2 -1
  13. package/dist/find/buildPolymorphicJoinQuery.js.map +1 -1
  14. package/dist/find/buildPolymorphicJoinWhere.d.ts +2 -1
  15. package/dist/find/buildPolymorphicJoinWhere.d.ts.map +1 -1
  16. package/dist/find/buildPolymorphicJoinWhere.js +43 -10
  17. package/dist/find/buildPolymorphicJoinWhere.js.map +1 -1
  18. package/dist/find/createPolymorphicJoinWherePlan.js +3 -2
  19. package/dist/find/createPolymorphicJoinWherePlan.js.map +1 -1
  20. package/dist/find/traverseFields.d.ts.map +1 -1
  21. package/dist/find/traverseFields.js +2 -2
  22. package/dist/find/traverseFields.js.map +1 -1
  23. package/dist/index.d.ts +4 -11
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +2 -9
  26. package/dist/index.js.map +1 -1
  27. package/dist/migrate.d.ts.map +1 -1
  28. package/dist/migrate.js +41 -15
  29. package/dist/migrate.js.map +1 -1
  30. package/dist/migrateDown.d.ts +2 -1
  31. package/dist/migrateDown.d.ts.map +1 -1
  32. package/dist/migrateDown.js +17 -4
  33. package/dist/migrateDown.js.map +1 -1
  34. package/dist/migrateFresh.d.ts +4 -2
  35. package/dist/migrateFresh.d.ts.map +1 -1
  36. package/dist/migrateFresh.js +26 -9
  37. package/dist/migrateFresh.js.map +1 -1
  38. package/dist/migrateRefresh.d.ts +2 -1
  39. package/dist/migrateRefresh.d.ts.map +1 -1
  40. package/dist/migrateRefresh.js +20 -5
  41. package/dist/migrateRefresh.js.map +1 -1
  42. package/dist/migrateReset.d.ts +2 -1
  43. package/dist/migrateReset.d.ts.map +1 -1
  44. package/dist/migrateReset.js +18 -4
  45. package/dist/migrateReset.js.map +1 -1
  46. package/dist/migrateStatus.d.ts +2 -1
  47. package/dist/migrateStatus.d.ts.map +1 -1
  48. package/dist/migrateStatus.js +11 -6
  49. package/dist/migrateStatus.js.map +1 -1
  50. package/dist/postgres/predefinedMigrations/localize-status/index.d.ts +11 -0
  51. package/dist/postgres/predefinedMigrations/localize-status/index.d.ts.map +1 -0
  52. package/dist/postgres/predefinedMigrations/localize-status/index.js +296 -0
  53. package/dist/postgres/predefinedMigrations/localize-status/index.js.map +1 -0
  54. package/dist/postgres/predefinedMigrations/localize-status/migrateMainCollection.d.ts +13 -0
  55. package/dist/postgres/predefinedMigrations/localize-status/migrateMainCollection.d.ts.map +1 -0
  56. package/dist/postgres/predefinedMigrations/localize-status/migrateMainCollection.js +51 -0
  57. package/dist/postgres/predefinedMigrations/localize-status/migrateMainCollection.js.map +1 -0
  58. package/dist/postgres/predefinedMigrations/localize-status/migrateMainGlobal.d.ts +13 -0
  59. package/dist/postgres/predefinedMigrations/localize-status/migrateMainGlobal.d.ts.map +1 -0
  60. package/dist/postgres/predefinedMigrations/localize-status/migrateMainGlobal.js +54 -0
  61. package/dist/postgres/predefinedMigrations/localize-status/migrateMainGlobal.js.map +1 -0
  62. package/dist/postgres/predefinedMigrations/sizes-to-variants/index.d.ts +35 -0
  63. package/dist/postgres/predefinedMigrations/sizes-to-variants/index.d.ts.map +1 -0
  64. package/dist/postgres/predefinedMigrations/sizes-to-variants/index.js +185 -0
  65. package/dist/postgres/predefinedMigrations/sizes-to-variants/index.js.map +1 -0
  66. package/dist/postgres/predefinedMigrations/v2-v3/fetchAndResave/index.d.ts.map +1 -1
  67. package/dist/postgres/predefinedMigrations/v2-v3/fetchAndResave/index.js +8 -4
  68. package/dist/postgres/predefinedMigrations/v2-v3/fetchAndResave/index.js.map +1 -1
  69. package/dist/postgres/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.d.ts.map +1 -1
  70. package/dist/postgres/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.js.map +1 -1
  71. package/dist/postgres/predefinedMigrations/v2-v3/index.js +1 -1
  72. package/dist/postgres/predefinedMigrations/v2-v3/index.js.map +1 -1
  73. package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.d.ts +15 -0
  74. package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.d.ts.map +1 -0
  75. package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.js +25 -0
  76. package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.js.map +1 -0
  77. package/dist/postgres/query/postgresUnaccent.d.ts +13 -0
  78. package/dist/postgres/query/postgresUnaccent.d.ts.map +1 -0
  79. package/dist/postgres/query/postgresUnaccent.js +40 -0
  80. package/dist/postgres/query/postgresUnaccent.js.map +1 -0
  81. package/dist/postgres/schema/geometryColumn.d.ts +2 -2
  82. package/dist/postgres/types.d.ts +13 -2
  83. package/dist/postgres/types.d.ts.map +1 -1
  84. package/dist/postgres/types.js.map +1 -1
  85. package/dist/queries/addJoinTable.d.ts +1 -1
  86. package/dist/queries/buildOperatorConstraint.d.ts +22 -0
  87. package/dist/queries/buildOperatorConstraint.d.ts.map +1 -0
  88. package/dist/queries/buildOperatorConstraint.js +63 -0
  89. package/dist/queries/buildOperatorConstraint.js.map +1 -0
  90. package/dist/queries/buildOrderBy.d.ts +1 -1
  91. package/dist/queries/buildOrderBy.d.ts.map +1 -1
  92. package/dist/queries/buildOrderBy.js +6 -1
  93. package/dist/queries/buildOrderBy.js.map +1 -1
  94. package/dist/queries/getTableColumnFromPath.d.ts +12 -3
  95. package/dist/queries/getTableColumnFromPath.d.ts.map +1 -1
  96. package/dist/queries/getTableColumnFromPath.js +52 -29
  97. package/dist/queries/getTableColumnFromPath.js.map +1 -1
  98. package/dist/queries/operatorMap.d.ts +7 -3
  99. package/dist/queries/operatorMap.d.ts.map +1 -1
  100. package/dist/queries/operatorMap.js.map +1 -1
  101. package/dist/queries/parseParams.d.ts.map +1 -1
  102. package/dist/queries/parseParams.js +226 -36
  103. package/dist/queries/parseParams.js.map +1 -1
  104. package/dist/queries/resolveRelationshipPath.d.ts +36 -0
  105. package/dist/queries/resolveRelationshipPath.d.ts.map +1 -0
  106. package/dist/queries/resolveRelationshipPath.js +66 -0
  107. package/dist/queries/resolveRelationshipPath.js.map +1 -0
  108. package/dist/queries/validateOperatorHandlers.d.ts +8 -0
  109. package/dist/queries/validateOperatorHandlers.d.ts.map +1 -0
  110. package/dist/queries/validateOperatorHandlers.js +30 -0
  111. package/dist/queries/validateOperatorHandlers.js.map +1 -0
  112. package/dist/schema/traverseFields.d.ts.map +1 -1
  113. package/dist/schema/traverseFields.js +2 -1
  114. package/dist/schema/traverseFields.js.map +1 -1
  115. package/dist/sqlite/insert.d.ts.map +1 -1
  116. package/dist/sqlite/insert.js +4 -1
  117. package/dist/sqlite/insert.js.map +1 -1
  118. package/dist/sqlite/predefinedMigrations/localize-status/index.d.ts +28 -0
  119. package/dist/sqlite/predefinedMigrations/localize-status/index.d.ts.map +1 -0
  120. package/dist/sqlite/predefinedMigrations/localize-status/index.js +198 -0
  121. package/dist/sqlite/predefinedMigrations/localize-status/index.js.map +1 -0
  122. package/dist/sqlite/predefinedMigrations/localize-status/migrateMainCollection.d.ts +12 -0
  123. package/dist/sqlite/predefinedMigrations/localize-status/migrateMainCollection.d.ts.map +1 -0
  124. package/dist/sqlite/predefinedMigrations/localize-status/migrateMainCollection.js +24 -0
  125. package/dist/sqlite/predefinedMigrations/localize-status/migrateMainCollection.js.map +1 -0
  126. package/dist/sqlite/predefinedMigrations/localize-status/migrateMainGlobal.d.ts +12 -0
  127. package/dist/sqlite/predefinedMigrations/localize-status/migrateMainGlobal.d.ts.map +1 -0
  128. package/dist/sqlite/predefinedMigrations/localize-status/migrateMainGlobal.js +28 -0
  129. package/dist/sqlite/predefinedMigrations/localize-status/migrateMainGlobal.js.map +1 -0
  130. package/dist/sqlite/predefinedMigrations/sizes-to-variants/index.d.ts +15 -0
  131. package/dist/sqlite/predefinedMigrations/sizes-to-variants/index.d.ts.map +1 -0
  132. package/dist/sqlite/predefinedMigrations/sizes-to-variants/index.js +114 -0
  133. package/dist/sqlite/predefinedMigrations/sizes-to-variants/index.js.map +1 -0
  134. package/dist/transform/read/traverseFields.js +2 -2
  135. package/dist/transform/read/traverseFields.js.map +1 -1
  136. package/dist/transform/write/blocks.js +1 -1
  137. package/dist/transform/write/blocks.js.map +1 -1
  138. package/dist/transform/write/traverseFields.js +1 -2
  139. package/dist/transform/write/traverseFields.js.map +1 -1
  140. package/dist/types.d.ts +50 -6
  141. package/dist/types.d.ts.map +1 -1
  142. package/dist/types.js +1 -3
  143. package/dist/types.js.map +1 -1
  144. package/dist/updateJobs.d.ts.map +1 -1
  145. package/dist/updateJobs.js +37 -0
  146. package/dist/updateJobs.js.map +1 -1
  147. package/dist/upsertRow/index.d.ts.map +1 -1
  148. package/dist/upsertRow/index.js +5 -2
  149. package/dist/upsertRow/index.js.map +1 -1
  150. package/dist/upsertRow/insertArrays.d.ts.map +1 -1
  151. package/dist/upsertRow/insertArrays.js +2 -1
  152. package/dist/upsertRow/insertArrays.js.map +1 -1
  153. package/dist/utilities/buildCreateMigration.d.ts.map +1 -1
  154. package/dist/utilities/buildCreateMigration.js +12 -8
  155. package/dist/utilities/buildCreateMigration.js.map +1 -1
  156. package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.d.ts +15 -0
  157. package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.d.ts.map +1 -0
  158. package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.js +110 -0
  159. package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.js.map +1 -0
  160. package/dist/utilities/checkTruncatedIdentifiers.d.ts +1 -1
  161. package/dist/utilities/createSchemaGenerator.d.ts.map +1 -1
  162. package/dist/utilities/createSchemaGenerator.js +3 -0
  163. package/dist/utilities/createSchemaGenerator.js.map +1 -1
  164. package/dist/utilities/getPrimaryDb.d.ts +1 -1
  165. package/dist/utilities/getSizesToVariantsRenames.d.ts +54 -0
  166. package/dist/utilities/getSizesToVariantsRenames.d.ts.map +1 -0
  167. package/dist/utilities/getSizesToVariantsRenames.js +251 -0
  168. package/dist/utilities/getSizesToVariantsRenames.js.map +1 -0
  169. package/dist/utilities/getTransaction.d.ts +1 -1
  170. package/dist/utilities/getTransaction.d.ts.map +1 -1
  171. package/dist/utilities/validateExistingBlockIsIdentical.d.ts +1 -4
  172. package/dist/utilities/validateExistingBlockIsIdentical.d.ts.map +1 -1
  173. package/dist/utilities/validateExistingBlockIsIdentical.js.map +1 -1
  174. package/package.json +6 -11
  175. package/dist/exports/types-deprecated.d.ts +0 -150
  176. package/dist/exports/types-deprecated.d.ts.map +0 -1
  177. package/dist/exports/types-deprecated.js +0 -5
  178. package/dist/exports/types-deprecated.js.map +0 -1
  179. package/dist/find/buildPolymorphicJoinQuery.spec.js +0 -384
  180. package/dist/find/buildPolymorphicJoinQuery.spec.js.map +0 -1
  181. package/dist/find/buildPolymorphicJoinWhere.spec.js +0 -762
  182. package/dist/find/buildPolymorphicJoinWhere.spec.js.map +0 -1
  183. package/dist/find/chainMethods.d.ts +0 -20
  184. package/dist/find/chainMethods.d.ts.map +0 -1
  185. package/dist/find/chainMethods.js +0 -16
  186. package/dist/find/chainMethods.js.map +0 -1
  187. package/dist/find/createPolymorphicJoinWherePlan.spec.js +0 -897
  188. package/dist/find/createPolymorphicJoinWherePlan.spec.js.map +0 -1
  189. package/dist/schema/buildRawSchema.spec.js +0 -231
  190. package/dist/schema/buildRawSchema.spec.js.map +0 -1
  191. package/dist/sqlite/createJSONQuery/index.spec.js +0 -28
  192. package/dist/sqlite/createJSONQuery/index.spec.js.map +0 -1
  193. package/dist/updateOne.spec.js +0 -84
  194. package/dist/updateOne.spec.js.map +0 -1
  195. package/dist/upsertRow/conditionalUpdate.spec.js +0 -61
  196. package/dist/upsertRow/conditionalUpdate.spec.js.map +0 -1
  197. package/dist/upsertRow/handleUpsertError.spec.js +0 -42
  198. package/dist/upsertRow/handleUpsertError.spec.js.map +0 -1
  199. package/dist/utilities/checkTruncatedIdentifiers.spec.js +0 -301
  200. package/dist/utilities/checkTruncatedIdentifiers.spec.js.map +0 -1
  201. package/dist/utilities/isValidStringID.spec.js +0 -15
  202. package/dist/utilities/isValidStringID.spec.js.map +0 -1
  203. package/dist/utilities/validateIdentifierLength.spec.js +0 -19
  204. package/dist/utilities/validateIdentifierLength.spec.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/queries/resolveRelationshipPath.ts"],"sourcesContent":["import type { FlattenedField, RelationshipField, UploadField } from 'payload'\n\nimport type { DrizzleAdapter } from '../types.js'\n\ntype ResolvedRelationshipPath = {\n field: RelationshipField | UploadField\n isLocalized: boolean\n locale?: string\n path: string\n}\n\n/**\n * Adds a field to the path used by Drizzle's shared relationship, text, and number tables.\n * Array and block entries are stored with a numeric position, represented by `%` while querying.\n *\n * @example `blocks` becomes `blocks.%` and then `directors` becomes\n * `blocks.%.directors`.\n */\nexport function appendFieldToStoragePath({\n field,\n path = '',\n}: {\n field: FlattenedField\n path?: string\n}): string {\n const pathSegments = path ? [path.replace(/\\.$/, ''), field.name] : [field.name]\n\n if (field.type === 'array' || field.type === 'blocks') {\n pathSegments.push('%')\n }\n\n return pathSegments.join('.')\n}\n\n/**\n * Resolves a schema path to the relationship field and the path stored in the collection's shared\n * relationships table. This understands groups, tabs, arrays, blocks, and explicit locale\n * segments.\n *\n * @example `blocks.directors` resolves to the stored path `blocks.%.directors`.\n */\nexport function resolveRelationshipPath({\n adapter,\n fields,\n locale,\n parentIsLocalized,\n path,\n pathPrefix = '',\n}: {\n adapter: DrizzleAdapter\n fields: FlattenedField[]\n locale?: string\n parentIsLocalized: boolean\n path: string\n pathPrefix?: string\n}): null | ResolvedRelationshipPath {\n const localeCodes = adapter.payload.config.localization\n ? adapter.payload.config.localization.localeCodes\n : []\n const pathSegments = path.split('.')\n let currentField: FlattenedField | undefined\n let currentFields = fields\n let isLocalized = parentIsLocalized\n let resolvedPath = pathPrefix\n\n for (const segment of pathSegments) {\n const field = currentFields.find(({ name }) => name === segment)\n\n if (!field && isLocalized && localeCodes.includes(segment)) {\n locale = segment\n continue\n }\n\n if (!field) {\n return null\n }\n\n currentField = field\n resolvedPath = appendFieldToStoragePath({ field, path: resolvedPath })\n isLocalized = isLocalized || Boolean(field.localized)\n\n if ('flattenedFields' in field) {\n currentFields = field.flattenedFields\n } else if (field.type === 'blocks') {\n currentFields = field.blocks.flatMap((block) =>\n typeof block === 'string'\n ? adapter.payload.blocks[block].flattenedFields\n : block.flattenedFields,\n )\n } else {\n currentFields = []\n }\n }\n\n if (!currentField || (currentField.type !== 'relationship' && currentField.type !== 'upload')) {\n return null\n }\n\n return {\n field: currentField,\n isLocalized,\n locale,\n path: resolvedPath,\n }\n}\n"],"names":["appendFieldToStoragePath","field","path","pathSegments","replace","name","type","push","join","resolveRelationshipPath","adapter","fields","locale","parentIsLocalized","pathPrefix","localeCodes","payload","config","localization","split","currentField","currentFields","isLocalized","resolvedPath","segment","find","includes","Boolean","localized","flattenedFields","blocks","flatMap","block"],"mappings":"AAWA;;;;;;CAMC,GACD,OAAO,SAASA,yBAAyB,EACvCC,KAAK,EACLC,OAAO,EAAE,EAIV;IACC,MAAMC,eAAeD,OAAO;QAACA,KAAKE,OAAO,CAAC,OAAO;QAAKH,MAAMI,IAAI;KAAC,GAAG;QAACJ,MAAMI,IAAI;KAAC;IAEhF,IAAIJ,MAAMK,IAAI,KAAK,WAAWL,MAAMK,IAAI,KAAK,UAAU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OAAOmB;QACPE;QACAV;QACAV,MAAMqB;IACR;AACF"}
@@ -0,0 +1,8 @@
1
+ import type { DrizzleOperatorHandler } from '../types.js';
2
+ /**
3
+ * Validates operator-handler configuration before any request runs: rejects a handler that
4
+ * defines both `build` and `transformOperands`, and rejects two replacement handlers whose
5
+ * `operators` and `fieldTypes` both overlap for the same resolved operator.
6
+ */
7
+ export declare const validateOperatorHandlers: (operatorHandlers: DrizzleOperatorHandler[]) => void;
8
+ //# sourceMappingURL=validateOperatorHandlers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validateOperatorHandlers.d.ts","sourceRoot":"","sources":["../../src/queries/validateOperatorHandlers.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,sBAAsB,EAAqC,MAAM,aAAa,CAAA;AAc5F;;;;GAIG;AACH,eAAO,MAAM,wBAAwB,qBAAsB,sBAAsB,EAAE,KAAG,IA+BrF,CAAA"}
@@ -0,0 +1,30 @@
1
+ import { APIError } from 'payload';
2
+ const isReplacementHandler = (handler)=>typeof handler.build === 'function';
3
+ const fieldTypesOverlap = (a, b)=>!a.fieldTypes || !b.fieldTypes || a.fieldTypes.some((fieldType)=>b.fieldTypes.includes(fieldType));
4
+ /**
5
+ * Validates operator-handler configuration before any request runs: rejects a handler that
6
+ * defines both `build` and `transformOperands`, and rejects two replacement handlers whose
7
+ * `operators` and `fieldTypes` both overlap for the same resolved operator.
8
+ */ export const validateOperatorHandlers = (operatorHandlers)=>{
9
+ for (const handler of operatorHandlers){
10
+ if (typeof handler.build === 'function' && typeof handler.transformOperands === 'function') {
11
+ throw new APIError(`Operator handler "${handler.name}" cannot define both "build" and "transformOperands". Use "transformOperands" to adjust operands, or "build" to replace the comparison entirely.`);
12
+ }
13
+ }
14
+ const replacementHandlers = operatorHandlers.filter(isReplacementHandler);
15
+ for(let i = 0; i < replacementHandlers.length; i++){
16
+ for(let j = i + 1; j < replacementHandlers.length; j++){
17
+ const handlerA = replacementHandlers[i];
18
+ const handlerB = replacementHandlers[j];
19
+ const sharedOperators = handlerA.operators.filter((operator)=>handlerB.operators.includes(operator));
20
+ if (!sharedOperators.length) {
21
+ continue;
22
+ }
23
+ if (fieldTypesOverlap(handlerA, handlerB)) {
24
+ throw new APIError(`Operator handlers "${handlerA.name}" and "${handlerB.name}" both replace the "${sharedOperators.join('", "')}" operator for overlapping field types. Only one replacement handler may match a given resolved operator and field type.`);
25
+ }
26
+ }
27
+ }
28
+ };
29
+
30
+ //# sourceMappingURL=validateOperatorHandlers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/queries/validateOperatorHandlers.ts"],"sourcesContent":["import { APIError } from 'payload'\n\nimport type { DrizzleOperatorHandler, DrizzleOperatorReplacementHandler } from '../types.js'\n\nconst isReplacementHandler = (\n handler: DrizzleOperatorHandler,\n): handler is DrizzleOperatorReplacementHandler => typeof handler.build === 'function'\n\nconst fieldTypesOverlap = (\n a: DrizzleOperatorReplacementHandler,\n b: DrizzleOperatorReplacementHandler,\n): boolean =>\n !a.fieldTypes ||\n !b.fieldTypes ||\n a.fieldTypes.some((fieldType) => b.fieldTypes.includes(fieldType))\n\n/**\n * Validates operator-handler configuration before any request runs: rejects a handler that\n * defines both `build` and `transformOperands`, and rejects two replacement handlers whose\n * `operators` and `fieldTypes` both overlap for the same resolved operator.\n */\nexport const validateOperatorHandlers = (operatorHandlers: DrizzleOperatorHandler[]): void => {\n for (const handler of operatorHandlers) {\n if (typeof handler.build === 'function' && typeof handler.transformOperands === 'function') {\n throw new APIError(\n `Operator handler \"${handler.name}\" cannot define both \"build\" and \"transformOperands\". Use \"transformOperands\" to adjust operands, or \"build\" to replace the comparison entirely.`,\n )\n }\n }\n\n const replacementHandlers = operatorHandlers.filter(isReplacementHandler)\n\n for (let i = 0; i < replacementHandlers.length; i++) {\n for (let j = i + 1; j < replacementHandlers.length; j++) {\n const handlerA = replacementHandlers[i]\n const handlerB = replacementHandlers[j]\n\n const sharedOperators = handlerA.operators.filter((operator) =>\n handlerB.operators.includes(operator),\n )\n\n if (!sharedOperators.length) {\n continue\n }\n\n if (fieldTypesOverlap(handlerA, handlerB)) {\n throw new APIError(\n `Operator handlers \"${handlerA.name}\" and \"${handlerB.name}\" both replace the \"${sharedOperators.join('\", \"')}\" operator for overlapping field types. Only one replacement handler may match a given resolved operator and field type.`,\n )\n }\n }\n }\n}\n"],"names":["APIError","isReplacementHandler","handler","build","fieldTypesOverlap","a","b","fieldTypes","some","fieldType","includes","validateOperatorHandlers","operatorHandlers","transformOperands","name","replacementHandlers","filter","i","length","j","handlerA","handlerB","sharedOperators","operators","operator","join"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,UAAS;AAIlC,MAAMC,uBAAuB,CAC3BC,UACiD,OAAOA,QAAQC,KAAK,KAAK;AAE5E,MAAMC,oBAAoB,CACxBC,GACAC,IAEA,CAACD,EAAEE,UAAU,IACb,CAACD,EAAEC,UAAU,IACbF,EAAEE,UAAU,CAACC,IAAI,CAAC,CAACC,YAAcH,EAAEC,UAAU,CAACG,QAAQ,CAACD;AAEzD;;;;CAIC,GACD,OAAO,MAAME,2BAA2B,CAACC;IACvC,KAAK,MAAMV,WAAWU,iBAAkB;QACtC,IAAI,OAAOV,QAAQC,KAAK,KAAK,cAAc,OAAOD,QAAQW,iBAAiB,KAAK,YAAY;YAC1F,MAAM,IAAIb,SACR,CAAC,kBAAkB,EAAEE,QAAQY,IAAI,CAAC,gJAAgJ,CAAC;QAEvL;IACF;IAEA,MAAMC,sBAAsBH,iBAAiBI,MAAM,CAACf;IAEpD,IAAK,IAAIgB,IAAI,GAAGA,IAAIF,oBAAoBG,MAAM,EAAED,IAAK;QACnD,IAAK,IAAIE,IAAIF,IAAI,GAAGE,IAAIJ,oBAAoBG,MAAM,EAAEC,IAAK;YACvD,MAAMC,WAAWL,mBAAmB,CAACE,EAAE;YACvC,MAAMI,WAAWN,mBAAmB,CAACI,EAAE;YAEvC,MAAMG,kBAAkBF,SAASG,SAAS,CAACP,MAAM,CAA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AAsB,CAAC,EAAE,OAAO,CAAA;IAChC,aAAa,CAAC,EAAE,OAAO,CAAA;IACvB,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,MAAM,EAAE,cAAc,EAAE,CAAA;IACxB,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;IACjC,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAA;IACzC,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;IACxC,YAAY,EAAE,MAAM,CAAA;IACpB,iBAAiB,EAAE,OAAO,CAAA;IAC1B,eAAe,EAAE,MAAM,CAAA;IACvB,aAAa,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;IAC1B,gBAAgB,EAAE,WAAW,CAAA;IAC7B,oBAAoB,CAAC,EAAE,WAAW,CAAA;IAClC,kBAAkB,EAAE,MAAM,CAAA;IAC1B,aAAa,EAAE,MAAM,CAAA;IACrB,WAAW,EAAE,WAAW,CAAA;IACxB,mBAAmB,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;IAChC,QAAQ,EAAE,OAAO,CAAA;IACjB;;;OAGG;IACH,2BAA2B,CAAC,EAAE,OAAO,CAAA;CACtC,CAAA;AAED,KAAK,MAAM,GAAG;IACZ,iBAAiB,EAAE,OAAO,CAAA;IAC1B,2BAA2B,EAAE,OAAO,CAAA;IACpC,yBAAyB,EAAE,OAAO,CAAA;IAClC,6BAA6B,EAAE,OAAO,CAAA;IACtC,kBAAkB,EAAE,OAAO,GAAG,OAAO,CAAA;IACrC,gBAAgB,EAAE,OAAO,GAAG,OAAO,CAAA;CACpC,CAAA;AAED,eAAO,MAAM,cAAc,sZA0BxB,IAAI,KAAG,MAs7BT,CAAA"}
@@ -259,7 +259,7 @@ export const traverseFields = ({ adapter, blocksTableNameMap, columnPrefix, colu
259
259
  break;
260
260
  }
261
261
  const disableNotNullFromHere = Boolean(field.admin?.condition) || disableNotNull;
262
- (field.blockReferences ?? field.blocks).forEach((_block)=>{
262
+ field.blocks.forEach((_block)=>{
263
263
  const block = typeof _block === 'string' ? adapter.payload.blocks[_block] : _block;
264
264
  let blockTableName = createTableName({
265
265
  adapter,
@@ -462,6 +462,7 @@ export const traverseFields = ({ adapter, blocksTableNameMap, columnPrefix, colu
462
462
  }
463
463
  case 'code':
464
464
  case 'email':
465
+ case 'slug':
465
466
  case 'textarea':
466
467
  {
467
468
  targetTable[fieldName] = withDefault({
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/schema/traverseFields.ts"],"sourcesContent":["import type { FlattenedField } from 'payload'\n\nimport { InvalidConfiguration } from 'payload'\nimport {\n fieldAffectsData,\n fieldIsVirtual,\n fieldShouldBeLocalized,\n optionIsObject,\n} from 'payload/shared'\nimport toSnakeCase from 'to-snake-case'\n\nimport type {\n DrizzleAdapter,\n IDType,\n RawColumn,\n RawForeignKey,\n RawIndex,\n RawRelation,\n RelationMap,\n SetColumnID,\n} from '../types.js'\n\nimport { createTableName } from '../createTableName.js'\nimport { buildIndexName } from '../utilities/buildIndexName.js'\nimport { getArrayRelationName } from '../utilities/getArrayRelationName.js'\nimport { hasLocalesTable } from '../utilities/hasLocalesTable.js'\nimport { isUUIDType } from '../utilities/isUUIDType.js'\nimport {\n InternalBlockTableNameIndex,\n setInternalBlockIndex,\n validateExistingBlockIsIdentical,\n} from '../utilities/validateExistingBlockIsIdentical.js'\nimport { buildTable } from './build.js'\nimport { idToUUID } from './idToUUID.js'\nimport { withDefault } from './withDefault.js'\n\ntype Args = {\n adapter: DrizzleAdapter\n blocksTableNameMap: Record<string, number>\n columnPrefix?: string\n columns: Record<string, RawColumn>\n disableNotNull: boolean\n disableRelsTableUnique?: boolean\n disableUnique?: boolean\n fieldPrefix?: string\n fields: FlattenedField[]\n forceLocalized?: boolean\n indexes: Record<string, RawIndex>\n localesColumns: Record<string, RawColumn>\n localesIndexes: Record<string, RawIndex>\n newTableName: string\n parentIsLocalized: boolean\n parentTableName: string\n relationships: Set<string>\n relationsToBuild: RelationMap\n rootRelationsToBuild?: RelationMap\n rootTableIDColType: IDType\n rootTableName: string\n setColumnID: SetColumnID\n uniqueRelationships: Set<string>\n versions: boolean\n /**\n * Tracks whether or not this table is built\n * from the result of a localized array or block field at some point\n */\n withinLocalizedArrayOrBlock?: boolean\n}\n\ntype Result = {\n hasLocalizedField: boolean\n hasLocalizedManyNumberField: boolean\n hasLocalizedManyTextField: boolean\n hasLocalizedRelationshipField: boolean\n hasManyNumberField: 'index' | boolean\n hasManyTextField: 'index' | boolean\n}\n\nexport const traverseFields = ({\n adapter,\n blocksTableNameMap,\n columnPrefix,\n columns,\n disableNotNull,\n disableRelsTableUnique,\n disableUnique = false,\n fieldPrefix,\n fields,\n forceLocalized,\n indexes,\n localesColumns,\n localesIndexes,\n newTableName,\n parentIsLocalized,\n parentTableName,\n relationships,\n relationsToBuild,\n rootRelationsToBuild,\n rootTableIDColType,\n rootTableName,\n setColumnID,\n uniqueRelationships,\n versions,\n withinLocalizedArrayOrBlock,\n}: Args): Result => {\n const throwValidationError = true\n let hasLocalizedField = false\n let hasLocalizedRelationshipField = false\n let hasManyTextField: 'index' | boolean = false\n let hasLocalizedManyTextField = false\n let hasManyNumberField: 'index' | boolean = false\n let hasLocalizedManyNumberField = false\n\n let parentIDColType: IDType = 'integer'\n\n const idColumn = columns.id\n\n if (idColumn && ['numeric', 'text', 'uuid', 'varchar'].includes(idColumn.type)) {\n parentIDColType = idColumn.type as IDType\n }\n\n fields.forEach((field) => {\n if ('name' in field && field.name === 'id') {\n return\n }\n if (fieldIsVirtual(field)) {\n return\n }\n\n let targetTable = columns\n let targetIndexes = indexes\n\n const columnName = `${columnPrefix || ''}${field.name[0] === '_' ? '_' : ''}${toSnakeCase(\n field.name,\n )}`\n const fieldName = `${fieldPrefix?.replace('.', '_') || ''}${field.name}`\n\n const isFieldLocalized = fieldShouldBeLocalized({ field, parentIsLocalized })\n\n // If field is localized,\n // add the column to the locale table instead of main table\n if (\n adapter.payload.config.localization &&\n (isFieldLocalized || forceLocalized) &&\n field.type !== 'array' &&\n (field.type !== 'blocks' || adapter.blocksAsJSON) &&\n (('hasMany' in field && field.hasMany !== true) || !('hasMany' in field))\n ) {\n hasLocalizedField = true\n targetTable = localesColumns\n targetIndexes = localesIndexes\n }\n\n if (\n (field.unique || field.index || ['relationship', 'upload'].includes(field.type)) &&\n !['array', 'blocks', 'group'].includes(field.type) &&\n !('hasMany' in field && field.hasMany === true) &&\n !('relationTo' in field && Array.isArray(field.relationTo))\n ) {\n const unique = disableUnique !== true && field.unique\n if (unique) {\n const constraintValue = `${fieldPrefix || ''}${field.name}`\n if (!adapter.fieldConstraints?.[rootTableName]) {\n adapter.fieldConstraints[rootTableName] = {}\n }\n adapter.fieldConstraints[rootTableName][`${columnName}_idx`] = constraintValue\n }\n\n const indexName = buildIndexName({ name: `${newTableName}_${columnName}`, adapter })\n\n targetIndexes[indexName] = {\n name: indexName,\n on: isFieldLocalized ? [fieldName, '_locale'] : fieldName,\n unique,\n }\n }\n\n switch (field.type) {\n case 'array': {\n const disableNotNullFromHere = Boolean(field.admin?.condition) || disableNotNull\n\n const arrayTableName = createTableName({\n adapter,\n config: field,\n parentTableName: newTableName,\n prefix: `${newTableName}_`,\n throwValidationError,\n versionsCustomName: versions,\n })\n\n const baseColumns: Record<string, RawColumn> = {\n _order: {\n name: '_order',\n type: 'integer',\n notNull: true,\n },\n _parentID: {\n name: '_parent_id',\n type: parentIDColType,\n notNull: true,\n },\n }\n\n const baseIndexes: Record<string, RawIndex> = {\n _orderIdx: {\n name: `${arrayTableName}_order_idx`,\n on: ['_order'],\n },\n _parentIDIdx: {\n name: `${arrayTableName}_parent_id_idx`,\n on: '_parentID',\n },\n }\n\n const baseForeignKeys: Record<string, RawForeignKey> = {\n _parentIDFk: {\n name: `${arrayTableName}_parent_id_fk`,\n columns: ['_parentID'],\n foreignColumns: [\n {\n name: 'id',\n table: parentTableName,\n },\n ],\n onDelete: 'cascade',\n },\n }\n\n const isLocalized =\n Boolean(isFieldLocalized && adapter.payload.config.localization) ||\n withinLocalizedArrayOrBlock ||\n forceLocalized\n\n if (isLocalized) {\n baseColumns._locale = {\n name: '_locale',\n type: 'enum',\n locale: true,\n notNull: true,\n }\n\n baseIndexes._localeIdx = {\n name: `${arrayTableName}_locale_idx`,\n on: '_locale',\n }\n }\n\n const {\n hasLocalizedManyNumberField: subHasLocalizedManyNumberField,\n hasLocalizedManyTextField: subHasLocalizedManyTextField,\n hasLocalizedRelationshipField: subHasLocalizedRelationshipField,\n hasManyNumberField: subHasManyNumberField,\n hasManyTextField: subHasManyTextField,\n relationsToBuild: subRelationsToBuild,\n } = buildTable({\n adapter,\n baseColumns,\n baseForeignKeys,\n baseIndexes,\n blocksTableNameMap,\n disableNotNull: disableNotNullFromHere,\n disableRelsTableUnique: true,\n disableUnique,\n fields: disableUnique ? idToUUID(field.flattenedFields) : field.flattenedFields,\n parentIsLocalized: parentIsLocalized || field.localized,\n rootRelationships: relationships,\n rootRelationsToBuild,\n rootTableIDColType,\n rootTableName,\n rootUniqueRelationships: uniqueRelationships,\n setColumnID,\n tableName: arrayTableName,\n versions,\n withinLocalizedArrayOrBlock: isLocalized,\n })\n\n if (subHasLocalizedManyNumberField) {\n hasLocalizedManyNumberField = subHasLocalizedManyNumberField\n }\n\n if (subHasLocalizedRelationshipField) {\n hasLocalizedRelationshipField = subHasLocalizedRelationshipField\n }\n\n if (subHasLocalizedManyTextField) {\n hasLocalizedManyTextField = subHasLocalizedManyTextField\n }\n\n if (subHasManyTextField) {\n if (!hasManyTextField || subHasManyTextField === 'index') {\n hasManyTextField = subHasManyTextField\n }\n }\n if (subHasManyNumberField) {\n if (!hasManyNumberField || subHasManyNumberField === 'index') {\n hasManyNumberField = subHasManyNumberField\n }\n }\n\n const relationName = getArrayRelationName({\n field,\n path: fieldName,\n tableName: arrayTableName,\n })\n\n relationsToBuild.set(relationName, {\n type: 'many',\n // arrays have their own localized table, independent of the base table.\n localized: false,\n target: arrayTableName,\n })\n\n const arrayRelations: Record<string, RawRelation> = {\n _parentID: {\n type: 'one',\n fields: [\n {\n name: '_parentID',\n table: arrayTableName,\n },\n ],\n references: ['id'],\n relationName,\n to: parentTableName,\n },\n }\n\n if (\n hasLocalesTable({\n fields: field.fields,\n parentIsLocalized: parentIsLocalized || field.localized,\n })\n ) {\n arrayRelations._locales = {\n type: 'many',\n relationName: '_locales',\n to: `${arrayTableName}${adapter.localesSuffix}`,\n }\n }\n\n subRelationsToBuild.forEach(({ type, localized, target }, key) => {\n if (type === 'one') {\n const arrayWithLocalized = localized\n ? `${arrayTableName}${adapter.localesSuffix}`\n : arrayTableName\n\n arrayRelations[key] = {\n type: 'one',\n fields: [\n {\n name: key,\n table: arrayWithLocalized,\n },\n ],\n references: ['id'],\n relationName: key,\n to: target,\n }\n }\n\n if (type === 'many') {\n arrayRelations[key] = {\n type: 'many',\n relationName: key,\n to: target,\n }\n }\n })\n\n adapter.rawRelations[arrayTableName] = arrayRelations\n\n break\n }\n case 'blocks': {\n if (adapter.blocksAsJSON) {\n targetTable[fieldName] = withDefault(\n {\n name: columnName,\n type: 'jsonb',\n },\n field,\n )\n break\n }\n\n const disableNotNullFromHere = Boolean(field.admin?.condition) || disableNotNull\n\n ;(field.blockReferences ?? field.blocks).forEach((_block) => {\n const block = typeof _block === 'string' ? adapter.payload.blocks[_block] : _block\n\n let blockTableName = createTableName({\n adapter,\n config: block,\n parentTableName: rootTableName,\n prefix: `${rootTableName}_blocks_`,\n throwValidationError,\n versionsCustomName: versions,\n })\n const isLocalizedBlockTable =\n Boolean(isFieldLocalized && adapter.payload.config.localization) ||\n withinLocalizedArrayOrBlock ||\n forceLocalized\n if (typeof blocksTableNameMap[blockTableName] === 'undefined') {\n blocksTableNameMap[blockTableName] = 1\n } else if (\n !adapter.rawTables[blockTableName] ||\n !validateExistingBlockIsIdentical({\n block,\n localized: isLocalizedBlockTable,\n parentIsLocalized,\n table: adapter.rawTables[blockTableName],\n tableLocales: adapter.rawTables[`${blockTableName}${adapter.localesSuffix}`],\n })\n ) {\n blocksTableNameMap[blockTableName]++\n setInternalBlockIndex(block, blocksTableNameMap[blockTableName])\n blockTableName = `${blockTableName}_${blocksTableNameMap[blockTableName]}`\n }\n let relationName = `_blocks_${block.slug}`\n if (typeof block[InternalBlockTableNameIndex] !== 'undefined') {\n relationName = `_blocks_${block.slug}_${block[InternalBlockTableNameIndex]}`\n }\n\n if (!adapter.rawTables[blockTableName]) {\n const baseColumns: Record<string, RawColumn> = {\n _order: {\n name: '_order',\n type: 'integer',\n notNull: true,\n },\n _parentID: {\n name: '_parent_id',\n type: rootTableIDColType,\n notNull: true,\n },\n _path: {\n name: '_path',\n type: 'text',\n notNull: true,\n },\n }\n\n const baseIndexes: Record<string, RawIndex> = {\n _orderIdx: {\n name: `${blockTableName}_order_idx`,\n on: '_order',\n },\n _parentIDIdx: {\n name: `${blockTableName}_parent_id_idx`,\n on: ['_parentID'],\n },\n _pathIdx: {\n name: `${blockTableName}_path_idx`,\n on: '_path',\n },\n }\n\n const baseForeignKeys: Record<string, RawForeignKey> = {\n _parentIdFk: {\n name: `${blockTableName}_parent_id_fk`,\n columns: ['_parentID'],\n foreignColumns: [\n {\n name: 'id',\n table: rootTableName,\n },\n ],\n onDelete: 'cascade',\n },\n }\n\n if (isLocalizedBlockTable) {\n baseColumns._locale = {\n name: '_locale',\n type: 'enum',\n locale: true,\n notNull: true,\n }\n\n baseIndexes._localeIdx = {\n name: `${blockTableName}_locale_idx`,\n on: '_locale',\n }\n }\n\n const {\n hasLocalizedManyNumberField: subHasLocalizedManyNumberField,\n hasLocalizedManyTextField: subHasLocalizedManyTextField,\n hasLocalizedRelationshipField: subHasLocalizedRelationshipField,\n hasManyNumberField: subHasManyNumberField,\n hasManyTextField: subHasManyTextField,\n relationsToBuild: subRelationsToBuild,\n } = buildTable({\n adapter,\n baseColumns,\n baseForeignKeys,\n baseIndexes,\n blocksTableNameMap,\n disableNotNull: disableNotNullFromHere,\n disableRelsTableUnique: true,\n disableUnique,\n fields: disableUnique ? idToUUID(block.flattenedFields) : block.flattenedFields,\n parentIsLocalized: parentIsLocalized || field.localized,\n rootRelationships: relationships,\n rootRelationsToBuild,\n rootTableIDColType,\n rootTableName,\n rootUniqueRelationships: uniqueRelationships,\n setColumnID,\n tableName: blockTableName,\n versions,\n withinLocalizedArrayOrBlock: isLocalizedBlockTable,\n })\n\n if (subHasLocalizedManyNumberField) {\n hasLocalizedManyNumberField = subHasLocalizedManyNumberField\n }\n\n if (subHasLocalizedRelationshipField) {\n hasLocalizedRelationshipField = subHasLocalizedRelationshipField\n }\n\n if (subHasLocalizedManyTextField) {\n hasLocalizedManyTextField = subHasLocalizedManyTextField\n }\n\n if (subHasManyTextField) {\n if (!hasManyTextField || subHasManyTextField === 'index') {\n hasManyTextField = subHasManyTextField\n }\n }\n\n if (subHasManyNumberField) {\n if (!hasManyNumberField || subHasManyNumberField === 'index') {\n hasManyNumberField = subHasManyNumberField\n }\n }\n\n const blockRelations: Record<string, RawRelation> = {\n _parentID: {\n type: 'one',\n fields: [\n {\n name: '_parentID',\n table: blockTableName,\n },\n ],\n references: ['id'],\n relationName,\n to: rootTableName,\n },\n }\n\n if (\n hasLocalesTable({\n fields: block.fields,\n parentIsLocalized: parentIsLocalized || field.localized,\n })\n ) {\n blockRelations._locales = {\n type: 'many',\n relationName: '_locales',\n to: `${blockTableName}${adapter.localesSuffix}`,\n }\n }\n\n subRelationsToBuild.forEach(({ type, localized, target }, key) => {\n if (type === 'one') {\n const blockWithLocalized = localized\n ? `${blockTableName}${adapter.localesSuffix}`\n : blockTableName\n\n blockRelations[key] = {\n type: 'one',\n fields: [\n {\n name: key,\n table: blockWithLocalized,\n },\n ],\n references: ['id'],\n relationName: key,\n to: target,\n }\n }\n\n if (type === 'many') {\n blockRelations[key] = {\n type: 'many',\n relationName: key,\n to: target,\n }\n }\n })\n\n adapter.rawRelations[blockTableName] = blockRelations\n }\n\n // blocks relationships are defined from the collection or globals table down to the block, bypassing any subBlocks\n rootRelationsToBuild.set(relationName, {\n type: 'many',\n // blocks are not localized on the parent table\n localized: false,\n target: blockTableName,\n })\n })\n\n break\n }\n case 'checkbox': {\n targetTable[fieldName] = withDefault(\n {\n name: columnName,\n type: 'boolean',\n },\n field,\n )\n\n break\n }\n\n case 'code':\n case 'email':\n case 'textarea': {\n targetTable[fieldName] = withDefault(\n {\n name: columnName,\n type: 'varchar',\n },\n field,\n )\n\n break\n }\n\n case 'date': {\n targetTable[fieldName] = withDefault(\n {\n name: columnName,\n type: 'timestamp',\n mode: 'string',\n precision: 3,\n withTimezone: true,\n },\n field,\n )\n\n break\n }\n\n case 'group':\n case 'tab': {\n const disableNotNullFromHere = Boolean(field.admin?.condition) || disableNotNull\n\n const {\n hasLocalizedField: groupHasLocalizedField,\n hasLocalizedManyNumberField: groupHasLocalizedManyNumberField,\n hasLocalizedManyTextField: groupHasLocalizedManyTextField,\n hasLocalizedRelationshipField: groupHasLocalizedRelationshipField,\n hasManyNumberField: groupHasManyNumberField,\n hasManyTextField: groupHasManyTextField,\n } = traverseFields({\n adapter,\n blocksTableNameMap,\n columnPrefix: `${columnName}_`,\n columns,\n disableNotNull: disableNotNullFromHere,\n disableUnique,\n fieldPrefix: `${fieldName}.`,\n fields: field.flattenedFields,\n forceLocalized: isFieldLocalized || Boolean(forceLocalized),\n indexes,\n localesColumns,\n localesIndexes,\n newTableName: `${parentTableName}_${columnName}`,\n parentIsLocalized: parentIsLocalized || field.localized,\n parentTableName,\n relationships,\n relationsToBuild,\n rootRelationsToBuild,\n rootTableIDColType,\n rootTableName,\n setColumnID,\n uniqueRelationships,\n versions,\n withinLocalizedArrayOrBlock: withinLocalizedArrayOrBlock || isFieldLocalized,\n })\n\n if (groupHasLocalizedField) {\n hasLocalizedField = true\n }\n if (groupHasLocalizedRelationshipField) {\n hasLocalizedRelationshipField = true\n }\n if (groupHasManyTextField) {\n hasManyTextField = true\n }\n if (groupHasLocalizedManyTextField) {\n hasLocalizedManyTextField = true\n }\n if (groupHasManyNumberField) {\n hasManyNumberField = true\n }\n if (groupHasLocalizedManyNumberField) {\n hasLocalizedManyNumberField = true\n }\n break\n }\n\n case 'json':\n case 'richText': {\n targetTable[fieldName] = withDefault(\n {\n name: columnName,\n type: 'jsonb',\n },\n field,\n )\n\n break\n }\n\n case 'number': {\n if (field.hasMany) {\n const isLocalized =\n Boolean(isFieldLocalized && adapter.payload.config.localization) ||\n withinLocalizedArrayOrBlock ||\n forceLocalized\n\n if (isLocalized) {\n hasLocalizedManyNumberField = true\n }\n\n if (field.index) {\n hasManyNumberField = 'index'\n } else if (!hasManyNumberField) {\n hasManyNumberField = true\n }\n\n if (field.unique) {\n throw new InvalidConfiguration(\n 'Unique is not supported in Postgres for hasMany number fields.',\n )\n }\n } else {\n targetTable[fieldName] = withDefault(\n {\n name: columnName,\n type: 'numeric',\n },\n field,\n )\n }\n\n break\n }\n\n case 'point': {\n targetTable[fieldName] = withDefault(\n {\n name: columnName,\n type: 'geometry',\n },\n field,\n )\n\n break\n }\n\n case 'radio':\n case 'select': {\n const enumName = createTableName({\n adapter,\n config: field,\n parentTableName: newTableName,\n prefix: `enum_${newTableName}_`,\n target: 'enumName',\n throwValidationError,\n })\n\n const options = field.options.map((option) => {\n if (optionIsObject(option)) {\n return option.value\n }\n\n return option\n })\n\n if (field.type === 'select' && field.hasMany) {\n const selectTableName = createTableName({\n adapter,\n config: field,\n parentTableName: newTableName,\n prefix: `${newTableName}_`,\n throwValidationError,\n versionsCustomName: versions,\n })\n\n const baseColumns: Record<string, RawColumn> = {\n order: {\n name: 'order',\n type: 'integer',\n notNull: true,\n },\n parent: {\n name: 'parent_id',\n type: parentIDColType,\n notNull: true,\n },\n value: {\n name: 'value',\n type: 'enum',\n enumName: createTableName({\n adapter,\n config: field,\n parentTableName: newTableName,\n prefix: `enum_${newTableName}_`,\n target: 'enumName',\n throwValidationError,\n }),\n options,\n },\n }\n\n const baseIndexes: Record<string, RawIndex> = {\n orderIdx: {\n name: `${selectTableName}_order_idx`,\n on: 'order',\n },\n parentIdx: {\n name: `${selectTableName}_parent_idx`,\n on: 'parent',\n },\n }\n\n const baseForeignKeys: Record<string, RawForeignKey> = {\n parentFk: {\n name: `${selectTableName}_parent_fk`,\n columns: ['parent'],\n foreignColumns: [\n {\n name: 'id',\n table: parentTableName,\n },\n ],\n onDelete: 'cascade',\n },\n }\n\n const isLocalized =\n Boolean(isFieldLocalized && adapter.payload.config.localization) ||\n withinLocalizedArrayOrBlock ||\n forceLocalized\n\n if (isLocalized) {\n baseColumns.locale = {\n name: 'locale',\n type: 'enum',\n locale: true,\n notNull: true,\n }\n\n baseIndexes.localeIdx = {\n name: `${selectTableName}_locale_idx`,\n on: 'locale',\n }\n }\n\n if (field.index) {\n baseIndexes.value = {\n name: `${selectTableName}_value_idx`,\n on: 'value',\n }\n }\n\n buildTable({\n adapter,\n baseColumns,\n baseForeignKeys,\n baseIndexes,\n blocksTableNameMap,\n disableNotNull,\n disableUnique,\n fields: [],\n parentIsLocalized: parentIsLocalized || field.localized,\n rootTableName,\n setColumnID,\n tableName: selectTableName,\n versions,\n })\n\n relationsToBuild.set(fieldName, {\n type: 'many',\n // selects have their own localized table, independent of the base table.\n localized: false,\n target: selectTableName,\n })\n\n adapter.rawRelations[selectTableName] = {\n parent: {\n type: 'one',\n fields: [\n {\n name: 'parent',\n table: selectTableName,\n },\n ],\n references: ['id'],\n relationName: fieldName,\n to: parentTableName,\n },\n }\n } else {\n targetTable[fieldName] = withDefault(\n {\n name: columnName,\n type: 'enum',\n enumName,\n options,\n },\n field,\n )\n }\n break\n }\n\n case 'relationship':\n case 'upload':\n if (Array.isArray(field.relationTo)) {\n field.relationTo.forEach((relation) => {\n relationships.add(relation)\n if (field.unique && !disableUnique && !disableRelsTableUnique) {\n uniqueRelationships.add(relation)\n }\n })\n } else if (field.hasMany) {\n relationships.add(field.relationTo)\n if (field.unique && !disableUnique && !disableRelsTableUnique) {\n uniqueRelationships.add(field.relationTo)\n }\n } else {\n // simple relationships get a column on the targetTable with a foreign key to the relationTo table\n const relationshipConfig = adapter.payload.collections[field.relationTo].config\n\n const tableName = adapter.tableNameMap.get(toSnakeCase(field.relationTo))\n\n // get the id type of the related collection\n let colType: IDType = isUUIDType(adapter.idType) ? 'uuid' : 'integer'\n const relatedCollectionCustomID = relationshipConfig.fields.find(\n (field) => fieldAffectsData(field) && field.name === 'id',\n )\n if (relatedCollectionCustomID?.type === 'number') {\n colType = 'numeric'\n }\n if (relatedCollectionCustomID?.type === 'text') {\n colType = 'varchar'\n }\n\n // make the foreign key column for relationship using the correct id column type\n targetTable[fieldName] = {\n name: `${columnName}_id`,\n type: colType,\n reference: {\n name: 'id',\n onDelete: 'set null',\n table: tableName,\n },\n }\n\n // add relationship to table\n relationsToBuild.set(fieldName, {\n type: 'one',\n localized: adapter.payload.config.localization && (isFieldLocalized || forceLocalized),\n target: tableName,\n })\n\n // add notNull when not required\n if (!disableNotNull && field.required && !field.admin?.condition) {\n targetTable[fieldName].notNull = true\n }\n break\n }\n\n if (\n Boolean(isFieldLocalized && adapter.payload.config.localization) ||\n withinLocalizedArrayOrBlock\n ) {\n hasLocalizedRelationshipField = true\n }\n\n break\n\n case 'text': {\n if (field.hasMany) {\n const isLocalized =\n Boolean(isFieldLocalized && adapter.payload.config.localization) ||\n withinLocalizedArrayOrBlock ||\n forceLocalized\n\n if (isLocalized) {\n hasLocalizedManyTextField = true\n }\n\n if (field.index) {\n hasManyTextField = 'index'\n } else if (!hasManyTextField) {\n hasManyTextField = true\n }\n\n if (field.unique) {\n throw new InvalidConfiguration(\n 'Unique is not supported in Postgres for hasMany text fields.',\n )\n }\n } else {\n targetTable[fieldName] = withDefault(\n {\n name: columnName,\n type: 'varchar',\n },\n field,\n )\n }\n break\n }\n\n default:\n break\n }\n\n const condition = field.admin && field.admin.condition\n\n if (\n !disableNotNull &&\n targetTable[fieldName] &&\n 'required' in field &&\n field.required &&\n !condition\n ) {\n targetTable[fieldName].notNull = true\n }\n })\n\n return {\n hasLocalizedField,\n hasLocalizedManyNumberField,\n hasLocalizedManyTextField,\n hasLocalizedRelationshipField,\n hasManyNumberField,\n hasManyTextField,\n }\n}\n"],"names":["InvalidConfiguration","fieldAffectsData","fieldIsVirtual","fieldShouldBeLocalized","optionIsObject","toSnakeCase","createTableName","buildIndexName","getArrayRelationName","hasLocalesTable","isUUIDType","InternalBlockTableNameIndex","setInternalBlockIndex","validateExistingBlockIsIdentical","buildTable","idToUUID","withDefault","traverseFields","adapter","blocksTableNameMap","columnPrefix","columns","disableNotNull","disableRelsTableUnique","disableUnique","fieldPrefix","fields","forceLocalized","indexes","localesColumns","localesIndexes","newTableName","parentIsLocalized","parentTableName","relationships","relationsToBuild","rootRelationsToBuild","rootTableIDColType","rootTableName","setColumnID","uniqueRelationships","versions","withinLocalizedArrayOrBlock","throwValidationError","hasLocalizedField","hasLocalizedRelationshipField","hasManyTextField","hasLocalizedManyTextField","hasManyNumberField","hasLocalizedManyNumberField","parentIDColType","idColumn","id","includes","type","forEach","field","name","targetTable","targetIndexes","columnName","fieldName","replace","isFieldLocalized","payload","config","localization","blocksAsJSON","hasMany","unique","index","Array","isArray","relationTo","constraintValue","fieldConstraints","indexName","on","disableNotNullFromHere","Boolean","admin","condition","arrayTableName","prefix","versionsCustomName","baseColumns","_order","notNull","_parentID","baseIndexes","_orderIdx","_parentIDIdx","baseForeignKeys","_parentIDFk","foreignColumns","table","onDelete","isLocalized","_locale","locale","_localeIdx","subHasLocalizedManyNumberField","subHasLocalizedManyTextField","subHasLocalizedRelationshipField","subHasManyNumberField","subHasManyTextField","subRelationsToBuild","flattenedFields","localized","rootRelationships","rootUniqueRelationships","tableName","relationName","path","set","target","arrayRelations","references","to","_locales","localesSuffix","key","arrayWithLocalized","rawRelations","blockReferences","blocks","_block","block","blockTableName","isLocalizedBlockTable","rawTables","tableLocales","slug","_path","_pathIdx","_parentIdFk","blockRelations","blockWithLocalized","mode","precision","withTimezone","groupHasLocalizedField","groupHasLocalizedManyNumberField","groupHasLocalizedManyTextField","groupHasLocalizedRelationshipField","groupHasManyNumberField","groupHasManyTextField","enumName","options","map","option","value","selectTableName","order","parent","orderIdx","parentIdx","parentFk","localeIdx","relation","add","relationshipConfig","collections","tableNameMap","get","colType","idType","relatedCollectionCustomID","find","reference","required"],"mappings":"AAEA,SAASA,oBAAoB,QAAQ,UAAS;AAC9C,SACEC,gBAAgB,EAChBC,cAAc,EACdC,sBAAsB,EACtBC,cAAc,QACT,iBAAgB;AACvB,OAAOC,iBAAiB,gBAAe;AAavC,SAASC,eAAe,QAAQ,wBAAuB;AACvD,SAASC,cAAc,QAAQ,iCAAgC;AAC/D,SAASC,oBAAoB,QAAQ,uCAAsC;AAC3E,SAASC,eAAe,QAAQ,kCAAiC;AACjE,SAASC,UAAU,QAAQ,6BAA4B;AACvD,SACEC,2BAA2B,EAC3BC,qBAAqB,EACrBC,gCAAgC,QAC3B,mDAAkD;AACzD,SAASC,UAAU,QAAQ,aAAY;AACvC,SAASC,QAAQ,QAAQ,gBAAe;AACxC,SAASC,WAAW,QAAQ,mBAAkB;AA2C9C,OAAO,MAAMC,iBAAiB,CAAC,EAC7BC,OAAO,EACPC,kBAAkB,EAClBC,YAAY,EACZC,OAAO,EACPC,cAAc,EACdC,sBAAsB,EACtBC,gBAAgB,KAAK,EACrBC,WAAW,EACXC,MAAM,EACNC,cAAc,EACdC,OAAO,EACPC,cAAc,EACdC,cAAc,EACdC,YAAY,EACZC,iBAAiB,EACjBC,eAAe,EACfC,aAAa,EACbC,gBAAgB,EAChBC,oBAAoB,EACpBC,kBAAkB,EAClBC,aAAa,EACbC,WAAW,EACXC,mBAAmB,EACnBC,QAAQ,EACRC,2BAA2B,EACtB;IACL,MAAMC,uBAAuB;IAC7B,IAAIC,oBAAoB;IACxB,IAAIC,gCAAgC;IACpC,IAAIC,mBAAsC;IAC1C,IAAIC,4BAA4B;IAChC,IAAIC,qBAAwC;IAC5C,IAAIC,8BAA8B;IAEl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;wBACL0D,WAAW,CAACG,UAAU,GAAG7C,YACvB;4BACEyC,MAAMG;4BACNN,MAAM;wBACR,GACAE;oBAEJ;oBACA;gBACF;YAEA;gBACE;QACJ;QAEA,MAAMyB,YAAYzB,MAAMwB,KAAK,IAAIxB,MAAMwB,KAAK,CAACC,SAAS;QAEtD,IACE,CAAC3D,kBACDoC,WAAW,CAACG,UAAU,IACtB,cAAcL,SACdA,MAAMkH,QAAQ,IACd,CAACzF,WACD;YACAvB,WAAW,CAACG,UAAU,CAAC0B,OAAO,GAAG;QACnC;IACF;IAEA,OAAO;QACL3C;QACAK;QACAF;QACAF;QACAG;QACAF;IACF;AACF,EAAC"}
1
+ {"version":3,"sources":["../../src/schema/traverseFields.ts"],"sourcesContent":["import type { FlattenedField } from 'payload'\n\nimport { InvalidConfiguration } from 'payload'\nimport {\n fieldAffectsData,\n fieldIsVirtual,\n fieldShouldBeLocalized,\n optionIsObject,\n} from 'payload/shared'\nimport toSnakeCase from 'to-snake-case'\n\nimport type {\n DrizzleAdapter,\n IDType,\n RawColumn,\n RawForeignKey,\n RawIndex,\n RawRelation,\n RelationMap,\n SetColumnID,\n} from '../types.js'\n\nimport { createTableName } from '../createTableName.js'\nimport { buildIndexName } from '../utilities/buildIndexName.js'\nimport { getArrayRelationName } from '../utilities/getArrayRelationName.js'\nimport { hasLocalesTable } from '../utilities/hasLocalesTable.js'\nimport { isUUIDType } from '../utilities/isUUIDType.js'\nimport {\n InternalBlockTableNameIndex,\n setInternalBlockIndex,\n validateExistingBlockIsIdentical,\n} from '../utilities/validateExistingBlockIsIdentical.js'\nimport { buildTable } from './build.js'\nimport { idToUUID } from './idToUUID.js'\nimport { withDefault } from './withDefault.js'\n\ntype Args = {\n adapter: DrizzleAdapter\n blocksTableNameMap: Record<string, number>\n columnPrefix?: string\n columns: Record<string, RawColumn>\n disableNotNull: boolean\n disableRelsTableUnique?: boolean\n disableUnique?: boolean\n fieldPrefix?: string\n fields: FlattenedField[]\n forceLocalized?: boolean\n indexes: Record<string, RawIndex>\n localesColumns: Record<string, RawColumn>\n localesIndexes: Record<string, RawIndex>\n newTableName: string\n parentIsLocalized: boolean\n parentTableName: string\n relationships: Set<string>\n relationsToBuild: RelationMap\n rootRelationsToBuild?: RelationMap\n rootTableIDColType: IDType\n rootTableName: string\n setColumnID: SetColumnID\n uniqueRelationships: Set<string>\n versions: boolean\n /**\n * Tracks whether or not this table is built\n * from the result of a localized array or block field at some point\n */\n withinLocalizedArrayOrBlock?: boolean\n}\n\ntype Result = {\n hasLocalizedField: boolean\n hasLocalizedManyNumberField: boolean\n hasLocalizedManyTextField: boolean\n hasLocalizedRelationshipField: boolean\n hasManyNumberField: 'index' | boolean\n hasManyTextField: 'index' | boolean\n}\n\nexport const traverseFields = ({\n adapter,\n blocksTableNameMap,\n columnPrefix,\n columns,\n disableNotNull,\n disableRelsTableUnique,\n disableUnique = false,\n fieldPrefix,\n fields,\n forceLocalized,\n indexes,\n localesColumns,\n localesIndexes,\n newTableName,\n parentIsLocalized,\n parentTableName,\n relationships,\n relationsToBuild,\n rootRelationsToBuild,\n rootTableIDColType,\n rootTableName,\n setColumnID,\n uniqueRelationships,\n versions,\n withinLocalizedArrayOrBlock,\n}: Args): Result => {\n const throwValidationError = true\n let hasLocalizedField = false\n let hasLocalizedRelationshipField = false\n let hasManyTextField: 'index' | boolean = false\n let hasLocalizedManyTextField = false\n let hasManyNumberField: 'index' | boolean = false\n let hasLocalizedManyNumberField = false\n\n let parentIDColType: IDType = 'integer'\n\n const idColumn = columns.id\n\n if (idColumn && ['numeric', 'text', 'uuid', 'varchar'].includes(idColumn.type)) {\n parentIDColType = idColumn.type as IDType\n }\n\n fields.forEach((field) => {\n if ('name' in field && field.name === 'id') {\n return\n }\n if (fieldIsVirtual(field)) {\n return\n }\n\n let targetTable = columns\n let targetIndexes = indexes\n\n const columnName = `${columnPrefix || ''}${field.name[0] === '_' ? '_' : ''}${toSnakeCase(\n field.name,\n )}`\n const fieldName = `${fieldPrefix?.replace('.', '_') || ''}${field.name}`\n\n const isFieldLocalized = fieldShouldBeLocalized({ field, parentIsLocalized })\n\n // If field is localized,\n // add the column to the locale table instead of main table\n if (\n adapter.payload.config.localization &&\n (isFieldLocalized || forceLocalized) &&\n field.type !== 'array' &&\n (field.type !== 'blocks' || adapter.blocksAsJSON) &&\n (('hasMany' in field && field.hasMany !== true) || !('hasMany' in field))\n ) {\n hasLocalizedField = true\n targetTable = localesColumns\n targetIndexes = localesIndexes\n }\n\n if (\n (field.unique || field.index || ['relationship', 'upload'].includes(field.type)) &&\n !['array', 'blocks', 'group'].includes(field.type) &&\n !('hasMany' in field && field.hasMany === true) &&\n !('relationTo' in field && Array.isArray(field.relationTo))\n ) {\n const unique = disableUnique !== true && field.unique\n if (unique) {\n const constraintValue = `${fieldPrefix || ''}${field.name}`\n if (!adapter.fieldConstraints?.[rootTableName]) {\n adapter.fieldConstraints[rootTableName] = {}\n }\n adapter.fieldConstraints[rootTableName][`${columnName}_idx`] = constraintValue\n }\n\n const indexName = buildIndexName({ name: `${newTableName}_${columnName}`, adapter })\n\n targetIndexes[indexName] = {\n name: indexName,\n on: isFieldLocalized ? [fieldName, '_locale'] : fieldName,\n unique,\n }\n }\n\n switch (field.type) {\n case 'array': {\n const disableNotNullFromHere = Boolean(field.admin?.condition) || disableNotNull\n\n const arrayTableName = createTableName({\n adapter,\n config: field,\n parentTableName: newTableName,\n prefix: `${newTableName}_`,\n throwValidationError,\n versionsCustomName: versions,\n })\n\n const baseColumns: Record<string, RawColumn> = {\n _order: {\n name: '_order',\n type: 'integer',\n notNull: true,\n },\n _parentID: {\n name: '_parent_id',\n type: parentIDColType,\n notNull: true,\n },\n }\n\n const baseIndexes: Record<string, RawIndex> = {\n _orderIdx: {\n name: `${arrayTableName}_order_idx`,\n on: ['_order'],\n },\n _parentIDIdx: {\n name: `${arrayTableName}_parent_id_idx`,\n on: '_parentID',\n },\n }\n\n const baseForeignKeys: Record<string, RawForeignKey> = {\n _parentIDFk: {\n name: `${arrayTableName}_parent_id_fk`,\n columns: ['_parentID'],\n foreignColumns: [\n {\n name: 'id',\n table: parentTableName,\n },\n ],\n onDelete: 'cascade',\n },\n }\n\n const isLocalized =\n Boolean(isFieldLocalized && adapter.payload.config.localization) ||\n withinLocalizedArrayOrBlock ||\n forceLocalized\n\n if (isLocalized) {\n baseColumns._locale = {\n name: '_locale',\n type: 'enum',\n locale: true,\n notNull: true,\n }\n\n baseIndexes._localeIdx = {\n name: `${arrayTableName}_locale_idx`,\n on: '_locale',\n }\n }\n\n const {\n hasLocalizedManyNumberField: subHasLocalizedManyNumberField,\n hasLocalizedManyTextField: subHasLocalizedManyTextField,\n hasLocalizedRelationshipField: subHasLocalizedRelationshipField,\n hasManyNumberField: subHasManyNumberField,\n hasManyTextField: subHasManyTextField,\n relationsToBuild: subRelationsToBuild,\n } = buildTable({\n adapter,\n baseColumns,\n baseForeignKeys,\n baseIndexes,\n blocksTableNameMap,\n disableNotNull: disableNotNullFromHere,\n disableRelsTableUnique: true,\n disableUnique,\n fields: disableUnique ? idToUUID(field.flattenedFields) : field.flattenedFields,\n parentIsLocalized: parentIsLocalized || field.localized,\n rootRelationships: relationships,\n rootRelationsToBuild,\n rootTableIDColType,\n rootTableName,\n rootUniqueRelationships: uniqueRelationships,\n setColumnID,\n tableName: arrayTableName,\n versions,\n withinLocalizedArrayOrBlock: isLocalized,\n })\n\n if (subHasLocalizedManyNumberField) {\n hasLocalizedManyNumberField = subHasLocalizedManyNumberField\n }\n\n if (subHasLocalizedRelationshipField) {\n hasLocalizedRelationshipField = subHasLocalizedRelationshipField\n }\n\n if (subHasLocalizedManyTextField) {\n hasLocalizedManyTextField = subHasLocalizedManyTextField\n }\n\n if (subHasManyTextField) {\n if (!hasManyTextField || subHasManyTextField === 'index') {\n hasManyTextField = subHasManyTextField\n }\n }\n if (subHasManyNumberField) {\n if (!hasManyNumberField || subHasManyNumberField === 'index') {\n hasManyNumberField = subHasManyNumberField\n }\n }\n\n const relationName = getArrayRelationName({\n field,\n path: fieldName,\n tableName: arrayTableName,\n })\n\n relationsToBuild.set(relationName, {\n type: 'many',\n // arrays have their own localized table, independent of the base table.\n localized: false,\n target: arrayTableName,\n })\n\n const arrayRelations: Record<string, RawRelation> = {\n _parentID: {\n type: 'one',\n fields: [\n {\n name: '_parentID',\n table: arrayTableName,\n },\n ],\n references: ['id'],\n relationName,\n to: parentTableName,\n },\n }\n\n if (\n hasLocalesTable({\n fields: field.fields,\n parentIsLocalized: parentIsLocalized || field.localized,\n })\n ) {\n arrayRelations._locales = {\n type: 'many',\n relationName: '_locales',\n to: `${arrayTableName}${adapter.localesSuffix}`,\n }\n }\n\n subRelationsToBuild.forEach(({ type, localized, target }, key) => {\n if (type === 'one') {\n const arrayWithLocalized = localized\n ? `${arrayTableName}${adapter.localesSuffix}`\n : arrayTableName\n\n arrayRelations[key] = {\n type: 'one',\n fields: [\n {\n name: key,\n table: arrayWithLocalized,\n },\n ],\n references: ['id'],\n relationName: key,\n to: target,\n }\n }\n\n if (type === 'many') {\n arrayRelations[key] = {\n type: 'many',\n relationName: key,\n to: target,\n }\n }\n })\n\n adapter.rawRelations[arrayTableName] = arrayRelations\n\n break\n }\n case 'blocks': {\n if (adapter.blocksAsJSON) {\n targetTable[fieldName] = withDefault(\n {\n name: columnName,\n type: 'jsonb',\n },\n field,\n )\n break\n }\n\n const disableNotNullFromHere = Boolean(field.admin?.condition) || disableNotNull\n\n field.blocks.forEach((_block) => {\n const block = typeof _block === 'string' ? adapter.payload.blocks[_block] : _block\n\n let blockTableName = createTableName({\n adapter,\n config: block,\n parentTableName: rootTableName,\n prefix: `${rootTableName}_blocks_`,\n throwValidationError,\n versionsCustomName: versions,\n })\n\n const isLocalizedBlockTable =\n Boolean(isFieldLocalized && adapter.payload.config.localization) ||\n withinLocalizedArrayOrBlock ||\n forceLocalized\n\n if (typeof blocksTableNameMap[blockTableName] === 'undefined') {\n blocksTableNameMap[blockTableName] = 1\n } else if (\n !adapter.rawTables[blockTableName] ||\n !validateExistingBlockIsIdentical({\n block,\n localized: isLocalizedBlockTable,\n parentIsLocalized,\n table: adapter.rawTables[blockTableName],\n tableLocales: adapter.rawTables[`${blockTableName}${adapter.localesSuffix}`],\n })\n ) {\n blocksTableNameMap[blockTableName]++\n setInternalBlockIndex(block, blocksTableNameMap[blockTableName])\n blockTableName = `${blockTableName}_${blocksTableNameMap[blockTableName]}`\n }\n let relationName = `_blocks_${block.slug}`\n if (typeof block[InternalBlockTableNameIndex] !== 'undefined') {\n relationName = `_blocks_${block.slug}_${block[InternalBlockTableNameIndex]}`\n }\n\n if (!adapter.rawTables[blockTableName]) {\n const baseColumns: Record<string, RawColumn> = {\n _order: {\n name: '_order',\n type: 'integer',\n notNull: true,\n },\n _parentID: {\n name: '_parent_id',\n type: rootTableIDColType,\n notNull: true,\n },\n _path: {\n name: '_path',\n type: 'text',\n notNull: true,\n },\n }\n\n const baseIndexes: Record<string, RawIndex> = {\n _orderIdx: {\n name: `${blockTableName}_order_idx`,\n on: '_order',\n },\n _parentIDIdx: {\n name: `${blockTableName}_parent_id_idx`,\n on: ['_parentID'],\n },\n _pathIdx: {\n name: `${blockTableName}_path_idx`,\n on: '_path',\n },\n }\n\n const baseForeignKeys: Record<string, RawForeignKey> = {\n _parentIdFk: {\n name: `${blockTableName}_parent_id_fk`,\n columns: ['_parentID'],\n foreignColumns: [\n {\n name: 'id',\n table: rootTableName,\n },\n ],\n onDelete: 'cascade',\n },\n }\n\n if (isLocalizedBlockTable) {\n baseColumns._locale = {\n name: '_locale',\n type: 'enum',\n locale: true,\n notNull: true,\n }\n\n baseIndexes._localeIdx = {\n name: `${blockTableName}_locale_idx`,\n on: '_locale',\n }\n }\n\n const {\n hasLocalizedManyNumberField: subHasLocalizedManyNumberField,\n hasLocalizedManyTextField: subHasLocalizedManyTextField,\n hasLocalizedRelationshipField: subHasLocalizedRelationshipField,\n hasManyNumberField: subHasManyNumberField,\n hasManyTextField: subHasManyTextField,\n relationsToBuild: subRelationsToBuild,\n } = buildTable({\n adapter,\n baseColumns,\n baseForeignKeys,\n baseIndexes,\n blocksTableNameMap,\n disableNotNull: disableNotNullFromHere,\n disableRelsTableUnique: true,\n disableUnique,\n fields: disableUnique ? idToUUID(block.flattenedFields) : block.flattenedFields,\n parentIsLocalized: parentIsLocalized || field.localized,\n rootRelationships: relationships,\n rootRelationsToBuild,\n rootTableIDColType,\n rootTableName,\n rootUniqueRelationships: uniqueRelationships,\n setColumnID,\n tableName: blockTableName,\n versions,\n withinLocalizedArrayOrBlock: isLocalizedBlockTable,\n })\n\n if (subHasLocalizedManyNumberField) {\n hasLocalizedManyNumberField = subHasLocalizedManyNumberField\n }\n\n if (subHasLocalizedRelationshipField) {\n hasLocalizedRelationshipField = subHasLocalizedRelationshipField\n }\n\n if (subHasLocalizedManyTextField) {\n hasLocalizedManyTextField = subHasLocalizedManyTextField\n }\n\n if (subHasManyTextField) {\n if (!hasManyTextField || subHasManyTextField === 'index') {\n hasManyTextField = subHasManyTextField\n }\n }\n\n if (subHasManyNumberField) {\n if (!hasManyNumberField || subHasManyNumberField === 'index') {\n hasManyNumberField = subHasManyNumberField\n }\n }\n\n const blockRelations: Record<string, RawRelation> = {\n _parentID: {\n type: 'one',\n fields: [\n {\n name: '_parentID',\n table: blockTableName,\n },\n ],\n references: ['id'],\n relationName,\n to: rootTableName,\n },\n }\n\n if (\n hasLocalesTable({\n fields: block.fields,\n parentIsLocalized: parentIsLocalized || field.localized,\n })\n ) {\n blockRelations._locales = {\n type: 'many',\n relationName: '_locales',\n to: `${blockTableName}${adapter.localesSuffix}`,\n }\n }\n\n subRelationsToBuild.forEach(({ type, localized, target }, key) => {\n if (type === 'one') {\n const blockWithLocalized = localized\n ? `${blockTableName}${adapter.localesSuffix}`\n : blockTableName\n\n blockRelations[key] = {\n type: 'one',\n fields: [\n {\n name: key,\n table: blockWithLocalized,\n },\n ],\n references: ['id'],\n relationName: key,\n to: target,\n }\n }\n\n if (type === 'many') {\n blockRelations[key] = {\n type: 'many',\n relationName: key,\n to: target,\n }\n }\n })\n\n adapter.rawRelations[blockTableName] = blockRelations\n }\n\n // blocks relationships are defined from the collection or globals table down to the block, bypassing any subBlocks\n rootRelationsToBuild.set(relationName, {\n type: 'many',\n // blocks are not localized on the parent table\n localized: false,\n target: blockTableName,\n })\n })\n\n break\n }\n case 'checkbox': {\n targetTable[fieldName] = withDefault(\n {\n name: columnName,\n type: 'boolean',\n },\n field,\n )\n\n break\n }\n\n case 'code':\n case 'email':\n case 'slug':\n case 'textarea': {\n targetTable[fieldName] = withDefault(\n {\n name: columnName,\n type: 'varchar',\n },\n field,\n )\n\n break\n }\n\n case 'date': {\n targetTable[fieldName] = withDefault(\n {\n name: columnName,\n type: 'timestamp',\n mode: 'string',\n precision: 3,\n withTimezone: true,\n },\n field,\n )\n\n break\n }\n\n case 'group':\n case 'tab': {\n const disableNotNullFromHere = Boolean(field.admin?.condition) || disableNotNull\n\n const {\n hasLocalizedField: groupHasLocalizedField,\n hasLocalizedManyNumberField: groupHasLocalizedManyNumberField,\n hasLocalizedManyTextField: groupHasLocalizedManyTextField,\n hasLocalizedRelationshipField: groupHasLocalizedRelationshipField,\n hasManyNumberField: groupHasManyNumberField,\n hasManyTextField: groupHasManyTextField,\n } = traverseFields({\n adapter,\n blocksTableNameMap,\n columnPrefix: `${columnName}_`,\n columns,\n disableNotNull: disableNotNullFromHere,\n disableUnique,\n fieldPrefix: `${fieldName}.`,\n fields: field.flattenedFields,\n forceLocalized: isFieldLocalized || Boolean(forceLocalized),\n indexes,\n localesColumns,\n localesIndexes,\n newTableName: `${parentTableName}_${columnName}`,\n parentIsLocalized: parentIsLocalized || field.localized,\n parentTableName,\n relationships,\n relationsToBuild,\n rootRelationsToBuild,\n rootTableIDColType,\n rootTableName,\n setColumnID,\n uniqueRelationships,\n versions,\n withinLocalizedArrayOrBlock: withinLocalizedArrayOrBlock || isFieldLocalized,\n })\n\n if (groupHasLocalizedField) {\n hasLocalizedField = true\n }\n if (groupHasLocalizedRelationshipField) {\n hasLocalizedRelationshipField = true\n }\n if (groupHasManyTextField) {\n hasManyTextField = true\n }\n if (groupHasLocalizedManyTextField) {\n hasLocalizedManyTextField = true\n }\n if (groupHasManyNumberField) {\n hasManyNumberField = true\n }\n if (groupHasLocalizedManyNumberField) {\n hasLocalizedManyNumberField = true\n }\n break\n }\n\n case 'json':\n case 'richText': {\n targetTable[fieldName] = withDefault(\n {\n name: columnName,\n type: 'jsonb',\n },\n field,\n )\n\n break\n }\n\n case 'number': {\n if (field.hasMany) {\n const isLocalized =\n Boolean(isFieldLocalized && adapter.payload.config.localization) ||\n withinLocalizedArrayOrBlock ||\n forceLocalized\n\n if (isLocalized) {\n hasLocalizedManyNumberField = true\n }\n\n if (field.index) {\n hasManyNumberField = 'index'\n } else if (!hasManyNumberField) {\n hasManyNumberField = true\n }\n\n if (field.unique) {\n throw new InvalidConfiguration(\n 'Unique is not supported in Postgres for hasMany number fields.',\n )\n }\n } else {\n targetTable[fieldName] = withDefault(\n {\n name: columnName,\n type: 'numeric',\n },\n field,\n )\n }\n\n break\n }\n\n case 'point': {\n targetTable[fieldName] = withDefault(\n {\n name: columnName,\n type: 'geometry',\n },\n field,\n )\n\n break\n }\n\n case 'radio':\n case 'select': {\n const enumName = createTableName({\n adapter,\n config: field,\n parentTableName: newTableName,\n prefix: `enum_${newTableName}_`,\n target: 'enumName',\n throwValidationError,\n })\n\n const options = field.options.map((option) => {\n if (optionIsObject(option)) {\n return option.value\n }\n\n return option\n })\n\n if (field.type === 'select' && field.hasMany) {\n const selectTableName = createTableName({\n adapter,\n config: field,\n parentTableName: newTableName,\n prefix: `${newTableName}_`,\n throwValidationError,\n versionsCustomName: versions,\n })\n\n const baseColumns: Record<string, RawColumn> = {\n order: {\n name: 'order',\n type: 'integer',\n notNull: true,\n },\n parent: {\n name: 'parent_id',\n type: parentIDColType,\n notNull: true,\n },\n value: {\n name: 'value',\n type: 'enum',\n enumName: createTableName({\n adapter,\n config: field,\n parentTableName: newTableName,\n prefix: `enum_${newTableName}_`,\n target: 'enumName',\n throwValidationError,\n }),\n options,\n },\n }\n\n const baseIndexes: Record<string, RawIndex> = {\n orderIdx: {\n name: `${selectTableName}_order_idx`,\n on: 'order',\n },\n parentIdx: {\n name: `${selectTableName}_parent_idx`,\n on: 'parent',\n },\n }\n\n const baseForeignKeys: Record<string, RawForeignKey> = {\n parentFk: {\n name: `${selectTableName}_parent_fk`,\n columns: ['parent'],\n foreignColumns: [\n {\n name: 'id',\n table: parentTableName,\n },\n ],\n onDelete: 'cascade',\n },\n }\n\n const isLocalized =\n Boolean(isFieldLocalized && adapter.payload.config.localization) ||\n withinLocalizedArrayOrBlock ||\n forceLocalized\n\n if (isLocalized) {\n baseColumns.locale = {\n name: 'locale',\n type: 'enum',\n locale: true,\n notNull: true,\n }\n\n baseIndexes.localeIdx = {\n name: `${selectTableName}_locale_idx`,\n on: 'locale',\n }\n }\n\n if (field.index) {\n baseIndexes.value = {\n name: `${selectTableName}_value_idx`,\n on: 'value',\n }\n }\n\n buildTable({\n adapter,\n baseColumns,\n baseForeignKeys,\n baseIndexes,\n blocksTableNameMap,\n disableNotNull,\n disableUnique,\n fields: [],\n parentIsLocalized: parentIsLocalized || field.localized,\n rootTableName,\n setColumnID,\n tableName: selectTableName,\n versions,\n })\n\n relationsToBuild.set(fieldName, {\n type: 'many',\n // selects have their own localized table, independent of the base table.\n localized: false,\n target: selectTableName,\n })\n\n adapter.rawRelations[selectTableName] = {\n parent: {\n type: 'one',\n fields: [\n {\n name: 'parent',\n table: selectTableName,\n },\n ],\n references: ['id'],\n relationName: fieldName,\n to: parentTableName,\n },\n }\n } else {\n targetTable[fieldName] = withDefault(\n {\n name: columnName,\n type: 'enum',\n enumName,\n options,\n },\n field,\n )\n }\n break\n }\n\n case 'relationship':\n case 'upload':\n if (Array.isArray(field.relationTo)) {\n field.relationTo.forEach((relation) => {\n relationships.add(relation)\n if (field.unique && !disableUnique && !disableRelsTableUnique) {\n uniqueRelationships.add(relation)\n }\n })\n } else if (field.hasMany) {\n relationships.add(field.relationTo)\n if (field.unique && !disableUnique && !disableRelsTableUnique) {\n uniqueRelationships.add(field.relationTo)\n }\n } else {\n // simple relationships get a column on the targetTable with a foreign key to the relationTo table\n const relationshipConfig = adapter.payload.collections[field.relationTo].config\n\n const tableName = adapter.tableNameMap.get(toSnakeCase(field.relationTo))\n\n // get the id type of the related collection\n let colType: IDType = isUUIDType(adapter.idType) ? 'uuid' : 'integer'\n const relatedCollectionCustomID = relationshipConfig.fields.find(\n (field) => fieldAffectsData(field) && field.name === 'id',\n )\n if (relatedCollectionCustomID?.type === 'number') {\n colType = 'numeric'\n }\n if (relatedCollectionCustomID?.type === 'text') {\n colType = 'varchar'\n }\n\n // make the foreign key column for relationship using the correct id column type\n targetTable[fieldName] = {\n name: `${columnName}_id`,\n type: colType,\n reference: {\n name: 'id',\n onDelete: 'set null',\n table: tableName,\n },\n }\n\n // add relationship to table\n relationsToBuild.set(fieldName, {\n type: 'one',\n localized: adapter.payload.config.localization && (isFieldLocalized || forceLocalized),\n target: tableName,\n })\n\n // add notNull when not required\n if (!disableNotNull && field.required && !field.admin?.condition) {\n targetTable[fieldName].notNull = true\n }\n break\n }\n\n if (\n Boolean(isFieldLocalized && adapter.payload.config.localization) ||\n withinLocalizedArrayOrBlock\n ) {\n hasLocalizedRelationshipField = true\n }\n\n break\n\n case 'text': {\n if (field.hasMany) {\n const isLocalized =\n Boolean(isFieldLocalized && adapter.payload.config.localization) ||\n withinLocalizedArrayOrBlock ||\n forceLocalized\n\n if (isLocalized) {\n hasLocalizedManyTextField = true\n }\n\n if (field.index) {\n hasManyTextField = 'index'\n } else if (!hasManyTextField) {\n hasManyTextField = true\n }\n\n if (field.unique) {\n throw new InvalidConfiguration(\n 'Unique is not supported in Postgres for hasMany text fields.',\n )\n }\n } else {\n targetTable[fieldName] = withDefault(\n {\n name: columnName,\n type: 'varchar',\n },\n field,\n )\n }\n break\n }\n\n default:\n break\n }\n\n const condition = field.admin && field.admin.condition\n\n if (\n !disableNotNull &&\n targetTable[fieldName] &&\n 'required' in field &&\n field.required &&\n !condition\n ) {\n targetTable[fieldName].notNull = true\n }\n })\n\n return {\n hasLocalizedField,\n hasLocalizedManyNumberField,\n hasLocalizedManyTextField,\n hasLocalizedRelationshipField,\n hasManyNumberField,\n hasManyTextField,\n }\n}\n"],"names":["InvalidConfiguration","fieldAffectsData","fieldIsVirtual","fieldShouldBeLocalized","optionIsObject","toSnakeCase","createTableName","buildIndexName","getArrayRelationName","hasLocalesTable","isUUIDType","InternalBlockTableNameIndex","setInternalBlockIndex","validateExistingBlockIsIdentical","buildTable","idToUUID","withDefault","traverseFields","adapter","blocksTableNameMap","columnPrefix","columns","disableNotNull","disableRelsTableUnique","disableUnique","fieldPrefix","fields","forceLocalized","indexes","localesColumns","localesIndexes","newTableName","parentIsLocalized","parentTableName","relationships","relationsToBuild","rootRelationsToBuild","rootTableIDColType","rootTableName","setColumnID","uniqueRelationships","versions","withinLocalizedArrayOrBlock","throwValidationError","hasLocalizedField","hasLocalizedRelationshipField","hasManyTextField","hasLocalizedManyTextField","hasManyNumberField","hasLocalizedManyNumberField","parentIDColType","idColumn","id","includes","type","forEach","field","name","targetTable","targetIndexes","columnName","fieldName","replace","isFieldLocalized","payload","config","localization","blocksAsJSON","hasMany","unique","index","Array","isArray","relationTo","constraintValue","fieldConstraints","indexName","on","disableNotNullFromHere","Boolean","admin","condition","arrayTableName","prefix","versionsCustomName","baseColumns","_order","notNull","_parentID","baseIndexes","_orderIdx","_parentIDIdx","baseForeignKeys","_parentIDFk","foreignColumns","table","onDelete","isLocalized","_locale","locale","_localeIdx","subHasLocalizedManyNumberField","subHasLocalizedManyTextField","subHasLocalizedRelationshipField","subHasManyNumberField","subHasManyTextField","subRelationsToBuild","flattenedFields","localized","rootRelationships","rootUniqueRelationships","tableName","relationName","path","set","target","arrayRelations","references","to","_locales","localesSuffix","key","arrayWithLocalized","rawRelations","blocks","_block","block","blockTableName","isLocalizedBlockTable","rawTables","tableLocales","slug","_path","_pathIdx","_parentIdFk","blockRelations","blockWithLocalized","mode","precision","withTimezone","groupHasLocalizedField","groupHasLocalizedManyNumberField","groupHasLocalizedManyTextField","groupHasLocalizedRelationshipField","groupHasManyNumberField","groupHasManyTextField","enumName","options","map","option","value","selectTableName","order","parent","orderIdx","parentIdx","parentFk","localeIdx","relation","add","relationshipConfig","collections","tableNameMap","get","colType","idType","relatedCollectionCustomID","find","reference","required"],"mappings":"AAEA,SAASA,oBAAoB,QAAQ,UAAS;AAC9C,SACEC,gBAAgB,EAChBC,cAAc,EACdC,sBAAsB,EACtBC,cAAc,QACT,iBAAgB;AACvB,OAAOC,iBAAiB,gBAAe;AAavC,SAASC,eAAe,QAAQ,wBAAuB;AACvD,SAASC,cAAc,QAAQ,iCAAgC;AAC/D,SAASC,oBAAoB,QAAQ,uCAAsC;AAC3E,SAASC,eAAe,QAAQ,kCAAiC;AACjE,SAASC,UAAU,QAAQ,6BAA4B;AACvD,SACEC,2BAA2B,EAC3BC,qBAAqB,EACrBC,gCAAgC,QAC3B,mDAAkD;AACzD,SAASC,UAAU,QAAQ,aAAY;AACvC,SAASC,QAAQ,QAAQ,gBAAe;AACxC,SAASC,WAAW,QAAQ,mBAAkB;AA2C9C,OAAO,MAAMC,iBAAiB,CAAC,EAC7BC,OAAO,EACPC,kBAAkB,EAClBC,YAAY,EACZC,OAAO,EACPC,cAAc,EACdC,sBAAsB,EACtBC,gBAAgB,KAAK,EACrBC,WAAW,EACXC,MAAM,EACNC,cAAc,EACdC,OAAO,EACPC,cAAc,EACdC,cAAc,EACdC,YAAY,EACZC,iBAAiB,EACjBC,eAAe,EACfC,aAAa,EACbC,gBAAgB,EAChBC,oBAAoB,EACpBC,kBAAkB,EAClBC,aAAa,EACbC,WAAW,EACXC,mBAAmB,EACnBC,QAAQ,EACRC,2BAA2B,EACtB;IACL,MAAMC,uBAAuB;IAC7B,IAAIC,oBAAoB;IACxB,IAAIC,gCAAgC;IACpC,IAAIC,mBAAsC;IAC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AM,IAAIrE,qBACR;wBAEJ;oBACF,OAAO;wBACL0D,WAAW,CAACG,UAAU,GAAG7C,YACvB;4BACEyC,MAAMG;4BACNN,MAAM;wBACR,GACAE;oBAEJ;oBACA;gBACF;YAEA;gBACE;QACJ;QAEA,MAAMyB,YAAYzB,MAAMwB,KAAK,IAAIxB,MAAMwB,KAAK,CAACC,SAAS;QAEtD,IACE,CAAC3D,kBACDoC,WAAW,CAACG,UAAU,IACtB,cAAcL,SACdA,MAAMiH,QAAQ,IACd,CAACxF,WACD;YACAvB,WAAW,CAACG,UAAU,CAAC0B,OAAO,GAAG;QACnC;IACF;IAEA,OAAO;QACL3C;QACAK;QACAF;QACAF;QACAG;QACAF;IACF;AACF,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"insert.d.ts","sourceRoot":"","sources":["../../src/sqlite/insert.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAqB,MAAM,EAAE,MAAM,YAAY,CAAA;AAE3D,eAAO,MAAM,MAAM,EAAE,MAkCpB,CAAA"}
1
+ {"version":3,"file":"insert.d.ts","sourceRoot":"","sources":["../../src/sqlite/insert.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAqB,MAAM,EAAE,MAAM,YAAY,CAAA;AAE3D,eAAO,MAAM,MAAM,EAAE,MAoCpB,CAAA"}
@@ -1,9 +1,12 @@
1
+ import { getTableColumns } from 'drizzle-orm';
1
2
  export const insert = async function({ db, onConflictDoUpdate, tableName, values }) {
2
3
  const table = this.tables[tableName];
3
4
  // Batch insert if limitedBoundParameters: true
4
5
  if (this.limitedBoundParameters && Array.isArray(values)) {
5
6
  const results = [];
6
- const colsPerRow = Object.keys(values[0]).length;
7
+ // Drizzle emits a value for every table column per row, not just the keys present on the row —
8
+ // omitted columns fall back to their default / defaultFn, which is also a bound parameter
9
+ const colsPerRow = Math.max(1, Object.keys(getTableColumns(table)).length);
7
10
  const maxParams = 100;
8
11
  const maxRowsPerBatch = Math.max(1, Math.floor(maxParams / colsPerRow));
9
12
  for(let i = 0; i < values.length; i += maxRowsPerBatch){
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/sqlite/insert.ts"],"sourcesContent":["import type { BaseSQLiteAdapter, Insert } from './types.js'\n\nexport const insert: Insert = async function (\n // Here 'this' is not a parameter. See:\n // https://www.typescriptlang.org/docs/handbook/2/classes.html#this-parameters\n this: BaseSQLiteAdapter,\n { db, onConflictDoUpdate, tableName, values },\n): Promise<Record<string, unknown>[]> {\n const table = this.tables[tableName]\n\n // Batch insert if limitedBoundParameters: true\n if (this.limitedBoundParameters && Array.isArray(values)) {\n const results: Record<string, unknown>[] = []\n const colsPerRow = Object.keys(values[0]).length\n const maxParams = 100\n const maxRowsPerBatch = Math.max(1, Math.floor(maxParams / colsPerRow))\n\n for (let i = 0; i < values.length; i += maxRowsPerBatch) {\n const batch = values.slice(i, i + maxRowsPerBatch)\n\n const batchResult = onConflictDoUpdate\n ? await db.insert(table).values(batch).onConflictDoUpdate(onConflictDoUpdate).returning()\n : await db.insert(table).values(batch).returning()\n\n results.push(...(batchResult as Record<string, unknown>[]))\n }\n\n return results\n }\n\n const result = onConflictDoUpdate\n ? await db.insert(table).values(values).onConflictDoUpdate(onConflictDoUpdate).returning()\n : await db.insert(table).values(values).returning()\n\n // See https://github.com/payloadcms/payload/pull/11831#discussion_r2010431908\n return result as Record<string, unknown>[]\n}\n"],"names":["insert","db","onConflictDoUpdate","tableName","values","table","tables","limitedBoundParameters","Array","isArray","results","colsPerRow","Object","keys","length","maxParams","maxRowsPerBatch","Math","max","floor","i","batch","slice","batchResult","returning","push","result"],"mappings":"AAEA,OAAO,MAAMA,SAAiB,eAI5B,EAAEC,EAAE,EAAEC,kBAAkB,EAAEC,SAAS,EAAEC,MAAM,EAAE;IAE7C,MAAMC,QAAQ,IAAI,CAACC,MAAM,CAACH,UAAU;IAEpC,+CAA+C;IAC/C,IAAI,IAAI,CAACI,sBAAsB,IAAIC,MAAMC,OAAO,CAACL,SAAS;QACxD,MAAMM,UAAqC,EAAE;QAC7C,MAAMC,aAAaC,OAAOC,IAAI,CAACT,MAAM,CAAC,EAAE,EAAEU,MAAM;QAChD,MAAMC,YAAY;QAClB,MAAMC,kBAAkBC,KAAKC,GAAG,CAAC,GAAGD,KAAKE,KAAK,CAACJ,YAAYJ;QAE3D,IAAK,IAAIS,IAAI,GAAGA,IAAIhB,OAAOU,MAAM,EAAEM,KAAKJ,gBAAiB;YACvD,MAAMK,QAAQjB,OAAOkB,KAAK,CAACF,GAAGA,IAAIJ;YAElC,MAAMO,cAAcrB,qBAChB,MAAMD,GAAGD,MAAM,CAACK,OAAOD,MAAM,CAACiB,OAAOnB,kBAAkB,CAACA,oBAAoBsB,SAAS,KACrF,MAAMvB,GAAGD,MAAM,CAACK,OAAOD,MAAM,CAACiB,OAAOG,SAAS;YAElDd,QAAQe,IAAI,IAAKF;QACnB;QAEA,OAAOb;IACT;IAEA,MAAMgB,SAASxB,qBACX,MAAMD,GAAGD,MAAM,CAACK,OAAOD,MAAM,CAACA,QAAQF,kBAAkB,CAACA,oBAAoBsB,SAAS,KACtF,MAAMvB,GAAGD,MAAM,CAACK,OAAOD,MAAM,CAACA,QAAQoB,SAAS;IAEnD,8EAA8E;IAC9E,OAAOE;AACT,EAAC"}
1
+ {"version":3,"sources":["../../src/sqlite/insert.ts"],"sourcesContent":["import { getTableColumns } from 'drizzle-orm'\n\nimport type { BaseSQLiteAdapter, Insert } from './types.js'\n\nexport const insert: Insert = async function (\n // Here 'this' is not a parameter. See:\n // https://www.typescriptlang.org/docs/handbook/2/classes.html#this-parameters\n this: BaseSQLiteAdapter,\n { db, onConflictDoUpdate, tableName, values },\n): Promise<Record<string, unknown>[]> {\n const table = this.tables[tableName]\n\n // Batch insert if limitedBoundParameters: true\n if (this.limitedBoundParameters && Array.isArray(values)) {\n const results: Record<string, unknown>[] = []\n // Drizzle emits a value for every table column per row, not just the keys present on the row —\n // omitted columns fall back to their default / defaultFn, which is also a bound parameter\n const colsPerRow = Math.max(1, Object.keys(getTableColumns(table)).length)\n const maxParams = 100\n const maxRowsPerBatch = Math.max(1, Math.floor(maxParams / colsPerRow))\n\n for (let i = 0; i < values.length; i += maxRowsPerBatch) {\n const batch = values.slice(i, i + maxRowsPerBatch)\n\n const batchResult = onConflictDoUpdate\n ? await db.insert(table).values(batch).onConflictDoUpdate(onConflictDoUpdate).returning()\n : await db.insert(table).values(batch).returning()\n\n results.push(...(batchResult as Record<string, unknown>[]))\n }\n\n return results\n }\n\n const result = onConflictDoUpdate\n ? await db.insert(table).values(values).onConflictDoUpdate(onConflictDoUpdate).returning()\n : await db.insert(table).values(values).returning()\n\n // See https://github.com/payloadcms/payload/pull/11831#discussion_r2010431908\n return result as Record<string, unknown>[]\n}\n"],"names":["getTableColumns","insert","db","onConflictDoUpdate","tableName","values","table","tables","limitedBoundParameters","Array","isArray","results","colsPerRow","Math","max","Object","keys","length","maxParams","maxRowsPerBatch","floor","i","batch","slice","batchResult","returning","push","result"],"mappings":"AAAA,SAASA,eAAe,QAAQ,cAAa;AAI7C,OAAO,MAAMC,SAAiB,eAI5B,EAAEC,EAAE,EAAEC,kBAAkB,EAAEC,SAAS,EAAEC,MAAM,EAAE;IAE7C,MAAMC,QAAQ,IAAI,CAACC,MAAM,CAACH,UAAU;IAEpC,+CAA+C;IAC/C,IAAI,IAAI,CAACI,sBAAsB,IAAIC,MAAMC,OAAO,CAACL,SAAS;QACxD,MAAMM,UAAqC,EAAE;QAC7C,+FAA+F;QAC/F,0FAA0F;QAC1F,MAAMC,aAAaC,KAAKC,GAAG,CAAC,GAAGC,OAAOC,IAAI,CAAChB,gBAAgBM,QAAQW,MAAM;QACzE,MAAMC,YAAY;QAClB,MAAMC,kBAAkBN,KAAKC,GAAG,CAAC,GAAGD,KAAKO,KAAK,CAACF,YAAYN;QAE3D,IAAK,IAAIS,IAAI,GAAGA,IAAIhB,OAAOY,MAAM,EAAEI,KAAKF,gBAAiB;YACvD,MAAMG,QAAQjB,OAAOkB,KAAK,CAACF,GAAGA,IAAIF;YAElC,MAAMK,cAAcrB,qBAChB,MAAMD,GAAGD,MAAM,CAACK,OAAOD,MAAM,CAACiB,OAAOnB,kBAAkB,CAACA,oBAAoBsB,SAAS,KACrF,MAAMvB,GAAGD,MAAM,CAACK,OAAOD,MAAM,CAACiB,OAAOG,SAAS;YAElDd,QAAQe,IAAI,IAAKF;QACnB;QAEA,OAAOb;IACT;IAEA,MAAMgB,SAASxB,qBACX,MAAMD,GAAGD,MAAM,CAACK,OAAOD,MAAM,CAACA,QAAQF,kBAAkB,CAACA,oBAAoBsB,SAAS,KACtF,MAAMvB,GAAGD,MAAM,CAACK,OAAOD,MAAM,CAACA,QAAQoB,SAAS;IAEnD,8EAA8E;IAC9E,OAAOE;AACT,EAAC"}
@@ -0,0 +1,28 @@
1
+ import type { Payload } from 'payload';
2
+ export type LocalizeStatusArgs = {
3
+ collectionSlug?: string;
4
+ db: any;
5
+ globalSlug?: string;
6
+ payload: Payload;
7
+ req?: any;
8
+ };
9
+ export declare function migrateSqliteLocalizeStatus(args: LocalizeStatusArgs): Promise<void>;
10
+ /**
11
+ * Drops a column, first removing any indexes that reference it. SQLite refuses to
12
+ * drop a column that is still referenced by an index.
13
+ */
14
+ export declare function dropColumn({ columnName, db, tableName, }: {
15
+ columnName: string;
16
+ db: any;
17
+ tableName: string;
18
+ }): Promise<void>;
19
+ export declare function columnExists({ columnName, db, tableName, }: {
20
+ columnName: string;
21
+ db: any;
22
+ tableName: string;
23
+ }): Promise<boolean>;
24
+ export declare function tableExists({ db, tableName, }: {
25
+ db: any;
26
+ tableName: string;
27
+ }): Promise<boolean>;
28
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/sqlite/predefinedMigrations/localize-status/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AAStC,MAAM,MAAM,kBAAkB,GAAG;IAC/B,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,EAAE,EAAE,GAAG,CAAA;IACP,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,OAAO,EAAE,OAAO,CAAA;IAChB,GAAG,CAAC,EAAE,GAAG,CAAA;CACV,CAAA;AAED,wBAAsB,2BAA2B,CAAC,IAAI,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC,CA2LzF;AAED;;;GAGG;AACH,wBAAsB,UAAU,CAAC,EAC/B,UAAU,EACV,EAAE,EACF,SAAS,GACV,EAAE;IACD,UAAU,EAAE,MAAM,CAAA;IAClB,EAAE,EAAE,GAAG,CAAA;IACP,SAAS,EAAE,MAAM,CAAA;CAClB,GAAG,OAAO,CAAC,IAAI,CAAC,CAYhB;AAED,wBAAsB,YAAY,CAAC,EACjC,UAAU,EACV,EAAE,EACF,SAAS,GACV,EAAE;IACD,UAAU,EAAE,MAAM,CAAA;IAClB,EAAE,EAAE,GAAG,CAAA;IACP,SAAS,EAAE,MAAM,CAAA;CAClB,GAAG,OAAO,CAAC,OAAO,CAAC,CAOnB;AAED,wBAAsB,WAAW,CAAC,EAChC,EAAE,EACF,SAAS,GACV,EAAE;IACD,EAAE,EAAE,GAAG,CAAA;IACP,SAAS,EAAE,MAAM,CAAA;CAClB,GAAG,OAAO,CAAC,OAAO,CAAC,CAOnB"}
@@ -0,0 +1,198 @@
1
+ import { sql } from 'drizzle-orm';
2
+ import { calculateVersionLocaleStatuses } from 'payload/migrations';
3
+ import toSnakeCase from 'to-snake-case';
4
+ import { migrateMainCollectionStatus } from './migrateMainCollection.js';
5
+ import { migrateMainGlobalStatus } from './migrateMainGlobal.js';
6
+ export async function migrateSqliteLocalizeStatus(args) {
7
+ const { collectionSlug, db, globalSlug, payload, req } = args;
8
+ if (!collectionSlug && !globalSlug) {
9
+ throw new Error('Either collectionSlug or globalSlug must be provided');
10
+ }
11
+ if (collectionSlug && globalSlug) {
12
+ throw new Error('Cannot provide both collectionSlug and globalSlug');
13
+ }
14
+ const entitySlug = collectionSlug || globalSlug;
15
+ const versionsTable = collectionSlug ? `_${toSnakeCase(collectionSlug)}_v` : `_${toSnakeCase(globalSlug)}_v`;
16
+ const localesTable = `${versionsTable}_locales`;
17
+ if (!payload.config.localization) {
18
+ throw new Error('Localization is not enabled in payload config');
19
+ }
20
+ // Check if versions are enabled on this collection/global
21
+ let entityConfig;
22
+ if (collectionSlug) {
23
+ entityConfig = payload.config.collections.find((c)=>c.slug === collectionSlug);
24
+ } else if (globalSlug) {
25
+ entityConfig = payload.config.globals.find((g)=>g.slug === globalSlug);
26
+ }
27
+ if (!entityConfig) {
28
+ throw new Error(`${collectionSlug ? 'Collection' : 'Global'} not found: ${collectionSlug || globalSlug}`);
29
+ }
30
+ payload.logger.info({
31
+ msg: `Starting _status localization migration for ${collectionSlug ? 'collection' : 'global'}: ${entitySlug}`
32
+ });
33
+ // Get filtered locales if filterAvailableLocales is defined
34
+ let locales = payload.config.localization.localeCodes;
35
+ if (typeof payload.config.localization.filterAvailableLocales === 'function') {
36
+ const filteredLocaleObjects = await payload.config.localization.filterAvailableLocales({
37
+ locales: payload.config.localization.locales,
38
+ req
39
+ });
40
+ locales = filteredLocaleObjects.map((locale)=>typeof locale === 'string' ? locale : locale.code);
41
+ }
42
+ payload.logger.info({
43
+ msg: `Locales: ${locales.join(', ')}`
44
+ });
45
+ // Check if versions are enabled in config (skip if not)
46
+ if (!entityConfig.versions) {
47
+ payload.logger.info({
48
+ msg: `Skipping migration for ${collectionSlug ? 'collection' : 'global'}: ${entitySlug} - versions not enabled`
49
+ });
50
+ return;
51
+ }
52
+ // Validate that version__status column exists before proceeding
53
+ if (!await columnExists({
54
+ columnName: 'version__status',
55
+ db,
56
+ tableName: versionsTable
57
+ })) {
58
+ throw new Error(`Migration aborted: version__status column not found in ${versionsTable} table. ` + `This migration should only run on schemas that have NOT yet been migrated to per-locale status. ` + `If you've already run this migration, no action is needed.`);
59
+ }
60
+ const localesTableExists = await tableExists({
61
+ db,
62
+ tableName: localesTable
63
+ });
64
+ if (!localesTableExists) {
65
+ // SCENARIO 1: Create the locales table (first localized field in versions)
66
+ payload.logger.info({
67
+ msg: `Creating new locales table: ${localesTable}`
68
+ });
69
+ await db.run(sql.raw(`CREATE TABLE "${localesTable}" (
70
+ id INTEGER PRIMARY KEY,
71
+ _locale TEXT NOT NULL,
72
+ _parent_id INTEGER NOT NULL,
73
+ version__status TEXT,
74
+ UNIQUE(_locale, _parent_id),
75
+ FOREIGN KEY (_parent_id) REFERENCES "${versionsTable}"(id) ON DELETE CASCADE
76
+ )`));
77
+ for (const locale of locales){
78
+ const inserted = await db.all(sql.raw(`INSERT INTO "${localesTable}" (_locale, _parent_id, version__status) SELECT '${locale}', id, version__status FROM "${versionsTable}" RETURNING id`));
79
+ payload.logger.info({
80
+ msg: `Inserted ${inserted.length} rows for locale: ${locale}`
81
+ });
82
+ }
83
+ } else {
84
+ // SCENARIO 2: Add version__status column to existing locales table
85
+ payload.logger.info({
86
+ msg: `Adding version__status column to existing table: ${localesTable}`
87
+ });
88
+ await db.run(sql.raw(`ALTER TABLE "${localesTable}" ADD COLUMN version__status TEXT`));
89
+ payload.logger.info({
90
+ msg: 'Processing version history to determine status per locale...'
91
+ });
92
+ const existingLocaleRows = await db.all(sql.raw(`SELECT DISTINCT _locale FROM "${localesTable}" ORDER BY _locale`));
93
+ const existingLocales = existingLocaleRows.map((row)=>row._locale);
94
+ payload.logger.info({
95
+ msg: `Found existing locales in table: ${existingLocales.join(', ')}`
96
+ });
97
+ // Check if the snapshot column exists (only present on DBs that used publishSpecificLocale)
98
+ const hasSnapshotColumn = await columnExists({
99
+ columnName: 'snapshot',
100
+ db,
101
+ tableName: versionsTable
102
+ });
103
+ const versionRows = await db.all(sql.raw(hasSnapshotColumn ? `SELECT id, parent_id as parent, version__status as _status, published_locale, snapshot, created_at FROM "${versionsTable}" ORDER BY parent_id, created_at ASC` : `SELECT id, parent_id as parent, version__status as _status, published_locale, created_at FROM "${versionsTable}" ORDER BY parent_id, created_at ASC`));
104
+ const versionLocaleStatus = calculateVersionLocaleStatuses(versionRows, existingLocales, payload);
105
+ payload.logger.info({
106
+ msg: 'Updating locales table with calculated statuses...'
107
+ });
108
+ let updateCount = 0;
109
+ for (const [versionId, localeMap] of versionLocaleStatus.entries()){
110
+ for (const [locale, status] of localeMap.entries()){
111
+ await db.run(sql.raw(`UPDATE "${localesTable}" SET version__status = '${status}' WHERE _parent_id = ${versionId} AND _locale = '${locale}'`));
112
+ updateCount++;
113
+ }
114
+ }
115
+ payload.logger.info({
116
+ msg: `Updated ${updateCount} locale rows with status`
117
+ });
118
+ }
119
+ // Drop the old version__status column from the versions table
120
+ await dropColumn({
121
+ columnName: 'version__status',
122
+ db,
123
+ tableName: versionsTable
124
+ });
125
+ // Migrate main table _status to locales table
126
+ const mainTable = collectionSlug ? toSnakeCase(collectionSlug) : toSnakeCase(globalSlug);
127
+ const mainLocalesTable = `${mainTable}_locales`;
128
+ if (await tableExists({
129
+ db,
130
+ tableName: mainLocalesTable
131
+ })) {
132
+ if (!await columnExists({
133
+ columnName: '_status',
134
+ db,
135
+ tableName: mainLocalesTable
136
+ })) {
137
+ await db.run(sql.raw(`ALTER TABLE "${mainLocalesTable}" ADD COLUMN _status TEXT DEFAULT 'draft'`));
138
+ }
139
+ if (collectionSlug) {
140
+ await migrateMainCollectionStatus({
141
+ collectionSlug,
142
+ db,
143
+ locales,
144
+ payload,
145
+ versionsTable
146
+ });
147
+ } else if (globalSlug) {
148
+ await migrateMainGlobalStatus({
149
+ db,
150
+ globalSlug,
151
+ locales,
152
+ payload,
153
+ versionsTable
154
+ });
155
+ }
156
+ } else {
157
+ payload.logger.info({
158
+ msg: `No locales table found: ${mainLocalesTable} (collection/global not localized)`
159
+ });
160
+ }
161
+ // Drop _status from main table if it exists (it will be in locales table now)
162
+ if (await columnExists({
163
+ columnName: '_status',
164
+ db,
165
+ tableName: mainTable
166
+ })) {
167
+ await dropColumn({
168
+ columnName: '_status',
169
+ db,
170
+ tableName: mainTable
171
+ });
172
+ }
173
+ payload.logger.info({
174
+ msg: 'Migration completed successfully'
175
+ });
176
+ }
177
+ /**
178
+ * Drops a column, first removing any indexes that reference it. SQLite refuses to
179
+ * drop a column that is still referenced by an index.
180
+ */ export async function dropColumn({ columnName, db, tableName }) {
181
+ const indexes = await db.all(sql.raw(`SELECT name, sql FROM sqlite_master WHERE type='index' AND tbl_name='${tableName}'`));
182
+ for (const index of indexes){
183
+ if (typeof index.sql === 'string' && index.sql.includes(columnName)) {
184
+ await db.run(sql.raw(`DROP INDEX IF EXISTS "${index.name}"`));
185
+ }
186
+ }
187
+ await db.run(sql.raw(`ALTER TABLE "${tableName}" DROP COLUMN ${columnName}`));
188
+ }
189
+ export async function columnExists({ columnName, db, tableName }) {
190
+ const result = await db.all(sql.raw(`SELECT COUNT(*) as count FROM pragma_table_info('${tableName}') WHERE name = '${columnName}'`));
191
+ return Number(result[0]?.count ?? 0) > 0;
192
+ }
193
+ export async function tableExists({ db, tableName }) {
194
+ const result = await db.all(sql.raw(`SELECT COUNT(*) as count FROM sqlite_master WHERE type='table' AND name='${tableName}'`));
195
+ return Number(result[0]?.count ?? 0) > 0;
196
+ }
197
+
198
+ //# sourceMappingURL=index.js.map