@payloadcms/db-postgres 3.0.0-beta.7 → 3.0.0-canary.2077da8

Sign up to get free protection for your applications and to get access to all the features.
Files changed (198) hide show
  1. package/dist/connect.d.ts.map +1 -1
  2. package/dist/connect.js +12 -7
  3. package/dist/connect.js.map +1 -1
  4. package/dist/count.d.ts +3 -0
  5. package/dist/count.d.ts.map +1 -0
  6. package/dist/count.js +41 -0
  7. package/dist/count.js.map +1 -0
  8. package/dist/create.d.ts.map +1 -1
  9. package/dist/create.js +3 -5
  10. package/dist/create.js.map +1 -1
  11. package/dist/createGlobal.d.ts.map +1 -1
  12. package/dist/createGlobal.js +3 -5
  13. package/dist/createGlobal.js.map +1 -1
  14. package/dist/createGlobalVersion.d.ts +1 -1
  15. package/dist/createGlobalVersion.d.ts.map +1 -1
  16. package/dist/createGlobalVersion.js +2 -6
  17. package/dist/createGlobalVersion.js.map +1 -1
  18. package/dist/createMigration.d.ts.map +1 -1
  19. package/dist/createMigration.js +58 -37
  20. package/dist/createMigration.js.map +1 -1
  21. package/dist/createVersion.d.ts.map +1 -1
  22. package/dist/createVersion.js +10 -18
  23. package/dist/createVersion.js.map +1 -1
  24. package/dist/deleteMany.d.ts.map +1 -1
  25. package/dist/deleteMany.js +2 -5
  26. package/dist/deleteMany.js.map +1 -1
  27. package/dist/deleteOne.d.ts.map +1 -1
  28. package/dist/deleteOne.js +4 -7
  29. package/dist/deleteOne.js.map +1 -1
  30. package/dist/deleteVersions.d.ts.map +1 -1
  31. package/dist/deleteVersions.js +2 -6
  32. package/dist/deleteVersions.js.map +1 -1
  33. package/dist/destroy.d.ts.map +1 -1
  34. package/dist/destroy.js +11 -7
  35. package/dist/destroy.js.map +1 -1
  36. package/dist/exports/migration-utils.d.ts +2 -0
  37. package/dist/exports/migration-utils.d.ts.map +1 -0
  38. package/dist/exports/migration-utils.js +3 -0
  39. package/dist/exports/migration-utils.js.map +1 -0
  40. package/dist/find/buildFindManyArgs.d.ts +5 -1
  41. package/dist/find/buildFindManyArgs.d.ts.map +1 -1
  42. package/dist/find/buildFindManyArgs.js +4 -3
  43. package/dist/find/buildFindManyArgs.js.map +1 -1
  44. package/dist/find/findMany.d.ts.map +1 -1
  45. package/dist/find/findMany.js +5 -16
  46. package/dist/find/findMany.js.map +1 -1
  47. package/dist/find/traverseFields.d.ts +3 -2
  48. package/dist/find/traverseFields.d.ts.map +1 -1
  49. package/dist/find/traverseFields.js +26 -24
  50. package/dist/find/traverseFields.js.map +1 -1
  51. package/dist/find.d.ts.map +1 -1
  52. package/dist/find.js +2 -5
  53. package/dist/find.js.map +1 -1
  54. package/dist/findGlobal.d.ts.map +1 -1
  55. package/dist/findGlobal.js +2 -5
  56. package/dist/findGlobal.js.map +1 -1
  57. package/dist/findGlobalVersions.d.ts.map +1 -1
  58. package/dist/findGlobalVersions.js +2 -6
  59. package/dist/findGlobalVersions.js.map +1 -1
  60. package/dist/findOne.d.ts.map +1 -1
  61. package/dist/findOne.js +2 -5
  62. package/dist/findOne.js.map +1 -1
  63. package/dist/findVersions.d.ts.map +1 -1
  64. package/dist/findVersions.js +2 -6
  65. package/dist/findVersions.js.map +1 -1
  66. package/dist/index.d.ts.map +1 -1
  67. package/dist/index.js +17 -8
  68. package/dist/index.js.map +1 -1
  69. package/dist/init.d.ts.map +1 -1
  70. package/dist/init.js +19 -22
  71. package/dist/init.js.map +1 -1
  72. package/dist/migrate.js.map +1 -1
  73. package/dist/migrateDown.js.map +1 -1
  74. package/dist/migrateFresh.js.map +1 -1
  75. package/dist/migrateRefresh.js.map +1 -1
  76. package/dist/migrateReset.js.map +1 -1
  77. package/dist/predefinedMigrations/relationships-v2-v3.d.ts +4 -0
  78. package/dist/predefinedMigrations/relationships-v2-v3.d.ts.map +1 -0
  79. package/dist/predefinedMigrations/relationships-v2-v3.js.map +1 -0
  80. package/dist/predefinedMigrations/relationships-v2-v3.mjs +11 -0
  81. package/dist/predefinedMigrations/v2-v3/fetchAndResave/index.d.ts +20 -0
  82. package/dist/predefinedMigrations/v2-v3/fetchAndResave/index.d.ts.map +1 -0
  83. package/dist/predefinedMigrations/v2-v3/fetchAndResave/index.js +170 -0
  84. package/dist/predefinedMigrations/v2-v3/fetchAndResave/index.js.map +1 -0
  85. package/dist/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.d.ts +11 -0
  86. package/dist/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.d.ts.map +1 -0
  87. package/dist/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.js +191 -0
  88. package/dist/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.js.map +1 -0
  89. package/dist/predefinedMigrations/v2-v3/groupUpSQLStatements.d.ts +3 -0
  90. package/dist/predefinedMigrations/v2-v3/groupUpSQLStatements.d.ts.map +1 -0
  91. package/dist/predefinedMigrations/v2-v3/groupUpSQLStatements.js +56 -0
  92. package/dist/predefinedMigrations/v2-v3/groupUpSQLStatements.js.map +1 -0
  93. package/dist/predefinedMigrations/v2-v3/index.d.ts +24 -0
  94. package/dist/predefinedMigrations/v2-v3/index.d.ts.map +1 -0
  95. package/dist/predefinedMigrations/v2-v3/index.js +211 -0
  96. package/dist/predefinedMigrations/v2-v3/index.js.map +1 -0
  97. package/dist/predefinedMigrations/v2-v3/migrateRelationships.d.ts +19 -0
  98. package/dist/predefinedMigrations/v2-v3/migrateRelationships.d.ts.map +1 -0
  99. package/dist/predefinedMigrations/v2-v3/migrateRelationships.js +57 -0
  100. package/dist/predefinedMigrations/v2-v3/migrateRelationships.js.map +1 -0
  101. package/dist/predefinedMigrations/v2-v3/traverseFields.d.ts +23 -0
  102. package/dist/predefinedMigrations/v2-v3/traverseFields.d.ts.map +1 -0
  103. package/dist/predefinedMigrations/v2-v3/traverseFields.js +85 -0
  104. package/dist/predefinedMigrations/v2-v3/traverseFields.js.map +1 -0
  105. package/dist/predefinedMigrations/v2-v3/types.d.ts +9 -0
  106. package/dist/predefinedMigrations/v2-v3/types.d.ts.map +1 -0
  107. package/dist/predefinedMigrations/v2-v3/types.js +6 -0
  108. package/dist/predefinedMigrations/v2-v3/types.js.map +1 -0
  109. package/dist/queries/buildAndOrConditions.d.ts +3 -4
  110. package/dist/queries/buildAndOrConditions.d.ts.map +1 -1
  111. package/dist/queries/buildAndOrConditions.js +1 -2
  112. package/dist/queries/buildAndOrConditions.js.map +1 -1
  113. package/dist/queries/buildQuery.d.ts +1 -2
  114. package/dist/queries/buildQuery.d.ts.map +1 -1
  115. package/dist/queries/buildQuery.js +1 -5
  116. package/dist/queries/buildQuery.js.map +1 -1
  117. package/dist/queries/getTableColumnFromPath.d.ts +3 -4
  118. package/dist/queries/getTableColumnFromPath.d.ts.map +1 -1
  119. package/dist/queries/getTableColumnFromPath.js +248 -143
  120. package/dist/queries/getTableColumnFromPath.js.map +1 -1
  121. package/dist/queries/parseParams.d.ts +3 -4
  122. package/dist/queries/parseParams.d.ts.map +1 -1
  123. package/dist/queries/parseParams.js +7 -6
  124. package/dist/queries/parseParams.js.map +1 -1
  125. package/dist/queries/selectDistinct.d.ts +3 -4
  126. package/dist/queries/selectDistinct.d.ts.map +1 -1
  127. package/dist/queries/selectDistinct.js +3 -14
  128. package/dist/queries/selectDistinct.js.map +1 -1
  129. package/dist/queryDrafts.d.ts.map +1 -1
  130. package/dist/queryDrafts.js +2 -6
  131. package/dist/queryDrafts.js.map +1 -1
  132. package/dist/schema/build.d.ts +11 -6
  133. package/dist/schema/build.d.ts.map +1 -1
  134. package/dist/schema/build.js +208 -124
  135. package/dist/schema/build.js.map +1 -1
  136. package/dist/schema/{getTableName.d.ts → createTableName.d.ts} +5 -7
  137. package/dist/schema/createTableName.d.ts.map +1 -0
  138. package/dist/schema/createTableName.js +31 -0
  139. package/dist/schema/createTableName.js.map +1 -0
  140. package/dist/schema/traverseFields.d.ts +4 -6
  141. package/dist/schema/traverseFields.d.ts.map +1 -1
  142. package/dist/schema/traverseFields.js +145 -61
  143. package/dist/schema/traverseFields.js.map +1 -1
  144. package/dist/schema/validateExistingBlockIsIdentical.d.ts +2 -1
  145. package/dist/schema/validateExistingBlockIsIdentical.d.ts.map +1 -1
  146. package/dist/schema/validateExistingBlockIsIdentical.js +13 -7
  147. package/dist/schema/validateExistingBlockIsIdentical.js.map +1 -1
  148. package/dist/transactions/beginTransaction.d.ts.map +1 -1
  149. package/dist/transactions/beginTransaction.js +4 -0
  150. package/dist/transactions/beginTransaction.js.map +1 -1
  151. package/dist/transform/read/index.d.ts +3 -1
  152. package/dist/transform/read/index.d.ts.map +1 -1
  153. package/dist/transform/read/index.js +2 -1
  154. package/dist/transform/read/index.js.map +1 -1
  155. package/dist/transform/read/relationship.d.ts.map +1 -1
  156. package/dist/transform/read/relationship.js +0 -4
  157. package/dist/transform/read/relationship.js.map +1 -1
  158. package/dist/transform/read/traverseFields.d.ts +6 -1
  159. package/dist/transform/read/traverseFields.d.ts.map +1 -1
  160. package/dist/transform/read/traverseFields.js +69 -55
  161. package/dist/transform/read/traverseFields.js.map +1 -1
  162. package/dist/transform/write/array.d.ts.map +1 -1
  163. package/dist/transform/write/array.js.map +1 -1
  164. package/dist/transform/write/blocks.js +1 -1
  165. package/dist/transform/write/blocks.js.map +1 -1
  166. package/dist/transform/write/traverseFields.d.ts.map +1 -1
  167. package/dist/transform/write/traverseFields.js +22 -5
  168. package/dist/transform/write/traverseFields.js.map +1 -1
  169. package/dist/types.d.ts +7 -7
  170. package/dist/types.d.ts.map +1 -1
  171. package/dist/types.js.map +1 -1
  172. package/dist/update.d.ts.map +1 -1
  173. package/dist/update.js +3 -7
  174. package/dist/update.js.map +1 -1
  175. package/dist/updateGlobal.d.ts.map +1 -1
  176. package/dist/updateGlobal.js +2 -5
  177. package/dist/updateGlobal.js.map +1 -1
  178. package/dist/updateGlobalVersion.d.ts.map +1 -1
  179. package/dist/updateGlobalVersion.js +2 -6
  180. package/dist/updateGlobalVersion.js.map +1 -1
  181. package/dist/updateVersion.d.ts.map +1 -1
  182. package/dist/updateVersion.js +2 -6
  183. package/dist/updateVersion.js.map +1 -1
  184. package/dist/upsertRow/index.d.ts +1 -1
  185. package/dist/upsertRow/index.d.ts.map +1 -1
  186. package/dist/upsertRow/index.js +9 -6
  187. package/dist/upsertRow/index.js.map +1 -1
  188. package/dist/upsertRow/insertArrays.d.ts.map +1 -1
  189. package/dist/upsertRow/insertArrays.js +3 -3
  190. package/dist/upsertRow/insertArrays.js.map +1 -1
  191. package/dist/upsertRow/types.d.ts +7 -2
  192. package/dist/upsertRow/types.d.ts.map +1 -1
  193. package/dist/upsertRow/types.js.map +1 -1
  194. package/package.json +30 -28
  195. package/dist/schema/getTableName.d.ts.map +0 -1
  196. package/dist/schema/getTableName.js +0 -31
  197. package/dist/schema/getTableName.js.map +0 -1
  198. package/src/index.ts +0 -156
