@payloadcms/db-postgres 3.0.0-beta.2 → 3.0.0-beta.20

Sign up to get free protection for your applications and to get access to all the features.
Files changed (119) hide show
  1. package/dist/count.d.ts +3 -0
  2. package/dist/count.d.ts.map +1 -0
  3. package/dist/count.js +50 -0
  4. package/dist/count.js.map +1 -0
  5. package/dist/create.d.ts.map +1 -1
  6. package/dist/create.js +3 -5
  7. package/dist/create.js.map +1 -1
  8. package/dist/createGlobal.d.ts.map +1 -1
  9. package/dist/createGlobal.js +3 -5
  10. package/dist/createGlobal.js.map +1 -1
  11. package/dist/createGlobalVersion.d.ts +1 -1
  12. package/dist/createGlobalVersion.d.ts.map +1 -1
  13. package/dist/createGlobalVersion.js +2 -6
  14. package/dist/createGlobalVersion.js.map +1 -1
  15. package/dist/createVersion.d.ts.map +1 -1
  16. package/dist/createVersion.js +9 -13
  17. package/dist/createVersion.js.map +1 -1
  18. package/dist/deleteMany.d.ts.map +1 -1
  19. package/dist/deleteMany.js +2 -5
  20. package/dist/deleteMany.js.map +1 -1
  21. package/dist/deleteOne.d.ts.map +1 -1
  22. package/dist/deleteOne.js +2 -5
  23. package/dist/deleteOne.js.map +1 -1
  24. package/dist/deleteVersions.d.ts.map +1 -1
  25. package/dist/deleteVersions.js +2 -6
  26. package/dist/deleteVersions.js.map +1 -1
  27. package/dist/destroy.d.ts.map +1 -1
  28. package/dist/destroy.js +7 -7
  29. package/dist/destroy.js.map +1 -1
  30. package/dist/find/buildFindManyArgs.js +2 -2
  31. package/dist/find/buildFindManyArgs.js.map +1 -1
  32. package/dist/find/findMany.d.ts.map +1 -1
  33. package/dist/find/findMany.js +1 -1
  34. package/dist/find/findMany.js.map +1 -1
  35. package/dist/find/traverseFields.d.ts.map +1 -1
  36. package/dist/find/traverseFields.js +4 -20
  37. package/dist/find/traverseFields.js.map +1 -1
  38. package/dist/find.d.ts.map +1 -1
  39. package/dist/find.js +2 -5
  40. package/dist/find.js.map +1 -1
  41. package/dist/findGlobal.d.ts.map +1 -1
  42. package/dist/findGlobal.js +2 -5
  43. package/dist/findGlobal.js.map +1 -1
  44. package/dist/findGlobalVersions.d.ts.map +1 -1
  45. package/dist/findGlobalVersions.js +2 -6
  46. package/dist/findGlobalVersions.js.map +1 -1
  47. package/dist/findOne.d.ts.map +1 -1
  48. package/dist/findOne.js +2 -5
  49. package/dist/findOne.js.map +1 -1
  50. package/dist/findVersions.d.ts.map +1 -1
  51. package/dist/findVersions.js +2 -6
  52. package/dist/findVersions.js.map +1 -1
  53. package/dist/index.d.ts.map +1 -1
  54. package/dist/index.js +8 -8
  55. package/dist/index.js.map +1 -1
  56. package/dist/init.d.ts.map +1 -1
  57. package/dist/init.js +9 -7
  58. package/dist/init.js.map +1 -1
  59. package/dist/migrate.js.map +1 -1
  60. package/dist/migrateDown.js.map +1 -1
  61. package/dist/migrateFresh.js.map +1 -1
  62. package/dist/migrateRefresh.js.map +1 -1
  63. package/dist/migrateReset.js.map +1 -1
  64. package/dist/queries/getTableColumnFromPath.d.ts.map +1 -1
  65. package/dist/queries/getTableColumnFromPath.js +95 -62
  66. package/dist/queries/getTableColumnFromPath.js.map +1 -1
  67. package/dist/queryDrafts.d.ts.map +1 -1
  68. package/dist/queryDrafts.js +2 -6
  69. package/dist/queryDrafts.js.map +1 -1
  70. package/dist/schema/build.d.ts +3 -2
  71. package/dist/schema/build.d.ts.map +1 -1
  72. package/dist/schema/build.js +80 -46
  73. package/dist/schema/build.js.map +1 -1
  74. package/dist/schema/{getTableName.d.ts → createTableName.d.ts} +5 -7
  75. package/dist/schema/createTableName.d.ts.map +1 -0
  76. package/dist/schema/createTableName.js +31 -0
  77. package/dist/schema/createTableName.js.map +1 -0
  78. package/dist/schema/traverseFields.d.ts.map +1 -1
  79. package/dist/schema/traverseFields.js +45 -24
  80. package/dist/schema/traverseFields.js.map +1 -1
  81. package/dist/schema/validateExistingBlockIsIdentical.d.ts +2 -1
  82. package/dist/schema/validateExistingBlockIsIdentical.d.ts.map +1 -1
  83. package/dist/schema/validateExistingBlockIsIdentical.js +13 -7
  84. package/dist/schema/validateExistingBlockIsIdentical.js.map +1 -1
  85. package/dist/transform/write/array.d.ts.map +1 -1
  86. package/dist/transform/write/array.js.map +1 -1
  87. package/dist/transform/write/blocks.js +1 -1
  88. package/dist/transform/write/blocks.js.map +1 -1
  89. package/dist/transform/write/traverseFields.js +2 -2
  90. package/dist/transform/write/traverseFields.js.map +1 -1
  91. package/dist/types.d.ts +4 -7
  92. package/dist/types.d.ts.map +1 -1
  93. package/dist/types.js.map +1 -1
  94. package/dist/update.d.ts.map +1 -1
  95. package/dist/update.js +2 -5
  96. package/dist/update.js.map +1 -1
  97. package/dist/updateGlobal.d.ts.map +1 -1
  98. package/dist/updateGlobal.js +2 -5
  99. package/dist/updateGlobal.js.map +1 -1
  100. package/dist/updateGlobalVersion.d.ts.map +1 -1
  101. package/dist/updateGlobalVersion.js +2 -6
  102. package/dist/updateGlobalVersion.js.map +1 -1
  103. package/dist/updateVersion.d.ts.map +1 -1
  104. package/dist/updateVersion.js +2 -6
  105. package/dist/updateVersion.js.map +1 -1
  106. package/dist/upsertRow/index.d.ts.map +1 -1
  107. package/dist/upsertRow/index.js +6 -5
  108. package/dist/upsertRow/index.js.map +1 -1
  109. package/dist/upsertRow/insertArrays.d.ts.map +1 -1
  110. package/dist/upsertRow/insertArrays.js +3 -3
  111. package/dist/upsertRow/insertArrays.js.map +1 -1
  112. package/dist/upsertRow/types.d.ts +2 -2
  113. package/dist/upsertRow/types.d.ts.map +1 -1
  114. package/dist/upsertRow/types.js.map +1 -1
  115. package/package.json +23 -23
  116. package/dist/schema/getTableName.d.ts.map +0 -1
  117. package/dist/schema/getTableName.js +0 -31
  118. package/dist/schema/getTableName.js.map +0 -1
  119. package/src/index.ts +0 -156