@@ -1,19 +1,15 @@
1
1
  /* eslint-disable no-param-reassign */ import { relations } from 'drizzle-orm';
2
- import { index, integer, numeric, serial, timestamp, unique, varchar } from 'drizzle-orm/pg-core';
3
- import { getTableName } from './getTableName.js';
2
+ import { foreignKey, index, integer, numeric, serial, timestamp, unique, varchar } from 'drizzle-orm/pg-core';
3
+ import toSnakeCase from 'to-snake-case';
4
+ import { createTableName } from './createTableName.js';
4
5
  import { parentIDColumnMap } from './parentIDColumnMap.js';
5
6
  import { setColumnID } from './setColumnID.js';
6
7
  import { traverseFields } from './traverseFields.js';
7
- export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, buildNumbers, buildRelationships, buildTexts, disableNotNull, disableUnique = false, fields, rootRelationsToBuild, rootRelationships, rootTableIDColType, rootTableName: incomingRootTableName, tableName, timestamps, versions })=>{
8
+ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, disableNotNull, disableUnique = false, fields, rootRelationsToBuild, rootRelationships, rootTableIDColType, rootTableName: incomingRootTableName, tableName, timestamps, versions })=>{
9
+ const isRoot = !incomingRootTableName;
8
10
  const rootTableName = incomingRootTableName || tableName;
9
11
  const columns = baseColumns;
10
12
  const indexes = {};
11
- let hasLocalizedField = false;
12
- let hasLocalizedRelationshipField = false;
13
- let hasManyTextField = false;
14
- let hasManyNumberField = false;
15
- let hasLocalizedManyTextField = false;
16
- let hasLocalizedManyNumberField = false;
17
13
  const localesColumns = {};
18
14
  const localesIndexes = {};
19
15
  let localesTable;
@@ -29,11 +25,8 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, bu
29
25
  columns,
30
26
  fields
31
27
  });
32
- ({ hasLocalizedField, hasLocalizedManyNumberField, hasLocalizedManyTextField, hasLocalizedRelationshipField, hasManyNumberField, hasManyTextField } = traverseFields({
28
+ const { hasLocalizedField, hasLocalizedManyNumberField, hasLocalizedManyTextField, hasLocalizedRelationshipField, hasManyNumberField, hasManyTextField } = traverseFields({
33
29
  adapter,
34
- buildNumbers,
35
- buildRelationships,
36
- buildTexts,
37
30
  columns,
38
31
  disableNotNull,
39
32
  disableUnique,
@@ -49,7 +42,17 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, bu
49
42
  rootTableIDColType: rootTableIDColType || idColType,
50
43
  rootTableName,
51
44
  versions
52
- }));
45
+ });
46
+ // split the relationsToBuild by localized and non-localized
47
+ const localizedRelations = new Map();
48
+ const nonLocalizedRelations = new Map();
49
+ relationsToBuild.forEach(({ type, localized, target }, key)=>{
50
+ const map = localized ? localizedRelations : nonLocalizedRelations;
51
+ map.set(key, {
52
+ type,
53
+ target
54
+ });
55
+ });
53
56
  if (timestamps) {
54
57
  columns.createdAt = timestamp('created_at', {
55
58
  mode: 'string',
@@ -67,134 +70,177 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, bu
67
70
  config[key] = func(cols);
68
71
  return config;
69
72
  }, {});
70
- return Object.entries(indexes).reduce((acc, [colName, func])=>{
73
+ const result = Object.entries(indexes).reduce((acc, [colName, func])=>{
71
74
  acc[colName] = func(cols);
72
75
  return acc;
73
76
  }, extraConfig);
77
+ return result;
74
78
  });
75
79
  adapter.tables[tableName] = table;
76
- if (hasLocalizedField) {
80
+ if (hasLocalizedField || localizedRelations.size) {
77
81
  const localeTableName = `${tableName}${adapter.localesSuffix}`;
78
82
  localesColumns.id = serial('id').primaryKey();
79
83
  localesColumns._locale = adapter.enums.enum__locales('_locale').notNull();
80
- localesColumns._parentID = parentIDColumnMap[idColType]('_parent_id').references(()=>table.id, {
81
- onDelete: 'cascade'
82
- }).notNull();
84
+ localesColumns._parentID = parentIDColumnMap[idColType]('_parent_id').notNull();
83
85
  localesTable = adapter.pgSchema.table(localeTableName, localesColumns, (cols)=>{
84
86
  return Object.entries(localesIndexes).reduce((acc, [colName, func])=>{
85
87
  acc[colName] = func(cols);
86
88
  return acc;
87
89
  }, {
88
- _localeParent: unique(`${localeTableName}_locale_parent_id_unique`).on(cols._locale, cols._parentID)
89
- });
90
- });
91
- adapter.tables[localeTableName] = localesTable;
92
- const localesTableRelations = relations(localesTable, ({ one })=>({
93
- _parentID: one(table, {
94
- fields: [
95
- localesTable._parentID
90
+ _localeParent: unique(`${localeTableName}_locale_parent_id_unique`).on(cols._locale, cols._parentID),
91
+ _parentIdFk: foreignKey({
92
+ name: `${localeTableName}_parent_id_fk`,
93
+ columns: [
94
+ cols._parentID
96
95
  ],
97
- references: [
96
+ foreignColumns: [
98
97
  table.id
99
98
  ]
100
- })
101
- }));
102
- adapter.relations[`relations_${localeTableName}`] = localesTableRelations;
99
+ }).onDelete('cascade')
100
+ });
101
+ });
102
+ adapter.tables[localeTableName] = localesTable;
103
+ adapter.relations[`relations_${localeTableName}`] = relations(localesTable, ({ many, one })=>{
104
+ const result = {};
105
+ result._parentID = one(table, {
106
+ fields: [
107
+ localesTable._parentID
108
+ ],
109
+ references: [
110
+ table.id
111
+ ],
112
+ // name the relationship by what the many() relationName is
113
+ relationName: '_locales'
114
+ });
115
+ localizedRelations.forEach(({ type, target }, key)=>{
116
+ if (type === 'one') {
117
+ result[key] = one(adapter.tables[target], {
118
+ fields: [
119
+ localesTable[key]
120
+ ],
121
+ references: [
122
+ adapter.tables[target].id
123
+ ],
124
+ relationName: key
125
+ });
126
+ }
127
+ if (type === 'many') {
128
+ result[key] = many(adapter.tables[target], {
129
+ relationName: key
130
+ });
131
+ }
132
+ });
133
+ return result;
134
+ });
103
135
  }