@@ -1,7 +1,7 @@
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 { fieldAffectsData } from 'payload/types';
4
- 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';
5
5
  import { parentIDColumnMap } from './parentIDColumnMap.js';
6
6
  import { setColumnID } from './setColumnID.js';
7
7
  import { traverseFields } from './traverseFields.js';
@@ -9,12 +9,6 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, bu
9
9
  const rootTableName = incomingRootTableName || tableName;
10
10
  const columns = baseColumns;
11
11
  const indexes = {};
12
- let hasLocalizedField = false;
13
- let hasLocalizedRelationshipField = false;
14
- let hasManyTextField = false;
15
- let hasManyNumberField = false;
16
- let hasLocalizedManyTextField = false;
17
- let hasLocalizedManyNumberField = false;
18
12
  const localesColumns = {};
19
13
  const localesIndexes = {};
20
14
  let localesTable;
@@ -30,7 +24,7 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, bu
30
24
  columns,
31
25
  fields
32
26
  });
33
- ({ hasLocalizedField, hasLocalizedManyNumberField, hasLocalizedManyTextField, hasLocalizedRelationshipField, hasManyNumberField, hasManyTextField } = traverseFields({
27
+ const { hasLocalizedField, hasLocalizedManyNumberField, hasLocalizedManyTextField, hasLocalizedRelationshipField, hasManyNumberField, hasManyTextField } = traverseFields({
34
28
  adapter,
35
29
  buildNumbers,
36
30
  buildRelationships,
@@ -50,7 +44,7 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, bu
50
44
  rootTableIDColType: rootTableIDColType || idColType,
51
45
  rootTableName,
52
46
  versions
53
- }));
47
+ });
54
48
  if (timestamps) {
55
49
  columns.createdAt = timestamp('created_at', {
56
50
  mode: 'string',
@@ -68,25 +62,33 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, bu
68
62
  config[key] = func(cols);
69
63
  return config;
70
64
  }, {});
71
- return Object.entries(indexes).reduce((acc, [colName, func])=>{
65
+ const result = Object.entries(indexes).reduce((acc, [colName, func])=>{
72
66
  acc[colName] = func(cols);
73
67
  return acc;
74
68
  }, extraConfig);
69
+ return result;
75
70
  });
76
71
  adapter.tables[tableName] = table;
77
72
  if (hasLocalizedField) {
78
73
  const localeTableName = `${tableName}${adapter.localesSuffix}`;
79
74
  localesColumns.id = serial('id').primaryKey();
80
75
  localesColumns._locale = adapter.enums.enum__locales('_locale').notNull();
81
- localesColumns._parentID = parentIDColumnMap[idColType]('_parent_id').references(()=>table.id, {
82
- onDelete: 'cascade'
83
- }).notNull();
76
+ localesColumns._parentID = parentIDColumnMap[idColType]('_parent_id').notNull();
84
77
  localesTable = adapter.pgSchema.table(localeTableName, localesColumns, (cols)=>{
85
78
  return Object.entries(localesIndexes).reduce((acc, [colName, func])=>{
86
79
  acc[colName] = func(cols);
87
80
  return acc;
88
81
  }, {
89
- _localeParent: unique(`${localeTableName}_locale_parent_id_unique`).on(cols._locale, cols._parentID)
82
+ _localeParent: unique(`${localeTableName}_locale_parent_id_unique`).on(cols._locale, cols._parentID),
83
+ _parentIdFk: foreignKey({
84
+ name: `${localeTableName}_parent_id_fk`,
85
+ columns: [
86
+ cols._parentID
87
+ ],
88
+ foreignColumns: [
89
+ table.id
90
+ ]
91
+ }).onDelete('cascade')
90
92
  });
91
93
  });
92
94
  adapter.tables[localeTableName] = localesTable;
@@ -107,9 +109,7 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, bu
107
109
  const columns = {
108
110
  id: serial('id').primaryKey(),
109
111
  order: integer('order').notNull(),
110
- parent: parentIDColumnMap[idColType]('parent_id').references(()=>table.id, {
111
- onDelete: 'cascade'
112
- }).notNull(),
112
+ parent: parentIDColumnMap[idColType]('parent_id').notNull(),
113
113
  path: varchar('path').notNull(),
114
114
  text: varchar('text')
115
115
  };
@@ -117,16 +117,25 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, bu
117
117
  columns.locale = adapter.enums.enum__locales('locale');
118
118
  }
119
119
  textsTable = adapter.pgSchema.table(textsTableName, columns, (cols)=>{
120
- const indexes = {
121
- orderParentIdx: index(`${textsTableName}_order_parent_idx`).on(cols.order, cols.parent)
120
+ const config = {
121
+ orderParentIdx: index(`${textsTableName}_order_parent_idx`).on(cols.order, cols.parent),
122
+ parentFk: foreignKey({
123
+ name: `${textsTableName}_parent_fk`,
124
+ columns: [
125
+ cols.parent
126
+ ],
127
+ foreignColumns: [
128
+ table.id
129
+ ]
130
+ }).onDelete('cascade')
122
131
  };
123
132
  if (hasManyTextField === 'index') {
124
- indexes.text_idx = index(`${textsTableName}_text_idx`).on(cols.text);
133
+ config.text_idx = index(`${textsTableName}_text_idx`).on(cols.text);
125
134
  }
126
135
  if (hasLocalizedManyTextField) {
127
- indexes.localeParent = index(`${textsTableName}_locale_parent`).on(cols.locale, cols.parent);
136
+ config.localeParent = index(`${textsTableName}_locale_parent`).on(cols.locale, cols.parent);
128
137
  }
129
- return indexes;
138
+ return config;
130
139
  });
131
140
  adapter.tables[textsTableName] = textsTable;
132
141
  const textsTableRelations = relations(textsTable, ({ one })=>({
@@ -147,25 +156,32 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, bu
147
156
  id: serial('id').primaryKey(),
148
157
  number: numeric('number'),
149
158
  order: integer('order').notNull(),
150
- parent: parentIDColumnMap[idColType]('parent_id').references(()=>table.id, {
151
- onDelete: 'cascade'
152
- }).notNull(),
159
+ parent: parentIDColumnMap[idColType]('parent_id').notNull(),
153
160
  path: varchar('path').notNull()
154
161
  };
155
162
  if (hasLocalizedManyNumberField) {
156
163
  columns.locale = adapter.enums.enum__locales('locale');
157
164
  }
158
165
  numbersTable = adapter.pgSchema.table(numbersTableName, columns, (cols)=>{
159
- const indexes = {
160
- orderParentIdx: index(`${numbersTableName}_order_parent_idx`).on(cols.order, cols.parent)
166
+ const config = {
167
+ orderParentIdx: index(`${numbersTableName}_order_parent_idx`).on(cols.order, cols.parent),
168
+ parentFk: foreignKey({
169
+ name: `${numbersTableName}_parent_fk`,
170
+ columns: [
171
+ cols.parent
172
+ ],
173
+ foreignColumns: [
174
+ table.id
175
+ ]
176
+ }).onDelete('cascade')
161
177
  };
162
178
  if (hasManyNumberField === 'index') {
163
- indexes.numberIdx = index(`${numbersTableName}_number_idx`).on(cols.number);
179
+ config.numberIdx = index(`${numbersTableName}_number_idx`).on(cols.number);
164
180
  }
165
181
  if (hasLocalizedManyNumberField) {
166
- indexes.localeParent = index(`${numbersTableName}_locale_parent`).on(cols.locale, cols.parent);
182
+ config.localeParent = index(`${numbersTableName}_locale_parent`).on(cols.locale, cols.parent);
167
183
  }
168
- return indexes;
184
+ return config;
169
185
  });
170
186
  adapter.tables[numbersTableName] = numbersTable;
171
187
  const numbersTableRelations = relations(numbersTable, ({ one })=>({
@@ -185,36 +201,54 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, bu
185
201
  const relationshipColumns = {
186
202
  id: serial('id').primaryKey(),
187
203
  order: integer('order'),
188
- parent: parentIDColumnMap[idColType]('parent_id').references(()=>table.id, {
189
- onDelete: 'cascade'
190
- }).notNull(),
204
+ parent: parentIDColumnMap[idColType]('parent_id').notNull(),
191
205
  path: varchar('path').notNull()
192
206
  };
193
207
  if (hasLocalizedRelationshipField) {
194
208
  relationshipColumns.locale = adapter.enums.enum__locales('locale');
195
209
  }
210
+ const relationExtraConfig = {};
211
+ const relationshipsTableName = `${tableName}${adapter.relationshipsSuffix}`;
196
212
  relationships.forEach((relationTo)=>{
197
213
  const relationshipConfig = adapter.payload.collections[relationTo].config;
198
- const formattedRelationTo = getTableName({
214
+ const formattedRelationTo = createTableName({
199
215
  adapter,
200
216
  config: relationshipConfig,
201
217
  throwValidationError: true
202
218
  });
203
219
  let colType = adapter.idType === 'uuid' ? 'uuid' : 'integer';
204
- const relatedCollectionCustomID = relationshipConfig.fields.find((field)=>fieldAffectsData(field) && field.name === 'id');
205
- if (relatedCollectionCustomID?.type === 'number') colType = 'numeric';
206
- if (relatedCollectionCustomID?.type === 'text') colType = 'varchar';
207
- relationshipColumns[`${relationTo}ID`] = parentIDColumnMap[colType](`${formattedRelationTo}_id`).references(()=>adapter.tables[formattedRelationTo].id, {
208
- onDelete: 'cascade'
209
- });
220
+ const relatedCollectionCustomIDType = adapter.payload.collections[relationshipConfig.slug]?.customIDType;
221
+ if (relatedCollectionCustomIDType === 'number') colType = 'numeric';
222
+ if (relatedCollectionCustomIDType === 'text') colType = 'varchar';
223
+ relationshipColumns[`${relationTo}ID`] = parentIDColumnMap[colType](`${formattedRelationTo}_id`);
224
+ relationExtraConfig[`${relationTo}IdFk`] = (cols)=>foreignKey({
225
+ name: `${relationshipsTableName}_${toSnakeCase(relationTo)}_fk`,
226
+ columns: [
227
+ cols[`${relationTo}ID`]
228
+ ],
229
+ foreignColumns: [
230
+ adapter.tables[formattedRelationTo].id
231
+ ]
232
+ }).onDelete('cascade');
210
233
  });
211
- const relationshipsTableName = `${tableName}${adapter.relationshipsSuffix}`;
212
234
  relationshipsTable = adapter.pgSchema.table(relationshipsTableName, relationshipColumns, (cols)=>{
213
- const result = {
235
+ const result = Object.entries(relationExtraConfig).reduce((config, [key, func])=>{
236
+ config[key] = func(cols);
237
+ return config;
238
+ }, {
214
239
  order: index(`${relationshipsTableName}_order_idx`).on(cols.order),
240
+ parentFk: foreignKey({
241
+ name: `${relationshipsTableName}_parent_fk`,
242
+ columns: [
243
+ cols.parent
244
+ ],
245
+ foreignColumns: [
246
+ table.id
247
+ ]
248
+ }).onDelete('cascade'),
215
249
  parentIdx: index(`${relationshipsTableName}_parent_idx`).on(cols.parent),
216
250
  pathIdx: index(`${relationshipsTableName}_path_idx`).on(cols.path)
217
- };
251
+ });
218
252
  if (hasLocalizedRelationshipField) {
219
253
  result.localeIdx = index(`${relationshipsTableName}_locale_idx`).on(cols.locale);
220
254
  }
@@ -234,7 +268,7 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, bu
234
268
  })
235
269
  };
236
270
  relationships.forEach((relationTo)=>{
237
- const relatedTableName = getTableName({
271
+ const relatedTableName = createTableName({
238
272
  adapter,
239
273
  config: adapter.payload.collections[relationTo].config,
240
274
  throwValidationError: true
@@ -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 const relatedCollectionCustomID = relationshipConfig.fields.find(\n (field) => fieldAffectsData(field) && field.name === 'id',\n )\n if (relatedCollectionCustomID?.type === 'number') colType = 'numeric'\n if (relatedCollectionCustomID?.type === '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","fieldAffectsData","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","relatedCollectionCustomID","find","field","name","type","relationshipsTableName","relationshipsSuffix","result","parentIdx","pathIdx","localeIdx","relationshipsTableRelations","relationName","relatedTableName","idColumnName","tableRelations","many","val","_locales","_texts","_numbers","_rels"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAEoH,uBAAuB,CAAC,CAAC,GAAGM;QAC7D;IACF;IAEA,MAAMI,iBAAiB9H,UAAU2D,OAAO,CAAC,EAAEoE,IAAI,EAAE;QAC/C,MAAMT,SAA2C,CAAC;QAElDvE,iBAAiBuD,OAAO,CAAC,CAAC0B,KAAK7D;YAC7BmD,MAAM,CAACnD,IAAI,GAAG4D,KAAKjH,QAAQyD,MAAM,CAACyD,IAAI;QACxC;QAEA,IAAI/F,mBAAmB;YACrBqF,OAAOW,QAAQ,GAAGF,KAAKtF;QACzB;QAEA,IAAIN,kBAAkB;YACpBmF,OAAOY,MAAM,GAAGH,KAAKrF;QACvB;QACA,IAAIN,oBAAoB;YACtBkF,OAAOa,QAAQ,GAAGJ,KAAKpF;QACzB;QAEA,IAAIC,cAAcwD,IAAI,IAAItD,oBAAoB;YAC5CwE,OAAOc,KAAK,GAAGL,KAAKjF,oBAAoB;gBACtC6E,cAAc;YAChB;QACF;QAEA,OAAOL;IACT;IAEAxG,QAAQd,SAAS,CAAC,CAAC,UAAU,EAAE4B,UAAU,CAAC,CAAC,GAAGkG;IAE9C,OAAO;QAAE1F;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\ntype Args = {\n adapter: PostgresAdapter\n baseColumns?: Record<string, PgColumnBuilder>\n baseExtraConfig?: BaseExtraConfig\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 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 const {\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 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) {\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 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').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(cols.locale, cols.parent)\n }\n\n return config\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').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 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').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\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\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 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 = 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 })\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","foreignKey","index","integer","numeric","serial","timestamp","unique","varchar","toSnakeCase","createTableName","parentIDColumnMap","setColumnID","traverseFields","buildTable","adapter","baseColumns","baseExtraConfig","buildNumbers","buildRelationships","buildTexts","disableNotNull","disableUnique","fields","rootRelationsToBuild","rootRelationships","rootTableIDColType","rootTableName","incomingRootTableName","tableName","timestamps","versions","columns","indexes","localesColumns","localesIndexes","localesTable","textsTable","numbersTable","relationships","Set","relationshipsTable","relationsToBuild","Map","idColType","hasLocalizedField","hasLocalizedManyNumberField","hasLocalizedManyTextField","hasLocalizedRelationshipField","hasManyNumberField","hasManyTextField","newTableName","parentTableName","createdAt","mode","precision","withTimezone","defaultNow","notNull","updatedAt","table","pgSchema","cols","extraConfig","Object","entries","reduce","config","key","func","result","acc","colName","tables","localeTableName","localesSuffix","id","primaryKey","_locale","enums","enum__locales","_parentID","_localeParent","on","_parentIdFk","name","foreignColumns","onDelete","localesTableRelations","one","references","textsTableName","order","parent","path","text","locale","orderParentIdx","parentFk","text_idx","localeParent","textsTableRelations","numbersTableName","number","numberIdx","numbersTableRelations","size","relationshipColumns","relationExtraConfig","relationshipsTableName","relationshipsSuffix","forEach","relationTo","relationshipConfig","payload","collections","formattedRelationTo","throwValidationError","colType","idType","relatedCollectionCustomIDType","slug","customIDType","parentIdx","pathIdx","localeIdx","relationshipsTableRelations","relationName","relatedTableName","idColumnName","tableRelations","many","val","_locales","_texts","_numbers","_rels"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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B,OAAOkE,KAAK,GAAGL,KAAK1F,oBAAoB;gBACtCsF,cAAc;YAChB;QACF;QAEA,OAAOzD;IACT;IAEAvD,QAAQf,SAAS,CAAC,CAAC,UAAU,EAAE6B,UAAU,CAAC,CAAC,GAAGqG;IAE9C,OAAO;QAAEjF;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
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/schema/createTableName.ts"],"sourcesContent":["import type { DBIdentifierName } from 'payload/database'\n\nimport { APIError } from 'payload/errors'\nimport toSnakeCase from 'to-snake-case'\n\nimport type { PostgresAdapter } from '../types.js'\n\ntype Args = {\n adapter: PostgresAdapter\n /** The collection, global or field config **/\n config: {\n dbName?: DBIdentifierName\n enumName?: DBIdentifierName\n name?: string\n slug?: string\n }\n /** For nested tables passed for the user custom dbName functions to handle their own iterations */\n parentTableName?: string\n /** For sub tables (array for example) this needs to include the parentTableName */\n prefix?: string\n /** For tables based on fields that could have both enumName and dbName (ie: select with hasMany), default: 'dbName' */\n target?: 'dbName' | 'enumName'\n throwValidationError?: boolean\n /** Adds the versions suffix to the default table name - should only be used on the base collection to avoid duplicate suffixing */\n versions?: boolean\n /** Adds the versions suffix to custom dbName only - this is used while creating blocks / selects / arrays / etc */\n versionsCustomName?: boolean\n}\n\n/**\n * Used to name database enums and tables\n * Returns the table or enum name for a given entity\n */\nexport const createTableName = ({\n adapter,\n config: { name, slug },\n config,\n parentTableName,\n prefix = '',\n target = 'dbName',\n throwValidationError = false,\n versions = false,\n versionsCustomName = false,\n}: Args): string => {\n let customNameDefinition = config[target]\n\n let defaultTableName = `${prefix}${toSnakeCase(name ?? slug)}`\n\n if (versions) defaultTableName = `_${defaultTableName}${adapter.versionsSuffix}`\n\n let customTableNameResult: string\n\n if (!customNameDefinition && target === 'enumName') {\n customNameDefinition = config['dbName']\n }\n\n if (customNameDefinition) {\n customTableNameResult =\n typeof customNameDefinition === 'function'\n ? customNameDefinition({ tableName: parentTableName })\n : customNameDefinition\n\n if (versionsCustomName)\n customTableNameResult = `_${customTableNameResult}${adapter.versionsSuffix}`\n }\n\n const result = customTableNameResult || defaultTableName\n\n adapter.tableNameMap.set(defaultTableName, result)\n\n if (!throwValidationError) {\n return result\n }\n\n if (result.length > 63) {\n throw new APIError(\n `Exceeded max identifier length for table or enum name of 63 characters. Invalid name: ${result}`,\n )\n }\n\n return result\n}\n"],"names":["APIError","toSnakeCase","createTableName","adapter","config","name","slug","parentTableName","prefix","target","throwValidationError","versions","versionsCustomName","customNameDefinition","defaultTableName","versionsSuffix","customTableNameResult","tableName","result","tableNameMap","set","length"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAEA,SAASA,QAAQ,QAAQ,iBAAgB;AACzC,OAAOC,iBAAiB,gBAAe;AA0BvC;;;CAGC,GACD,OAAO,MAAMC,kBAAkB,CAAC,EAC9BC,OAAO,EACPC,QAAQ,EAAEC,IAAI,EAAEC,IAAI,EAAE,EACtBF,MAAM,EACNG,eAAe,EACfC,SAAS,EAAE,EACXC,SAAS,QAAQ,EACjBC,uBAAuB,KAAK,EAC5BC,WAAW,KAAK,EAChBC,qBAAqB,KAAK,EACrB;IACL,IAAIC,uBAAuBT,MAAM,CAACK,OAAO;IAEzC,IAAIK,mBAAmB,CAAC,EAAEN,OAAO,EAAEP,YAAYI,QAAQC,MAAM,CAAC;IAE9D,IAAIK,UAAUG,mBAAmB,CAAC,CAAC,EAAEA,iBAAiB,EAAEX,QAAQY,cAAc,CAAC,CAAC;IAEhF,IAAIC;IAEJ,IAAI,CAACH,wBAAwBJ,WAAW,YAAY;QAClDI,uBAAuBT,MAAM,CAAC,SAAS;IACzC;IAEA,IAAIS,sBAAsB;QACxBG,wBACE,OAAOH,yBAAyB,aAC5BA,qBAAqB;YAAEI,WAAWV;QAAgB,KAClDM;QAEN,IAAID,oBACFI,wBAAwB,CAAC,CAAC,EAAEA,sB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olean, index, integer, jsonb, numeric, pgEnum, text, timestamp, varchar } from 'drizzle-orm/pg-core';
2
+ import { PgNumericBuilder, PgUUIDBuilder, PgVarcharBuilder, boolean, foreignKey, index, integer, jsonb, numeric, pgEnum, text, timestamp, varchar } from 'drizzle-orm/pg-core';
3
3
  import { InvalidConfiguration } from 'payload/errors';
4
4
  import { fieldAffectsData, optionIsObject } from 'payload/types';
5
5
  import toSnakeCase from 'to-snake-case';
6
6
  import { hasLocalesTable } from '../utilities/hasLocalesTable.js';
7
7
  import { buildTable } from './build.js';
8
8
  import { createIndex } from './createIndex.js';
9
- import { getTableName } from './getTableName.js';
9
+ import { createTableName } from './createTableName.js';
10
10
  import { idToUUID } from './idToUUID.js';
11
11
  import { parentIDColumnMap } from './parentIDColumnMap.js';
12
12
  import { validateExistingBlockIsIdentical } from './validateExistingBlockIsIdentical.js';
@@ -130,14 +130,13 @@ export const traverseFields = ({ adapter, buildNumbers, buildRelationships, buil
130
130
  case 'radio':
131
131
  case 'select':
132
132
  {
133
- const enumName = getTableName({
133
+ const enumName = createTableName({
134
134
  adapter,
135
135
  config: field,
136
136
  parentTableName: newTableName,
137
137
  prefix: `enum_${newTableName}_`,
138
138
  target: 'enumName',
139
- throwValidationError,
140
- versions
139
+ throwValidationError
141
140
  });
142
141
  adapter.enums[enumName] = pgEnum(enumName, field.options.map((option)=>{
143
142
  if (optionIsObject(option)) {
@@ -146,23 +145,29 @@ export const traverseFields = ({ adapter, buildNumbers, buildRelationships, buil
146
145
  return option;
147
146
  }));
148
147
  if (field.type === 'select' && field.hasMany) {
149
- const selectTableName = getTableName({
148
+ const selectTableName = createTableName({
150
149
  adapter,
151
150
  config: field,
152
151
  parentTableName: newTableName,
153
152
  prefix: `${newTableName}_`,
154
- throwValidationError,
155
- versions
153
+ throwValidationError
156
154
  });
157
155
  const baseColumns = {
158
156
  order: integer('order').notNull(),
159
- parent: parentIDColumnMap[parentIDColType]('parent_id').references(()=>adapter.tables[parentTableName].id, {
160
- onDelete: 'cascade'
161
- }).notNull(),
157
+ parent: parentIDColumnMap[parentIDColType]('parent_id').notNull(),
162
158
  value: adapter.enums[enumName]('value')
163
159
  };
164
160
  const baseExtraConfig = {
165
161
  orderIdx: (cols)=>index(`${selectTableName}_order_idx`).on(cols.order),
162
+ parentFk: (cols)=>foreignKey({
163
+ name: `${selectTableName}_parent_fk`,
164
+ columns: [
165
+ cols.parent
166
+ ],
167
+ foreignColumns: [
168
+ adapter.tables[parentTableName].id
169
+ ]
170
+ }),
166
171
  parentIdx: (cols)=>index(`${selectTableName}_parent_idx`).on(cols.parent)
167
172
  };
168
173
  if (field.localized) {
@@ -210,21 +215,29 @@ export const traverseFields = ({ adapter, buildNumbers, buildRelationships, buil
210
215
  case 'array':
211
216
  {
212
217
  const disableNotNullFromHere = Boolean(field.admin?.condition) || disableNotNull;
213
- const arrayTableName = getTableName({
218
+ const arrayTableName = createTableName({
214
219
  adapter,
215
220
  config: field,
216
221
  parentTableName: newTableName,
217
222
  prefix: `${newTableName}_`,
218
- throwValidationError
223
+ throwValidationError,
224
+ versionsCustomName: versions
219
225
  });
220
226
  const baseColumns = {
221
227
  _order: integer('_order').notNull(),
222
- _parentID: parentIDColumnMap[parentIDColType]('_parent_id').references(()=>adapter.tables[parentTableName].id, {
223
- onDelete: 'cascade'
224
- }).notNull()
228
+ _parentID: parentIDColumnMap[parentIDColType]('_parent_id').notNull()
225
229
  };
226
230
  const baseExtraConfig = {
227
231
  _orderIdx: (cols)=>index(`${arrayTableName}_order_idx`).on(cols._order),
232
+ _parentIDFk: (cols)=>foreignKey({
233
+ name: `${arrayTableName}_parent_id_fk`,
234
+ columns: [
235
+ cols['_parentID']
236
+ ],
237
+ foreignColumns: [
238
+ adapter.tables[parentTableName].id
239
+ ]
240
+ }).onDelete('cascade'),
228
241
  _parentIDIdx: (cols)=>index(`${arrayTableName}_parent_id_idx`).on(cols._parentID)
229
242
  };
230
243
  if (field.localized && adapter.payload.config.localization) {
@@ -278,24 +291,32 @@ export const traverseFields = ({ adapter, buildNumbers, buildRelationships, buil
278
291
  {
279
292
  const disableNotNullFromHere = Boolean(field.admin?.condition) || disableNotNull;
280
293
  field.blocks.forEach((block)=>{
281
- const blockTableName = getTableName({
294
+ const blockTableName = createTableName({
282
295
  adapter,
283
296
  config: block,
284
297
  parentTableName: rootTableName,
285
298
  prefix: `${rootTableName}_blocks_`,
286
- throwValidationError
299
+ throwValidationError,
300
+ versionsCustomName: versions
287
301
  });
288
302
  if (!adapter.tables[blockTableName]) {
289
303
  const baseColumns = {
290
304
  _order: integer('_order').notNull(),
291
- _parentID: parentIDColumnMap[rootTableIDColType]('_parent_id').references(()=>adapter.tables[rootTableName].id, {
292
- onDelete: 'cascade'
293
- }).notNull(),
305
+ _parentID: parentIDColumnMap[rootTableIDColType]('_parent_id').notNull(),
294
306
  _path: text('_path').notNull()
295
307
  };
296
308
  const baseExtraConfig = {
297
309
  _orderIdx: (cols)=>index(`${blockTableName}_order_idx`).on(cols._order),
298
310
  _parentIDIdx: (cols)=>index(`${blockTableName}_parent_id_idx`).on(cols._parentID),
311
+ _parentIdFk: (cols)=>foreignKey({
312
+ name: `${blockTableName}_parent_id_fk`,
313
+ columns: [
314
+ cols._parentID
315
+ ],
316
+ foreignColumns: [
317
+ adapter.tables[rootTableName].id
318
+ ]
319
+ }).onDelete('cascade'),
299
320
  _pathIdx: (cols)=>index(`${blockTableName}_path_idx`).on(cols._path)
300
321
  };
301
322
  if (field.localized && adapter.payload.config.localization) {
@@ -347,10 +368,10 @@ export const traverseFields = ({ adapter, buildNumbers, buildRelationships, buil
347
368
  block,
348
369
  localized: field.localized,
349
370
  rootTableName,
350
- table: adapter.tables[blockTableName]
371
+ table: adapter.tables[blockTableName],
372
+ tableLocales: adapter.tables[`${blockTableName}${adapter.localesSuffix}`]
351
373
  });
352
374
  }
353
- adapter.blockTableNames[`${rootTableName}.${toSnakeCase(block.slug)}`] = blockTableName;
354
375
  rootRelationsToBuild.set(`_blocks_${block.slug}`, blockTableName);
355
376
  });
356
377
  break;
@@ -481,7 +502,7 @@ export const traverseFields = ({ adapter, buildNumbers, buildRelationships, buil
481
502
  indexes,
482
503
  localesColumns,
483
504
  localesIndexes,
484
- newTableName: parentTableName,
505
+ newTableName,
485
506
  parentTableName,
486
507
  relationsToBuild,
487
508
  relationships,