104
- if (hasManyTextField && buildTexts) {
105
- const textsTableName = `${rootTableName}_texts`;
106
- const columns = {
107
- id: serial('id').primaryKey(),
108
- order: integer('order').notNull(),
109
- parent: parentIDColumnMap[idColType]('parent_id').references(()=>table.id, {
110
- onDelete: 'cascade'
111
- }).notNull(),
112
- path: varchar('path').notNull(),
113
- text: varchar('text')
114
- };
115
- if (hasLocalizedManyTextField) {
116
- columns.locale = adapter.enums.enum__locales('locale');
117
- }
118
- textsTable = adapter.pgSchema.table(textsTableName, columns, (cols)=>{
119
- const indexes = {
120
- orderParentIdx: index(`${textsTableName}_order_parent_idx`).on(cols.order, cols.parent)
136
+ if (isRoot) {
137
+ if (hasManyTextField) {
138
+ const textsTableName = `${rootTableName}_texts`;
139
+ const columns = {
140
+ id: serial('id').primaryKey(),
141
+ order: integer('order').notNull(),
142
+ parent: parentIDColumnMap[idColType]('parent_id').notNull(),
143
+ path: varchar('path').notNull(),
144
+ text: varchar('text')
121
145
  };
122
- if (hasManyTextField === 'index') {
123
- indexes.text_idx = index(`${textsTableName}_text_idx`).on(cols.text);
124
- }
125
146
  if (hasLocalizedManyTextField) {
126
- indexes.localeParent = index(`${textsTableName}_locale_parent`).on(cols.locale, cols.parent);
147
+ columns.locale = adapter.enums.enum__locales('locale');
127
148
  }
128
- return indexes;
129
- });
130
- adapter.tables[textsTableName] = textsTable;
131
- const textsTableRelations = relations(textsTable, ({ one })=>({
132
- parent: one(table, {
133
- fields: [
134
- textsTable.parent
135
- ],
136
- references: [
137
- table.id
138
- ]
139
- })
140
- }));
141
- adapter.relations[`relations_${textsTableName}`] = textsTableRelations;
142
- }
143
- if (hasManyNumberField && buildNumbers) {
144
- const numbersTableName = `${rootTableName}_numbers`;
145
- const columns = {
146
- id: serial('id').primaryKey(),
147
- number: numeric('number'),
148
- order: integer('order').notNull(),
149
- parent: parentIDColumnMap[idColType]('parent_id').references(()=>table.id, {
150
- onDelete: 'cascade'
151
- }).notNull(),
152
- path: varchar('path').notNull()
153
- };
154
- if (hasLocalizedManyNumberField) {
155
- columns.locale = adapter.enums.enum__locales('locale');
149
+ textsTable = adapter.pgSchema.table(textsTableName, columns, (cols)=>{
150
+ const config = {
151
+ orderParentIdx: index(`${textsTableName}_order_parent_idx`).on(cols.order, cols.parent),
152
+ parentFk: foreignKey({
153
+ name: `${textsTableName}_parent_fk`,
154
+ columns: [
155
+ cols.parent
156
+ ],
157
+ foreignColumns: [
158
+ table.id
159
+ ]
160
+ }).onDelete('cascade')
161
+ };
162
+ if (hasManyTextField === 'index') {
163
+ config.text_idx = index(`${textsTableName}_text_idx`).on(cols.text);
164
+ }
165
+ if (hasLocalizedManyTextField) {
166
+ config.localeParent = index(`${textsTableName}_locale_parent`).on(cols.locale, cols.parent);
167
+ }
168
+ return config;
169
+ });
170
+ adapter.tables[textsTableName] = textsTable;
171
+ adapter.relations[`relations_${textsTableName}`] = relations(textsTable, ({ one })=>({
172
+ parent: one(table, {
173
+ fields: [
174
+ textsTable.parent
175
+ ],
176
+ references: [
177
+ table.id
178
+ ],
179
+ relationName: '_texts'
180
+ })
181
+ }));
156
182
  }
157
- numbersTable = adapter.pgSchema.table(numbersTableName, columns, (cols)=>{
158
- const indexes = {
159
- orderParentIdx: index(`${numbersTableName}_order_parent_idx`).on(cols.order, cols.parent)
183
+ if (hasManyNumberField) {
184
+ const numbersTableName = `${rootTableName}_numbers`;
185
+ const columns = {
186
+ id: serial('id').primaryKey(),
187
+ number: numeric('number'),
188
+ order: integer('order').notNull(),
189
+ parent: parentIDColumnMap[idColType]('parent_id').notNull(),
190
+ path: varchar('path').notNull()
160
191
  };
161
- if (hasManyNumberField === 'index') {
162
- indexes.numberIdx = index(`${numbersTableName}_number_idx`).on(cols.number);
163
- }
164
192
  if (hasLocalizedManyNumberField) {
165
- indexes.localeParent = index(`${numbersTableName}_locale_parent`).on(cols.locale, cols.parent);
193
+ columns.locale = adapter.enums.enum__locales('locale');
166
194
  }
167
- return indexes;
168
- });
169
- adapter.tables[numbersTableName] = numbersTable;
170
- const numbersTableRelations = relations(numbersTable, ({ one })=>({
171
- parent: one(table, {
172
- fields: [
173
- numbersTable.parent
174
- ],
175
- references: [
176
- table.id
177
- ]
178
- })
179
- }));
180
- adapter.relations[`relations_${numbersTableName}`] = numbersTableRelations;
181
- }
182
- if (buildRelationships) {
195
+ numbersTable = adapter.pgSchema.table(numbersTableName, columns, (cols)=>{
196
+ const config = {
197
+ orderParentIdx: index(`${numbersTableName}_order_parent_idx`).on(cols.order, cols.parent),
198
+ parentFk: foreignKey({
199
+ name: `${numbersTableName}_parent_fk`,
200
+ columns: [
201
+ cols.parent
202
+ ],
203
+ foreignColumns: [
204
+ table.id
205
+ ]
206
+ }).onDelete('cascade')
207
+ };
208
+ if (hasManyNumberField === 'index') {
209
+ config.numberIdx = index(`${numbersTableName}_number_idx`).on(cols.number);
210
+ }
211
+ if (hasLocalizedManyNumberField) {
212
+ config.localeParent = index(`${numbersTableName}_locale_parent`).on(cols.locale, cols.parent);
213
+ }
214
+ return config;
215
+ });
216
+ adapter.tables[numbersTableName] = numbersTable;
217
+ adapter.relations[`relations_${numbersTableName}`] = relations(numbersTable, ({ one })=>({
218
+ parent: one(table, {
219
+ fields: [
220
+ numbersTable.parent
221
+ ],
222
+ references: [
223
+ table.id
224
+ ],
225
+ relationName: '_numbers'
226
+ })
227
+ }));
228
+ }
183
229
  if (relationships.size) {
184
230
  const relationshipColumns = {
185
231
  id: serial('id').primaryKey(),
186
232
  order: integer('order'),
187
- parent: parentIDColumnMap[idColType]('parent_id').references(()=>table.id, {
188
- onDelete: 'cascade'
189
- }).notNull(),
233
+ parent: parentIDColumnMap[idColType]('parent_id').notNull(),
190
234
  path: varchar('path').notNull()
191
235
  };
192
236
  if (hasLocalizedRelationshipField) {
193
237
  relationshipColumns.locale = adapter.enums.enum__locales('locale');
194
238
  }
239
+ const relationExtraConfig = {};
240
+ const relationshipsTableName = `${tableName}${adapter.relationshipsSuffix}`;
195
241
  relationships.forEach((relationTo)=>{
196
242
  const relationshipConfig = adapter.payload.collections[relationTo].config;
197
- const formattedRelationTo = getTableName({
243
+ const formattedRelationTo = createTableName({
198
244
  adapter,
199
245
  config: relationshipConfig,
200
246
  throwValidationError: true
@@ -203,24 +249,42 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, bu
203
249
  const relatedCollectionCustomIDType = adapter.payload.collections[relationshipConfig.slug]?.customIDType;
204
250
  if (relatedCollectionCustomIDType === 'number') colType = 'numeric';
205
251
  if (relatedCollectionCustomIDType === 'text') colType = 'varchar';
206
- relationshipColumns[`${relationTo}ID`] = parentIDColumnMap[colType](`${formattedRelationTo}_id`).references(()=>adapter.tables[formattedRelationTo].id, {
207
- onDelete: 'cascade'
208
- });
252
+ relationshipColumns[`${relationTo}ID`] = parentIDColumnMap[colType](`${formattedRelationTo}_id`);
253
+ relationExtraConfig[`${relationTo}IdFk`] = (cols)=>foreignKey({
254
+ name: `${relationshipsTableName}_${toSnakeCase(relationTo)}_fk`,
255
+ columns: [
256
+ cols[`${relationTo}ID`]
257
+ ],
258
+ foreignColumns: [
259
+ adapter.tables[formattedRelationTo].id
260
+ ]
261
+ }).onDelete('cascade');
209
262
  });
210
- const relationshipsTableName = `${tableName}${adapter.relationshipsSuffix}`;
211
263
  relationshipsTable = adapter.pgSchema.table(relationshipsTableName, relationshipColumns, (cols)=>{
212
- const result = {
264
+ const result = Object.entries(relationExtraConfig).reduce((config, [key, func])=>{
265
+ config[key] = func(cols);
266
+ return config;
267
+ }, {
213
268
  order: index(`${relationshipsTableName}_order_idx`).on(cols.order),
269
+ parentFk: foreignKey({
270
+ name: `${relationshipsTableName}_parent_fk`,
271
+ columns: [
272
+ cols.parent
273
+ ],
274
+ foreignColumns: [
275
+ table.id
276
+ ]
277
+ }).onDelete('cascade'),
214
278
  parentIdx: index(`${relationshipsTableName}_parent_idx`).on(cols.parent),
215
279
  pathIdx: index(`${relationshipsTableName}_path_idx`).on(cols.path)
216
- };
280
+ });
217
281
  if (hasLocalizedRelationshipField) {
218
282
  result.localeIdx = index(`${relationshipsTableName}_locale_idx`).on(cols.locale);
219
283
  }
220
284
  return result;
221
285
  });
222
286
  adapter.tables[relationshipsTableName] = relationshipsTable;
223
- const relationshipsTableRelations = relations(relationshipsTable, ({ one })=>{
287
+ adapter.relations[`relations_${relationshipsTableName}`] = relations(relationshipsTable, ({ one })=>{
224
288
  const result = {
225
289
  parent: one(table, {
226
290
  fields: [
@@ -233,7 +297,7 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, bu
233
297
  })
234
298
  };
235
299
  relationships.forEach((relationTo)=>{
236
- const relatedTableName = getTableName({
300
+ const relatedTableName = createTableName({
237
301
  adapter,
238
302
  config: adapter.payload.collections[relationTo].config,
239
303
  throwValidationError: true
@@ -245,27 +309,48 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, bu
245
309
  ],
246
310
  references: [
247
311
  adapter.tables[relatedTableName].id
248
- ]
312
+ ],
313
+ relationName: relationTo
249
314
  });
250
315
  });
251
316
  return result;
252
317
  });
253
- adapter.relations[`relations_${relationshipsTableName}`] = relationshipsTableRelations;
254
318
  }
255
319
  }
256
- const tableRelations = relations(table, ({ many })=>{
320
+ adapter.relations[`relations_${tableName}`] = relations(table, ({ many, one })=>{
257
321
  const result = {};
258
- relationsToBuild.forEach((val, key)=>{
259
- result[key] = many(adapter.tables[val]);
322
+ nonLocalizedRelations.forEach(({ type, target }, key)=>{
323
+ if (type === 'one') {
324
+ result[key] = one(adapter.tables[target], {
325
+ fields: [
326
+ table[key]
327
+ ],
328
+ references: [
329
+ adapter.tables[target].id
330
+ ],
331
+ relationName: key
332
+ });
333
+ }
334
+ if (type === 'many') {
335
+ result[key] = many(adapter.tables[target], {
336
+ relationName: key
337
+ });
338
+ }
260
339
  });
261
340
  if (hasLocalizedField) {
262
- result._locales = many(localesTable);
341
+ result._locales = many(localesTable, {
342
+ relationName: '_locales'
343
+ });
263
344
  }
264
345
  if (hasManyTextField) {
265
- result._texts = many(textsTable);
346
+ result._texts = many(textsTable, {
347
+ relationName: '_texts'
348
+ });
266
349
  }
267
350
  if (hasManyNumberField) {
268
- result._numbers = many(numbersTable);
351
+ result._numbers = many(numbersTable, {
352
+ relationName: '_numbers'
353
+ });
269
354
  }
270
355
  if (relationships.size && relationshipsTable) {
271
356
  result._rels = many(relationshipsTable, {
@@ -274,7 +359,6 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, bu
274
359
  }
275
360
  return result;
276
361
  });
277
- adapter.relations[`relations_${tableName}`] = tableRelations;
278
362
  return {
279
363
  hasManyNumberField,
280
364
  hasManyTextField,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/schema/build.ts"],"sourcesContent":["/* eslint-disable no-param-reassign */\nimport type { Relation } from 'drizzle-orm'\nimport type {\n IndexBuilder,\n PgColumnBuilder,\n PgTableWithColumns,\n UniqueConstraintBuilder,\n} from 'drizzle-orm/pg-core'\nimport type { Field } from 'payload/types'\n\nimport { relations } from 'drizzle-orm'\nimport { index, integer, numeric, serial, timestamp, unique, varchar } from 'drizzle-orm/pg-core'\nimport { fieldAffectsData } from 'payload/types'\n\nimport type { GenericColumns, GenericTable, IDType, PostgresAdapter } from '../types.js'\n\nimport { getTableName } from './getTableName.js'\nimport { parentIDColumnMap } from './parentIDColumnMap.js'\nimport { setColumnID } from './setColumnID.js'\nimport { traverseFields } from './traverseFields.js'\n\ntype Args = {\n adapter: PostgresAdapter\n baseColumns?: Record<string, PgColumnBuilder>\n baseExtraConfig?: Record<string, (cols: GenericColumns) => IndexBuilder | UniqueConstraintBuilder>\n buildNumbers?: boolean\n buildRelationships?: boolean\n buildTexts?: boolean\n disableNotNull: boolean\n disableUnique: boolean\n fields: Field[]\n rootRelationsToBuild?: Map<string, string>\n rootRelationships?: Set<string>\n rootTableIDColType?: string\n rootTableName?: string\n tableName: string\n timestamps?: boolean\n versions: boolean\n}\n\ntype Result = {\n hasManyNumberField: 'index' | boolean\n hasManyTextField: 'index' | boolean\n relationsToBuild: Map<string, string>\n}\n\nexport const buildTable = ({\n adapter,\n baseColumns = {},\n baseExtraConfig = {},\n buildNumbers,\n buildRelationships,\n buildTexts,\n disableNotNull,\n disableUnique = false,\n fields,\n rootRelationsToBuild,\n rootRelationships,\n rootTableIDColType,\n rootTableName: incomingRootTableName,\n tableName,\n timestamps,\n versions,\n}: Args): Result => {\n const rootTableName = incomingRootTableName || tableName\n const columns: Record<string, PgColumnBuilder> = baseColumns\n const indexes: Record<string, (cols: GenericColumns) => IndexBuilder> = {}\n\n let hasLocalizedField = false\n let hasLocalizedRelationshipField = false\n let hasManyTextField: 'index' | boolean = false\n let hasManyNumberField: 'index' | boolean = false\n let hasLocalizedManyTextField = false\n let hasLocalizedManyNumberField = false\n\n const localesColumns: Record<string, PgColumnBuilder> = {}\n const localesIndexes: Record<string, (cols: GenericColumns) => IndexBuilder> = {}\n let localesTable: GenericTable | PgTableWithColumns<any>\n let textsTable: GenericTable | PgTableWithColumns<any>\n let numbersTable: GenericTable | PgTableWithColumns<any>\n\n // Relationships to the base collection\n const relationships: Set<string> = rootRelationships || new Set()\n\n let relationshipsTable: GenericTable | PgTableWithColumns<any>\n\n // Drizzle relations\n const relationsToBuild: Map<string, string> = new Map()\n\n const idColType: IDType = setColumnID({ adapter, columns, fields })\n\n ;({\n hasLocalizedField,\n hasLocalizedManyNumberField,\n hasLocalizedManyTextField,\n hasLocalizedRelationshipField,\n hasManyNumberField,\n hasManyTextField,\n } = traverseFields({\n adapter,\n buildNumbers,\n buildRelationships,\n buildTexts,\n columns,\n disableNotNull,\n disableUnique,\n fields,\n indexes,\n localesColumns,\n localesIndexes,\n newTableName: tableName,\n parentTableName: tableName,\n relationsToBuild,\n relationships,\n rootRelationsToBuild: rootRelationsToBuild || relationsToBuild,\n rootTableIDColType: rootTableIDColType || idColType,\n rootTableName,\n versions,\n }))\n\n if (timestamps) {\n columns.createdAt = timestamp('created_at', {\n mode: 'string',\n precision: 3,\n withTimezone: true,\n })\n .defaultNow()\n .notNull()\n columns.updatedAt = timestamp('updated_at', {\n mode: 'string',\n precision: 3,\n withTimezone: true,\n })\n .defaultNow()\n .notNull()\n }\n\n const table = adapter.pgSchema.table(tableName, columns, (cols) => {\n const extraConfig = Object.entries(baseExtraConfig).reduce((config, [key, func]) => {\n config[key] = func(cols)\n return config\n }, {})\n\n return Object.entries(indexes).reduce((acc, [colName, func]) => {\n acc[colName] = func(cols)\n return acc\n }, extraConfig)\n })\n\n adapter.tables[tableName] = table\n\n if (hasLocalizedField) {\n const localeTableName = `${tableName}${adapter.localesSuffix}`\n localesColumns.id = serial('id').primaryKey()\n localesColumns._locale = adapter.enums.enum__locales('_locale').notNull()\n localesColumns._parentID = parentIDColumnMap[idColType]('_parent_id')\n .references(() => table.id, { onDelete: 'cascade' })\n .notNull()\n\n localesTable = adapter.pgSchema.table(localeTableName, localesColumns, (cols) => {\n return Object.entries(localesIndexes).reduce(\n (acc, [colName, func]) => {\n acc[colName] = func(cols)\n return acc\n },\n {\n _localeParent: unique(`${localeTableName}_locale_parent_id_unique`).on(\n cols._locale,\n cols._parentID,\n ),\n },\n )\n })\n\n adapter.tables[localeTableName] = localesTable\n\n const localesTableRelations = relations(localesTable, ({ one }) => ({\n _parentID: one(table, {\n fields: [localesTable._parentID],\n references: [table.id],\n }),\n }))\n\n adapter.relations[`relations_${localeTableName}`] = localesTableRelations\n }\n\n if (hasManyTextField && buildTexts) {\n const textsTableName = `${rootTableName}_texts`\n const columns: Record<string, PgColumnBuilder> = {\n id: serial('id').primaryKey(),\n order: integer('order').notNull(),\n parent: parentIDColumnMap[idColType]('parent_id')\n .references(() => table.id, { onDelete: 'cascade' })\n .notNull(),\n path: varchar('path').notNull(),\n text: varchar('text'),\n }\n\n if (hasLocalizedManyTextField) {\n columns.locale = adapter.enums.enum__locales('locale')\n }\n\n textsTable = adapter.pgSchema.table(textsTableName, columns, (cols) => {\n const indexes: Record<string, IndexBuilder> = {\n orderParentIdx: index(`${textsTableName}_order_parent_idx`).on(cols.order, cols.parent),\n }\n\n if (hasManyTextField === 'index') {\n indexes.text_idx = index(`${textsTableName}_text_idx`).on(cols.text)\n }\n\n if (hasLocalizedManyTextField) {\n indexes.localeParent = index(`${textsTableName}_locale_parent`).on(cols.locale, cols.parent)\n }\n\n return indexes\n })\n\n adapter.tables[textsTableName] = textsTable\n\n const textsTableRelations = relations(textsTable, ({ one }) => ({\n parent: one(table, {\n fields: [textsTable.parent],\n references: [table.id],\n }),\n }))\n\n adapter.relations[`relations_${textsTableName}`] = textsTableRelations\n }\n\n if (hasManyNumberField && buildNumbers) {\n const numbersTableName = `${rootTableName}_numbers`\n const columns: Record<string, PgColumnBuilder> = {\n id: serial('id').primaryKey(),\n number: numeric('number'),\n order: integer('order').notNull(),\n parent: parentIDColumnMap[idColType]('parent_id')\n .references(() => table.id, { onDelete: 'cascade' })\n .notNull(),\n path: varchar('path').notNull(),\n }\n\n if (hasLocalizedManyNumberField) {\n columns.locale = adapter.enums.enum__locales('locale')\n }\n\n numbersTable = adapter.pgSchema.table(numbersTableName, columns, (cols) => {\n const indexes: Record<string, IndexBuilder> = {\n orderParentIdx: index(`${numbersTableName}_order_parent_idx`).on(cols.order, cols.parent),\n }\n\n if (hasManyNumberField === 'index') {\n indexes.numberIdx = index(`${numbersTableName}_number_idx`).on(cols.number)\n }\n\n if (hasLocalizedManyNumberField) {\n indexes.localeParent = index(`${numbersTableName}_locale_parent`).on(\n cols.locale,\n cols.parent,\n )\n }\n\n return indexes\n })\n\n adapter.tables[numbersTableName] = numbersTable\n\n const numbersTableRelations = relations(numbersTable, ({ one }) => ({\n parent: one(table, {\n fields: [numbersTable.parent],\n references: [table.id],\n }),\n }))\n\n adapter.relations[`relations_${numbersTableName}`] = numbersTableRelations\n }\n\n if (buildRelationships) {\n if (relationships.size) {\n const relationshipColumns: Record<string, PgColumnBuilder> = {\n id: serial('id').primaryKey(),\n order: integer('order'),\n parent: parentIDColumnMap[idColType]('parent_id')\n .references(() => table.id, { onDelete: 'cascade' })\n .notNull(),\n path: varchar('path').notNull(),\n }\n\n if (hasLocalizedRelationshipField) {\n relationshipColumns.locale = adapter.enums.enum__locales('locale')\n }\n\n relationships.forEach((relationTo) => {\n const relationshipConfig = adapter.payload.collections[relationTo].config\n const formattedRelationTo = getTableName({\n adapter,\n config: relationshipConfig,\n throwValidationError: true,\n })\n let colType = adapter.idType === 'uuid' ? 'uuid' : 'integer'\n\n const relatedCollectionCustomIDType =\n adapter.payload.collections[relationshipConfig.slug]?.customIDType\n\n if (relatedCollectionCustomIDType === 'number') colType = 'numeric'\n if (relatedCollectionCustomIDType === 'text') colType = 'varchar'\n\n relationshipColumns[`${relationTo}ID`] = parentIDColumnMap[colType](\n `${formattedRelationTo}_id`,\n ).references(() => adapter.tables[formattedRelationTo].id, { onDelete: 'cascade' })\n })\n\n const relationshipsTableName = `${tableName}${adapter.relationshipsSuffix}`\n\n relationshipsTable = adapter.pgSchema.table(\n relationshipsTableName,\n relationshipColumns,\n (cols) => {\n const result: Record<string, unknown> = {\n order: index(`${relationshipsTableName}_order_idx`).on(cols.order),\n parentIdx: index(`${relationshipsTableName}_parent_idx`).on(cols.parent),\n pathIdx: index(`${relationshipsTableName}_path_idx`).on(cols.path),\n }\n\n if (hasLocalizedRelationshipField) {\n result.localeIdx = index(`${relationshipsTableName}_locale_idx`).on(cols.locale)\n }\n\n return result\n },\n )\n\n adapter.tables[relationshipsTableName] = relationshipsTable\n\n const relationshipsTableRelations = relations(relationshipsTable, ({ one }) => {\n const result: Record<string, Relation<string>> = {\n parent: one(table, {\n fields: [relationshipsTable.parent],\n references: [table.id],\n relationName: '_rels',\n }),\n }\n\n relationships.forEach((relationTo) => {\n const relatedTableName = getTableName({\n adapter,\n config: adapter.payload.collections[relationTo].config,\n throwValidationError: true,\n })\n const idColumnName = `${relationTo}ID`\n result[idColumnName] = one(adapter.tables[relatedTableName], {\n fields: [relationshipsTable[idColumnName]],\n references: [adapter.tables[relatedTableName].id],\n })\n })\n\n return result\n })\n\n adapter.relations[`relations_${relationshipsTableName}`] = relationshipsTableRelations\n }\n }\n\n const tableRelations = relations(table, ({ many }) => {\n const result: Record<string, Relation<string>> = {}\n\n relationsToBuild.forEach((val, key) => {\n result[key] = many(adapter.tables[val])\n })\n\n if (hasLocalizedField) {\n result._locales = many(localesTable)\n }\n\n if (hasManyTextField) {\n result._texts = many(textsTable)\n }\n if (hasManyNumberField) {\n result._numbers = many(numbersTable)\n }\n\n if (relationships.size && relationshipsTable) {\n result._rels = many(relationshipsTable, {\n relationName: '_rels',\n })\n }\n\n return result\n })\n\n adapter.relations[`relations_${tableName}`] = tableRelations\n\n return { hasManyNumberField, hasManyTextField, relationsToBuild }\n}\n"],"names":["relations","index","integer","numeric","serial","timestamp","unique","varchar","getTableName","parentIDColumnMap","setColumnID","traverseFields","buildTable","adapter","baseColumns","baseExtraConfig","buildNumbers","buildRelationships","buildTexts","disableNotNull","disableUnique","fields","rootRelationsToBuild","rootRelationships","rootTableIDColType","rootTableName","incomingRootTableName","tableName","timestamps","versions","columns","indexes","hasLocalizedField","hasLocalizedRelationshipField","hasManyTextField","hasManyNumberField","hasLocalizedManyTextField","hasLocalizedManyNumberField","localesColumns","localesIndexes","localesTable","textsTable","numbersTable","relationships","Set","relationshipsTable","relationsToBuild","Map","idColType","newTableName","parentTableName","createdAt","mode","precision","withTimezone","defaultNow","notNull","updatedAt","table","pgSchema","cols","extraConfig","Object","entries","reduce","config","key","func","acc","colName","tables","localeTableName","localesSuffix","id","primaryKey","_locale","enums","enum__locales","_parentID","references","onDelete","_localeParent","on","localesTableRelations","one","textsTableName","order","parent","path","text","locale","orderParentIdx","text_idx","localeParent","textsTableRelations","numbersTableName","number","numberIdx","numbersTableRelations","size","relationshipColumns","forEach","relationTo","relationshipConfig","payload","collections","formattedRelationTo","throwValidationError","colType","idType","relatedCollectionCustomIDType","slug","customIDType","relationshipsTableName","relationshipsSuffix","result","parentIdx","pathIdx","localeIdx","relationshipsTableRelations","relationName","relatedTableName","idColumnName","tableRelations","many","val","_locales","_texts","_numbers","_rels"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,oCAAoC,GAUpC,SAASA,SAAS,QAAQ,cAAa;AACvC,SAASC,KAAK,EAAEC,OAAO,EAAEC,OAAO,EAAEC,MAAM,EAAEC,SAAS,EAAEC,MAAM,EAAEC,OAAO,QAAQ,sBAAqB;AAKjG,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,WAAW,QAAQ,mBAAkB;AAC9C,SAASC,cAAc,QAAQ,sBAAqB;AA2BpD,OAAO,MAAMC,aAAa,CAAC,EACzBC,OAAO,EACPC,cAAc,CAAC,CAAC,EAChBC,kBAAkB,CAAC,CAAC,EACpBC,YAAY,EACZC,kBAAkB,EAClBC,UAAU,EACVC,cAAc,EACdC,gBAAgB,KAAK,EACrBC,MAAM,EACNC,oBAAoB,EACpBC,iBAAiB,EACjBC,kBAAkB,EAClBC,eAAeC,qBAAqB,EACpCC,SAAS,EACTC,UAAU,EACVC,QAAQ,EACH;IACL,MAAMJ,gBAAgBC,yBAAyBC;IAC/C,MAAMG,UAA2ChB;IACjD,MAAMiB,UAAkE,CAAC;IAEzE,IAAIC,oBAAoB;IACxB,IAAIC,gCAAgC;IACpC,IAAIC,mBAAsC;IAC1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ACtCa,MAAM,CAACO,aAAa,GAAGtC,IAAIvE,QAAQyD,MAAM,CAACmD,iBAAiB,EAAE;wBAC3DpG,QAAQ;4BAACwB,kBAAkB,CAAC6E,aAAa;yBAAC;wBAC1C3C,YAAY;4BAAClE,QAAQyD,MAAM,CAACmD,iBAAiB,CAAChD,EAAE;yBAAC;oBACnD;gBACF;gBAEA,OAAO0C;YACT;YAEAtG,QAAQb,SAAS,CAAC,CAAC,UAAU,EAAEiH,uBAAuB,CAAC,CAAC,GAAGM;QAC7D;IACF;IAEA,MAAMI,iBAAiB3H,UAAU0D,OAAO,CAAC,EAAEkE,IAAI,EAAE;QAC/C,MAAMT,SAA2C,CAAC;QAElDrE,iBAAiBuD,OAAO,CAAC,CAACwB,KAAK3D;YAC7BiD,MAAM,CAACjD,IAAI,GAAG0D,KAAK/G,QAAQyD,MAAM,CAACuD,IAAI;QACxC;QAEA,IAAI7F,mBAAmB;YACrBmF,OAAOW,QAAQ,GAAGF,KAAKpF;QACzB;QAEA,IAAIN,kBAAkB;YACpBiF,OAAOY,MAAM,GAAGH,KAAKnF;QACvB;QACA,IAAIN,oBAAoB;YACtBgF,OAAOa,QAAQ,GAAGJ,KAAKlF;QACzB;QAEA,IAAIC,cAAcwD,IAAI,IAAItD,oBAAoB;YAC5CsE,OAAOc,KAAK,GAAGL,KAAK/E,oBAAoB;gBACtC2E,cAAc;YAChB;QACF;QAEA,OAAOL;IACT;IAEAtG,QAAQb,SAAS,CAAC,CAAC,UAAU,EAAE2B,UAAU,CAAC,CAAC,GAAGgG;IAE9C,OAAO;QAAExF;QAAoBD;QAAkBY;IAAiB;AAClE,EAAC"}
1
+ {"version":3,"sources":["../../src/schema/build.ts"],"sourcesContent":["/* eslint-disable no-param-reassign */\nimport type { Relation } from 'drizzle-orm'\nimport type {\n ForeignKeyBuilder,\n IndexBuilder,\n PgColumnBuilder,\n PgTableWithColumns,\n UniqueConstraintBuilder,\n} from 'drizzle-orm/pg-core'\nimport type { Field } from 'payload/types'\n\nimport { relations } from 'drizzle-orm'\nimport {\n foreignKey,\n index,\n integer,\n numeric,\n serial,\n timestamp,\n unique,\n varchar,\n} from 'drizzle-orm/pg-core'\nimport toSnakeCase from 'to-snake-case'\n\nimport type { GenericColumns, GenericTable, IDType, PostgresAdapter } from '../types.js'\n\nimport { createTableName } from './createTableName.js'\nimport { parentIDColumnMap } from './parentIDColumnMap.js'\nimport { setColumnID } from './setColumnID.js'\nimport { traverseFields } from './traverseFields.js'\n\nexport type BaseExtraConfig = Record<\n string,\n (cols: GenericColumns) => ForeignKeyBuilder | IndexBuilder | UniqueConstraintBuilder\n>\n\nexport type RelationMap = Map<string, { localized: boolean; target: string; type: 'many' | 'one' }>\n\ntype Args = {\n adapter: PostgresAdapter\n baseColumns?: Record<string, PgColumnBuilder>\n baseExtraConfig?: BaseExtraConfig\n buildNumbers?: boolean\n buildRelationships?: boolean\n disableNotNull: boolean\n disableUnique: boolean\n fields: Field[]\n rootRelationsToBuild?: RelationMap\n rootRelationships?: Set<string>\n rootTableIDColType?: string\n rootTableName?: string\n tableName: string\n timestamps?: boolean\n versions: boolean\n}\n\ntype Result = {\n hasManyNumberField: 'index' | boolean\n hasManyTextField: 'index' | boolean\n relationsToBuild: RelationMap\n}\n\nexport const buildTable = ({\n adapter,\n baseColumns = {},\n baseExtraConfig = {},\n disableNotNull,\n disableUnique = false,\n fields,\n rootRelationsToBuild,\n rootRelationships,\n rootTableIDColType,\n rootTableName: incomingRootTableName,\n tableName,\n timestamps,\n versions,\n}: Args): Result => {\n const isRoot = !incomingRootTableName\n const rootTableName = incomingRootTableName || tableName\n const columns: Record<string, PgColumnBuilder> = baseColumns\n const indexes: Record<string, (cols: GenericColumns) => IndexBuilder> = {}\n\n const localesColumns: Record<string, PgColumnBuilder> = {}\n const localesIndexes: Record<string, (cols: GenericColumns) => IndexBuilder> = {}\n let localesTable: GenericTable | PgTableWithColumns<any>\n let textsTable: GenericTable | PgTableWithColumns<any>\n let numbersTable: GenericTable | PgTableWithColumns<any>\n\n // Relationships to the base collection\n const relationships: Set<string> = rootRelationships || new Set()\n\n let relationshipsTable: GenericTable | PgTableWithColumns<any>\n\n // Drizzle relations\n const relationsToBuild: RelationMap = new Map()\n\n const idColType: IDType = setColumnID({ adapter, columns, fields })\n\n const {\n hasLocalizedField,\n hasLocalizedManyNumberField,\n hasLocalizedManyTextField,\n hasLocalizedRelationshipField,\n hasManyNumberField,\n hasManyTextField,\n } = traverseFields({\n adapter,\n columns,\n disableNotNull,\n disableUnique,\n fields,\n indexes,\n localesColumns,\n localesIndexes,\n newTableName: tableName,\n parentTableName: tableName,\n relationsToBuild,\n relationships,\n rootRelationsToBuild: rootRelationsToBuild || relationsToBuild,\n rootTableIDColType: rootTableIDColType || idColType,\n rootTableName,\n versions,\n })\n\n // split the relationsToBuild by localized and non-localized\n const localizedRelations = new Map()\n const nonLocalizedRelations = new Map()\n\n relationsToBuild.forEach(({ type, localized, target }, key) => {\n const map = localized ? localizedRelations : nonLocalizedRelations\n map.set(key, { type, target })\n })\n\n if (timestamps) {\n columns.createdAt = timestamp('created_at', {\n mode: 'string',\n precision: 3,\n withTimezone: true,\n })\n .defaultNow()\n .notNull()\n columns.updatedAt = timestamp('updated_at', {\n mode: 'string',\n precision: 3,\n withTimezone: true,\n })\n .defaultNow()\n .notNull()\n }\n\n const table = adapter.pgSchema.table(tableName, columns, (cols) => {\n const extraConfig = Object.entries(baseExtraConfig).reduce((config, [key, func]) => {\n config[key] = func(cols)\n return config\n }, {})\n\n const result = Object.entries(indexes).reduce((acc, [colName, func]) => {\n acc[colName] = func(cols)\n return acc\n }, extraConfig)\n\n return result\n })\n\n adapter.tables[tableName] = table\n\n if (hasLocalizedField || localizedRelations.size) {\n const localeTableName = `${tableName}${adapter.localesSuffix}`\n localesColumns.id = serial('id').primaryKey()\n localesColumns._locale = adapter.enums.enum__locales('_locale').notNull()\n localesColumns._parentID = parentIDColumnMap[idColType]('_parent_id').notNull()\n\n localesTable = adapter.pgSchema.table(localeTableName, localesColumns, (cols) => {\n return Object.entries(localesIndexes).reduce(\n (acc, [colName, func]) => {\n acc[colName] = func(cols)\n return acc\n },\n {\n _localeParent: unique(`${localeTableName}_locale_parent_id_unique`).on(\n cols._locale,\n cols._parentID,\n ),\n _parentIdFk: foreignKey({\n name: `${localeTableName}_parent_id_fk`,\n columns: [cols._parentID],\n foreignColumns: [table.id],\n }).onDelete('cascade'),\n },\n )\n })\n\n adapter.tables[localeTableName] = localesTable\n\n adapter.relations[`relations_${localeTableName}`] = relations(localesTable, ({ many, one }) => {\n const result: Record<string, Relation<string>> = {}\n\n result._parentID = one(table, {\n fields: [localesTable._parentID],\n references: [table.id],\n // name the relationship by what the many() relationName is\n relationName: '_locales',\n })\n\n localizedRelations.forEach(({ type, target }, key) => {\n if (type === 'one') {\n result[key] = one(adapter.tables[target], {\n fields: [localesTable[key]],\n references: [adapter.tables[target].id],\n relationName: key,\n })\n }\n if (type === 'many') {\n result[key] = many(adapter.tables[target], {\n relationName: key,\n })\n }\n })\n\n return result\n })\n }\n\n if (isRoot) {\n if (hasManyTextField) {\n const textsTableName = `${rootTableName}_texts`\n const columns: Record<string, PgColumnBuilder> = {\n id: serial('id').primaryKey(),\n order: integer('order').notNull(),\n parent: parentIDColumnMap[idColType]('parent_id').notNull(),\n path: varchar('path').notNull(),\n text: varchar('text'),\n }\n\n if (hasLocalizedManyTextField) {\n columns.locale = adapter.enums.enum__locales('locale')\n }\n\n textsTable = adapter.pgSchema.table(textsTableName, columns, (cols) => {\n const config: Record<string, ForeignKeyBuilder | IndexBuilder> = {\n orderParentIdx: index(`${textsTableName}_order_parent_idx`).on(cols.order, cols.parent),\n parentFk: foreignKey({\n name: `${textsTableName}_parent_fk`,\n columns: [cols.parent],\n foreignColumns: [table.id],\n }).onDelete('cascade'),\n }\n\n if (hasManyTextField === 'index') {\n config.text_idx = index(`${textsTableName}_text_idx`).on(cols.text)\n }\n\n if (hasLocalizedManyTextField) {\n config.localeParent = index(`${textsTableName}_locale_parent`).on(\n cols.locale,\n cols.parent,\n )\n }\n\n return config\n })\n\n adapter.tables[textsTableName] = textsTable\n\n adapter.relations[`relations_${textsTableName}`] = relations(textsTable, ({ one }) => ({\n parent: one(table, {\n fields: [textsTable.parent],\n references: [table.id],\n relationName: '_texts',\n }),\n }))\n }\n\n if (hasManyNumberField) {\n const numbersTableName = `${rootTableName}_numbers`\n const columns: Record<string, PgColumnBuilder> = {\n id: serial('id').primaryKey(),\n number: numeric('number'),\n order: integer('order').notNull(),\n parent: parentIDColumnMap[idColType]('parent_id').notNull(),\n path: varchar('path').notNull(),\n }\n\n if (hasLocalizedManyNumberField) {\n columns.locale = adapter.enums.enum__locales('locale')\n }\n\n numbersTable = adapter.pgSchema.table(numbersTableName, columns, (cols) => {\n const config: Record<string, ForeignKeyBuilder | IndexBuilder> = {\n orderParentIdx: index(`${numbersTableName}_order_parent_idx`).on(cols.order, cols.parent),\n parentFk: foreignKey({\n name: `${numbersTableName}_parent_fk`,\n columns: [cols.parent],\n foreignColumns: [table.id],\n }).onDelete('cascade'),\n }\n\n if (hasManyNumberField === 'index') {\n config.numberIdx = index(`${numbersTableName}_number_idx`).on(cols.number)\n }\n\n if (hasLocalizedManyNumberField) {\n config.localeParent = index(`${numbersTableName}_locale_parent`).on(\n cols.locale,\n cols.parent,\n )\n }\n\n return config\n })\n\n adapter.tables[numbersTableName] = numbersTable\n\n adapter.relations[`relations_${numbersTableName}`] = relations(numbersTable, ({ one }) => ({\n parent: one(table, {\n fields: [numbersTable.parent],\n references: [table.id],\n relationName: '_numbers',\n }),\n }))\n }\n\n if (relationships.size) {\n const relationshipColumns: Record<string, PgColumnBuilder> = {\n id: serial('id').primaryKey(),\n order: integer('order'),\n parent: parentIDColumnMap[idColType]('parent_id').notNull(),\n path: varchar('path').notNull(),\n }\n\n if (hasLocalizedRelationshipField) {\n relationshipColumns.locale = adapter.enums.enum__locales('locale')\n }\n\n const relationExtraConfig: BaseExtraConfig = {}\n const relationshipsTableName = `${tableName}${adapter.relationshipsSuffix}`\n\n relationships.forEach((relationTo) => {\n const relationshipConfig = adapter.payload.collections[relationTo].config\n const formattedRelationTo = createTableName({\n adapter,\n config: relationshipConfig,\n throwValidationError: true,\n })\n let colType = adapter.idType === 'uuid' ? 'uuid' : 'integer'\n const relatedCollectionCustomIDType =\n adapter.payload.collections[relationshipConfig.slug]?.customIDType\n\n if (relatedCollectionCustomIDType === 'number') colType = 'numeric'\n if (relatedCollectionCustomIDType === 'text') colType = 'varchar'\n\n relationshipColumns[`${relationTo}ID`] = parentIDColumnMap[colType](\n `${formattedRelationTo}_id`,\n )\n\n relationExtraConfig[`${relationTo}IdFk`] = (cols) =>\n foreignKey({\n name: `${relationshipsTableName}_${toSnakeCase(relationTo)}_fk`,\n columns: [cols[`${relationTo}ID`]],\n foreignColumns: [adapter.tables[formattedRelationTo].id],\n }).onDelete('cascade')\n })\n\n relationshipsTable = adapter.pgSchema.table(\n relationshipsTableName,\n relationshipColumns,\n (cols) => {\n const result: Record<string, ForeignKeyBuilder | IndexBuilder> = Object.entries(\n relationExtraConfig,\n ).reduce(\n (config, [key, func]) => {\n config[key] = func(cols)\n return config\n },\n {\n order: index(`${relationshipsTableName}_order_idx`).on(cols.order),\n parentFk: foreignKey({\n name: `${relationshipsTableName}_parent_fk`,\n columns: [cols.parent],\n foreignColumns: [table.id],\n }).onDelete('cascade'),\n parentIdx: index(`${relationshipsTableName}_parent_idx`).on(cols.parent),\n pathIdx: index(`${relationshipsTableName}_path_idx`).on(cols.path),\n },\n )\n\n if (hasLocalizedRelationshipField) {\n result.localeIdx = index(`${relationshipsTableName}_locale_idx`).on(cols.locale)\n }\n\n return result\n },\n )\n\n adapter.tables[relationshipsTableName] = relationshipsTable\n\n adapter.relations[`relations_${relationshipsTableName}`] = relations(\n relationshipsTable,\n ({ one }) => {\n const result: Record<string, Relation<string>> = {\n parent: one(table, {\n fields: [relationshipsTable.parent],\n references: [table.id],\n relationName: '_rels',\n }),\n }\n\n relationships.forEach((relationTo) => {\n const relatedTableName = createTableName({\n adapter,\n config: adapter.payload.collections[relationTo].config,\n throwValidationError: true,\n })\n const idColumnName = `${relationTo}ID`\n result[idColumnName] = one(adapter.tables[relatedTableName], {\n fields: [relationshipsTable[idColumnName]],\n references: [adapter.tables[relatedTableName].id],\n relationName: relationTo,\n })\n })\n\n return result\n },\n )\n }\n }\n\n adapter.relations[`relations_${tableName}`] = relations(table, ({ many, one }) => {\n const result: Record<string, Relation<string>> = {}\n\n nonLocalizedRelations.forEach(({ type, target }, key) => {\n if (type === 'one') {\n result[key] = one(adapter.tables[target], {\n fields: [table[key]],\n references: [adapter.tables[target].id],\n relationName: key,\n })\n }\n if (type === 'many') {\n result[key] = many(adapter.tables[target], { relationName: key })\n }\n })\n\n if (hasLocalizedField) {\n result._locales = many(localesTable, { relationName: '_locales' })\n }\n\n if (hasManyTextField) {\n result._texts = many(textsTable, { relationName: '_texts' })\n }\n\n if (hasManyNumberField) {\n result._numbers = many(numbersTable, { relationName: '_numbers' })\n }\n\n if (relationships.size && relationshipsTable) {\n result._rels = many(relationshipsTable, {\n relationName: '_rels',\n })\n }\n\n return result\n })\n\n return { hasManyNumberField, hasManyTextField, relationsToBuild }\n}\n"],"names":["relations","foreignKey","index","integer","numeric","serial","timestamp","unique","varchar","toSnakeCase","createTableName","parentIDColumnMap","setColumnID","traverseFields","buildTable","adapter","baseColumns","baseExtraConfig","disableNotNull","disableUnique","fields","rootRelationsToBuild","rootRelationships","rootTableIDColType","rootTableName","incomingRootTableName","tableName","timestamps","versions","isRoot","columns","indexes","localesColumns","localesIndexes","localesTable","textsTable","numbersTable","relationships","Set","relationshipsTable","relationsToBuild","Map","idColType","hasLocalizedField","hasLocalizedManyNumberField","hasLocalizedManyTextField","hasLocalizedRelationshipField","hasManyNumberField","hasManyTextField","newTableName","parentTableName","localizedRelations","nonLocalizedRelations","forEach","type","localized","target","key","map","set","createdAt","mode","precision","withTimezone","defaultNow","notNull","updatedAt","table","pgSchema","cols","extraConfig","Object","entries","reduce","config","func","result","acc","colName","tables","size","localeTableName","localesSuffix","id","primaryKey","_locale","enums","enum__locales","_parentID","_localeParent","on","_parentIdFk","name","foreignColumns","onDelete","many","one","references","relationName","textsTableName","order","parent","path","text","locale","orderParentIdx","parentFk","text_idx","localeParent","numbersTableName","number","numberIdx","relationshipColumns","relationExtraConfig","relationshipsTableName","relationshipsSuffix","relationTo","relationshipConfig","payload","collections","formattedRelationTo","throwValidationError","colType","idType","relatedCollectionCustomIDType","slug","customIDType","parentIdx","pathIdx","localeIdx","relatedTableName","idColumnName","_locales","_texts","_numbers","_rels"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,oCAAoC,GAWpC,SAASA,SAAS,QAAQ,cAAa;AACvC,SACEC,UAAU,EACVC,KAAK,EACLC,OAAO,EACPC,OAAO,EACPC,MAAM,EACNC,SAAS,EACTC,MAAM,EACNC,OAAO,QACF,sBAAqB;AAC5B,OAAOC,iBAAiB,gBAAe;AAIvC,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,WAAW,QAAQ,mBAAkB;AAC9C,SAASC,cAAc,QAAQ,sBAAqB;AAiCpD,OAAO,MAAMC,aAAa,CAAC,EACzBC,OAAO,EACPC,cAAc,CAAC,CAAC,EAChB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CAAC;QAElDxB,sBAAsBC,OAAO,CAAC,CAAC,EAAEC,IAAI,EAAEE,MAAM,EAAE,EAAEC;YAC/C,IAAIH,SAAS,OAAO;gBAClBsB,MAAM,CAACnB,IAAI,GAAGuC,IAAIjF,QAAQgE,MAAM,CAACvB,OAAO,EAAE;oBACxCpC,QAAQ;wBAAC+C,KAAK,CAACV,IAAI;qBAAC;oBACpBwC,YAAY;wBAAClF,QAAQgE,MAAM,CAACvB,OAAO,CAAC2B,EAAE;qBAAC;oBACvCe,cAAczC;gBAChB;YACF;YACA,IAAIH,SAAS,QAAQ;gBACnBsB,MAAM,CAACnB,IAAI,GAAGsC,KAAKhF,QAAQgE,MAAM,CAACvB,OAAO,EAAE;oBAAE0C,cAAczC;gBAAI;YACjE;QACF;QAEA,IAAId,mBAAmB;YACrBiC,OAAOwD,QAAQ,GAAGrC,KAAK7D,cAAc;gBAAEgE,cAAc;YAAW;QAClE;QAEA,IAAIlD,kBAAkB;YACpB4B,OAAOyD,MAAM,GAAGtC,KAAK5D,YAAY;gBAAE+D,cAAc;YAAS;QAC5D;QAEA,IAAInD,oBAAoB;YACtB6B,OAAO0D,QAAQ,GAAGvC,KAAK3D,cAAc;gBAAE8D,cAAc;YAAW;QAClE;QAEA,IAAI7D,cAAc2C,IAAI,IAAIzC,oBAAoB;YAC5CqC,OAAO2D,KAAK,GAAGxC,KAAKxD,oBAAoB;gBACtC2D,cAAc;YAChB;QACF;QAEA,OAAOtB;IACT;IAEA,OAAO;QAAE7B;QAAoBC;QAAkBR;IAAiB;AAClE,EAAC"}
@@ -9,24 +9,22 @@ type Args = {
9
9
  name?: string;
10
10
  slug?: string;
11
11
  };
12
- /** Localized tables need to be given the locales suffix */
13
- locales?: boolean;
14
12
  /** For nested tables passed for the user custom dbName functions to handle their own iterations */
15
13
  parentTableName?: string;
16
14
  /** For sub tables (array for example) this needs to include the parentTableName */
17
15
  prefix?: string;
18
- /** Adds the relationships suffix */
19
- relationships?: boolean;
20
16
  /** For tables based on fields that could have both enumName and dbName (ie: select with hasMany), default: 'dbName' */
21
17
  target?: 'dbName' | 'enumName';
22
18
  throwValidationError?: boolean;
23
- /** Adds the versions suffix, should only be used on the base collection to duplicate suffixing */
19
+ /** Adds the versions suffix to the default table name - should only be used on the base collection to avoid duplicate suffixing */
24
20
  versions?: boolean;
21
+ /** Adds the versions suffix to custom dbName only - this is used while creating blocks / selects / arrays / etc */
22
+ versionsCustomName?: boolean;
25
23
  };
26
24
  /**
27
25
  * Used to name database enums and tables
28
26
  * Returns the table or enum name for a given entity
29
27
  */
30
- export declare const getTableName: ({ adapter, config: { name, slug }, config, locales, parentTableName, prefix, relationships, target, throwValidationError, versions, }: Args) => string;
28
+ export declare const createTableName: ({ adapter, config: { name, slug }, config, parentTableName, prefix, target, throwValidationError, versions, versionsCustomName, }: Args) => string;
31
29
  export {};
32
- //# sourceMappingURL=getTableName.d.ts.map
30
+ //# sourceMappingURL=createTableName.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createTableName.d.ts","sourceRoot":"","sources":["../../src/schema/createTableName.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAA;AAKxD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAElD,KAAK,IAAI,GAAG;IACV,OAAO,EAAE,eAAe,CAAA;IACxB,8CAA8C;IAC9C,MAAM,EAAE;QACN,MAAM,CAAC,EAAE,gBAAgB,CAAA;QACzB,QAAQ,CAAC,EAAE,gBAAgB,CAAA;QAC3B,IAAI,CAAC,EAAE,MAAM,CAAA;QACb,IAAI,CAAC,EAAE,MAAM,CAAA;KACd,CAAA;IACD,mGAAmG;IACnG,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,mFAAmF;IACnF,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,uHAAuH;IACvH,MAAM,CAAC,EAAE,QAAQ,GAAG,UAAU,CAAA;IAC9B,oBAAoB,CAAC,EAAE,OAAO,CAAA;IAC9B,mIAAmI;IACnI,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,mHAAmH;IACnH,kBAAkB,CAAC,EAAE,OAAO,CAAA;CAC7B,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,eAAe,sIAUzB,IAAI,KAAG,MAsCT,CAAA"}
@@ -0,0 +1,31 @@
1
+ import { APIError } from 'payload/errors';
2
+ import toSnakeCase from 'to-snake-case';
3
+ /**
4
+ * Used to name database enums and tables
5
+ * Returns the table or enum name for a given entity
6
+ */ export const createTableName = ({ adapter, config: { name, slug }, config, parentTableName, prefix = '', target = 'dbName', throwValidationError = false, versions = false, versionsCustomName = false })=>{
7
+ let customNameDefinition = config[target];
8
+ let defaultTableName = `${prefix}${toSnakeCase(name ?? slug)}`;
9
+ if (versions) defaultTableName = `_${defaultTableName}${adapter.versionsSuffix}`;
10
+ let customTableNameResult;
11
+ if (!customNameDefinition && target === 'enumName') {
12
+ customNameDefinition = config['dbName'];
13
+ }
14
+ if (customNameDefinition) {
15
+ customTableNameResult = typeof customNameDefinition === 'function' ? customNameDefinition({
16
+ tableName: parentTableName
17
+ }) : customNameDefinition;
18
+ if (versionsCustomName) customTableNameResult = `_${customTableNameResult}${adapter.versionsSuffix}`;
19
+ }
20
+ const result = customTableNameResult || defaultTableName;
21
+ adapter.tableNameMap.set(defaultTableName, result);
22
+ if (!throwValidationError) {
23
+ return result;
24
+ }
25
+ if (result.length > 63) {
26
+ throw new APIError(`Exceeded max identifier length for table or enum name of 63 characters. Invalid name: ${result}`);
27
+ }
28
+ return result;
29
+ };
30
+
31
+ //# sourceMappingURL=createTableName.js.map