@payloadcms/drizzle 3.49.0-canary.4 → 3.49.0-canary.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,6 +22,6 @@ export type Result = {
22
22
  _locales?: DBQueryConfig<'many', true, any, any>;
23
23
  } & DBQueryConfig<'many', true, any, any>;
24
24
  } & DBQueryConfig<'many', true, any, any>;
25
- export declare const buildFindManyArgs: ({ adapter, collectionSlug, depth, draftsEnabled, fields, joinQuery, joins, locale, select, tableName, versions, }: BuildFindQueryArgs) => Record<string, unknown>;
25
+ export declare const buildFindManyArgs: ({ adapter, collectionSlug, depth, draftsEnabled, fields, joinQuery, joins, locale, select, tableName, versions, }: BuildFindQueryArgs) => Result;
26
26
  export {};
27
27
  //# sourceMappingURL=buildFindManyArgs.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"buildFindManyArgs.d.ts","sourceRoot":"","sources":["../../src/find/buildFindManyArgs.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAChD,OAAO,KAAK,EAAE,cAAc,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAIpE,OAAO,KAAK,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAIxE,KAAK,kBAAkB,GAAG;IACxB,OAAO,EAAE,cAAc,CAAA;IACvB,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,KAAK,EAAE,MAAM,CAAA;IACb,aAAa,CAAC,EAAE,OAAO,CAAA;IACvB,MAAM,EAAE,cAAc,EAAE,CAAA;IACxB,SAAS,CAAC,EAAE,SAAS,CAAA;IACrB;;OAEG;IACH,KAAK,CAAC,EAAE,qBAAqB,CAAA;IAC7B,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,MAAM,CAAC,EAAE,UAAU,CAAA;IACnB,SAAS,EAAE,MAAM,CAAA;IACjB,QAAQ,CAAC,EAAE,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C,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;KACjD,GAAG,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;CAC1C,GAAG,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;AAIzC,eAAO,MAAM,iBAAiB,sHAY3B,kBAAkB,KAAG,MAkGvB,CAAA"}
@@ -84,6 +84,12 @@ export const buildFindManyArgs = ({ adapter, collectionSlug, depth, draftsEnable
84
84
  if (adapter.tables[`${tableName}${adapter.localesSuffix}`] && (!select || Object.keys(_locales.columns).length > 1)) {
85
85
  result.with._locales = _locales;
86
86
  }
87
+ // Delete properties that are empty
88
+ for (const key of Object.keys(result)){
89
+ if (!Object.keys(result[key]).length) {
90
+ delete result[key];
91
+ }
92
+ }
87
93
  return result;
88
94
  };
89
95
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/find/buildFindManyArgs.ts"],"sourcesContent":["import type { DBQueryConfig } from 'drizzle-orm'\nimport type { FlattenedField, JoinQuery, SelectType } from 'payload'\n\nimport { getSelectMode } from 'payload/shared'\n\nimport type { BuildQueryJoinAliases, DrizzleAdapter } from '../types.js'\n\nimport { traverseFields } from './traverseFields.js'\n\ntype BuildFindQueryArgs = {\n adapter: DrizzleAdapter\n collectionSlug?: string\n depth: number\n draftsEnabled?: boolean\n fields: FlattenedField[]\n joinQuery?: JoinQuery\n /**\n * The joins array will be mutated by pushing any joins needed for the where queries of join field joins\n */\n joins?: BuildQueryJoinAliases\n locale?: string\n select?: SelectType\n tableName: string\n versions?: boolean\n}\n\nexport type Result = {\n with?: {\n _locales?: DBQueryConfig<'many', true, any, any>\n } & DBQueryConfig<'many', true, any, any>\n} & DBQueryConfig<'many', true, any, any>\n\n// Generate the Drizzle query for findMany based on\n// a collection field structure\nexport const buildFindManyArgs = ({\n adapter,\n collectionSlug,\n depth,\n draftsEnabled,\n fields,\n joinQuery,\n joins = [],\n locale,\n select,\n tableName,\n versions,\n}: BuildFindQueryArgs): Record<string, unknown> => {\n const result: Result = {\n extras: {},\n with: {},\n }\n\n if (select) {\n result.columns = {\n id: true,\n }\n }\n\n const _locales: Result = {\n columns: select\n ? { _locale: true }\n : {\n id: false,\n _parentID: false,\n },\n extras: {},\n with: {},\n }\n\n const withTabledFields = select\n ? {}\n : {\n numbers: true,\n rels: true,\n texts: true,\n }\n\n traverseFields({\n _locales,\n adapter,\n collectionSlug,\n currentArgs: result,\n currentTableName: tableName,\n depth,\n draftsEnabled,\n fields,\n joinQuery,\n joins,\n locale,\n path: '',\n select,\n selectMode: select ? getSelectMode(select) : undefined,\n tablePath: '',\n topLevelArgs: result,\n topLevelTableName: tableName,\n versions,\n withTabledFields,\n })\n\n if (adapter.tables[`${tableName}_texts`] && withTabledFields.texts) {\n result.with._texts = {\n columns: {\n id: false,\n parent: false,\n },\n orderBy: ({ order }, { asc: ASC }) => [ASC(order)],\n }\n }\n\n if (adapter.tables[`${tableName}_numbers`] && withTabledFields.numbers) {\n result.with._numbers = {\n columns: {\n id: false,\n parent: false,\n },\n orderBy: ({ order }, { asc: ASC }) => [ASC(order)],\n }\n }\n\n if (adapter.tables[`${tableName}${adapter.relationshipsSuffix}`] && withTabledFields.rels) {\n result.with._rels = {\n columns: {\n id: false,\n parent: false,\n },\n orderBy: ({ order }, { asc: ASC }) => [ASC(order)],\n }\n }\n\n if (\n adapter.tables[`${tableName}${adapter.localesSuffix}`] &&\n (!select || Object.keys(_locales.columns).length > 1)\n ) {\n result.with._locales = _locales\n }\n\n return result\n}\n"],"names":["getSelectMode","traverseFields","buildFindManyArgs","adapter","collectionSlug","depth","draftsEnabled","fields","joinQuery","joins","locale","select","tableName","versions","result","extras","with","columns","id","_locales","_locale","_parentID","withTabledFields","numbers","rels","texts","currentArgs","currentTableName","path","selectMode","undefined","tablePath","topLevelArgs","topLevelTableName","tables","_texts","parent","orderBy","order","asc","ASC","_numbers","relationshipsSuffix","_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AC,CAAC,IAAIU,iBAAiBC,OAAO,EAAE;QACtET,OAAOE,IAAI,CAACyB,QAAQ,GAAG;YACrBxB,SAAS;gBACPC,IAAI;gBACJkB,QAAQ;YACV;YACAC,SAAS,CAAC,EAAEC,KAAK,EAAE,EAAE,EAAEC,KAAKC,GAAG,EAAE,GAAK;oBAACA,IAAIF;iBAAO;QACpD;IACF;IAEA,IAAInC,QAAQ+B,MAAM,CAAC,GAAGtB,YAAYT,QAAQuC,mBAAmB,EAAE,CAAC,IAAIpB,iBAAiBE,IAAI,EAAE;QACzFV,OAAOE,IAAI,CAAC2B,KAAK,GAAG;YAClB1B,SAAS;gBACPC,IAAI;gBACJkB,QAAQ;YACV;YACAC,SAAS,CAAC,EAAEC,KAAK,EAAE,EAAE,EAAEC,KAAKC,GAAG,EAAE,GAAK;oBAACA,IAAIF;iBAAO;QACpD;IACF;IAEA,IACEnC,QAAQ+B,MAAM,CAAC,GAAGtB,YAAYT,QAAQyC,aAAa,EAAE,CAAC,IACrD,CAAA,CAACjC,UAAUkC,OAAOC,IAAI,CAAC3B,SAASF,OAAO,EAAE8B,MAAM,GAAG,CAAA,GACnD;QACAjC,OAAOE,IAAI,CAACG,QAAQ,GAAGA;IACzB;IAEA,OAAOL;AACT,EAAC"}
1
+ {"version":3,"sources":["../../src/find/buildFindManyArgs.ts"],"sourcesContent":["import type { DBQueryConfig } from 'drizzle-orm'\nimport type { FlattenedField, JoinQuery, SelectType } from 'payload'\n\nimport { getSelectMode } from 'payload/shared'\n\nimport type { BuildQueryJoinAliases, DrizzleAdapter } from '../types.js'\n\nimport { traverseFields } from './traverseFields.js'\n\ntype BuildFindQueryArgs = {\n adapter: DrizzleAdapter\n collectionSlug?: string\n depth: number\n draftsEnabled?: boolean\n fields: FlattenedField[]\n joinQuery?: JoinQuery\n /**\n * The joins array will be mutated by pushing any joins needed for the where queries of join field joins\n */\n joins?: BuildQueryJoinAliases\n locale?: string\n select?: SelectType\n tableName: string\n versions?: boolean\n}\n\nexport type Result = {\n with?: {\n _locales?: DBQueryConfig<'many', true, any, any>\n } & DBQueryConfig<'many', true, any, any>\n} & DBQueryConfig<'many', true, any, any>\n\n// Generate the Drizzle query for findMany based on\n// a collection field structure\nexport const buildFindManyArgs = ({\n adapter,\n collectionSlug,\n depth,\n draftsEnabled,\n fields,\n joinQuery,\n joins = [],\n locale,\n select,\n tableName,\n versions,\n}: BuildFindQueryArgs): Result => {\n const result: Result = {\n extras: {},\n with: {},\n }\n\n if (select) {\n result.columns = {\n id: true,\n }\n }\n\n const _locales: Result = {\n columns: select\n ? { _locale: true }\n : {\n id: false,\n _parentID: false,\n },\n extras: {},\n with: {},\n }\n\n const withTabledFields = select\n ? {}\n : {\n numbers: true,\n rels: true,\n texts: true,\n }\n\n traverseFields({\n _locales,\n adapter,\n collectionSlug,\n currentArgs: result,\n currentTableName: tableName,\n depth,\n draftsEnabled,\n fields,\n joinQuery,\n joins,\n locale,\n path: '',\n select,\n selectMode: select ? getSelectMode(select) : undefined,\n tablePath: '',\n topLevelArgs: result,\n topLevelTableName: tableName,\n versions,\n withTabledFields,\n })\n\n if (adapter.tables[`${tableName}_texts`] && withTabledFields.texts) {\n result.with._texts = {\n columns: {\n id: false,\n parent: false,\n },\n orderBy: ({ order }, { asc: ASC }) => [ASC(order)],\n }\n }\n\n if (adapter.tables[`${tableName}_numbers`] && withTabledFields.numbers) {\n result.with._numbers = {\n columns: {\n id: false,\n parent: false,\n },\n orderBy: ({ order }, { asc: ASC }) => [ASC(order)],\n }\n }\n\n if (adapter.tables[`${tableName}${adapter.relationshipsSuffix}`] && withTabledFields.rels) {\n result.with._rels = {\n columns: {\n id: false,\n parent: false,\n },\n orderBy: ({ order }, { asc: ASC }) => [ASC(order)],\n }\n }\n\n if (\n adapter.tables[`${tableName}${adapter.localesSuffix}`] &&\n (!select || Object.keys(_locales.columns).length > 1)\n ) {\n result.with._locales = _locales\n }\n\n // Delete properties that are empty\n for (const key of Object.keys(result)) {\n if (!Object.keys(result[key]).length) {\n delete result[key]\n }\n }\n\n return result\n}\n"],"names":["getSelectMode","traverseFields","buildFindManyArgs","adapter","collectionSlug","depth","draftsEnabled","fields","joinQuery","joins","locale","select","tableName","versions","result","extras","with","columns","id","_locales","_locale","_parentID","withTabledFields","numbers","rels","texts","currentArgs","currentTableName","path","selectMode","undefined","tablePath","topLevelArgs","topLevelTableName","tables","_texts","parent","orderBy","order","asc","ASC","_numbers","relationshipsSuffix","_rels","localesSuffix","Object","keys","length","key"],"mappings":"AAGA,SAASA,aAAa,QAAQ,iBAAgB;AAI9C,SAASC,cAAc,QAAQ,sBAAqB;AAyBpD,mDAAmD;AACnD,+BAA+B;AAC/B,OAAO,MAAMC,oBAAoB,CAAC,EAChCC,OAAO,EACPC,cAAc,EACdC,KAAK,EACLC,aAAa,EACbC,MAAM,EACNC,SAAS,EACTC,QAAQ,EAAE,EACVC,MAAM,EACNC,MAAM,EACNC,SAAS,EACTC,QAAQ,EACW;IACnB,MAAMC,SAAiB;QACrBC,QAAQ,CAAC;QACTC,MAAM,CAAC;IACT;IAEA,IAAIL,QAAQ;QACVG,OAAOG,OAAO,GAAG;YACfC,IAAI;QACN;IACF;IAEA,MAAMC,WAAmB;QACvBF,SAASN,SACL;YAAES,SAAS;QAAK,IAChB;YACEF,IAAI;YACJG,WAAW;QACb;QACJN,QAAQ,CAAC;QACTC,MAAM,CAAC;IACT;IAEA,MAAMM,mBAAmBX,SACrB,CAAC,IACD;QACEY,SAAS;QACTC,MAAM;QACNC,OAAO;IACT;IAEJxB,eAAe;QACbkB;QACAhB;QACAC;QACAsB,aAAaZ;QACba,kBAAkBf;QAClBP;QACAC;QACAC;QACAC;QACAC;QACAC;QACAkB,MAAM;QACNjB;QACAkB,YAAYlB,SAASX,cAAcW,UAAUmB;QAC7CC,WAAW;QACXC,cAAclB;QACdmB,mBAAmBrB;QACnBC;QACAS;IACF;IAEA,IAAInB,QAAQ+B,MAAM,CAAC,GAAGtB,UAAU,MAAM,CAAC,CAAC,IAAIU,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,OAAOlC;AACT,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/upsertRow/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAMzC,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAA;AAUtC;;;;;;GAMG;AACH,eAAO,MAAM,SAAS,GAAU,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,UAAU,yIAkB3E,IAAI,KAAG,OAAO,CAAC,CAAC,CAmelB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/upsertRow/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAMzC,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAA;AAUtC;;;;;;GAMG;AACH,eAAO,MAAM,SAAS,GAAU,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,UAAU,yIAkB3E,IAAI,KAAG,OAAO,CAAC,CAAC,CAiiBlB,CAAA"}
@@ -32,390 +32,436 @@ joinQuery: _joinQuery, operation, path = '', req, select, tableName, upsertTarge
32
32
  tableName
33
33
  });
34
34
  const drizzle = db;
35
- await drizzle.update(adapter.tables[tableName]).set(row)// TODO: we can skip fetching idToUpdate here with using the incoming where
36
- .where(eq(adapter.tables[tableName].id, id));
37
- } else {
38
- // Split out the incoming data into the corresponding:
39
- // base row, locales, relationships, blocks, and arrays
40
- const rowToInsert = transformForWrite({
35
+ if (ignoreResult) {
36
+ await drizzle.update(adapter.tables[tableName]).set(row).where(eq(adapter.tables[tableName].id, id));
37
+ return ignoreResult === 'idOnly' ? {
38
+ id
39
+ } : null;
40
+ }
41
+ const findManyArgs = buildFindManyArgs({
41
42
  adapter,
42
- data,
43
- enableAtomicWrites: false,
43
+ depth: 0,
44
44
  fields,
45
- path,
45
+ joinQuery: false,
46
+ select,
46
47
  tableName
47
48
  });
48
- // First, we insert the main row
49
- try {
50
- if (operation === 'update') {
51
- const target = upsertTarget || adapter.tables[tableName].id;
52
- if (id) {
53
- rowToInsert.row.id = id;
54
- [insertedRow] = await adapter.insert({
55
- db,
56
- onConflictDoUpdate: {
57
- set: rowToInsert.row,
58
- target
59
- },
60
- tableName,
61
- values: rowToInsert.row
62
- });
63
- } else {
64
- ;
65
- [insertedRow] = await adapter.insert({
66
- db,
67
- onConflictDoUpdate: {
68
- set: rowToInsert.row,
69
- target,
70
- where
71
- },
72
- tableName,
73
- values: rowToInsert.row
74
- });
49
+ const findManyKeysLength = Object.keys(findManyArgs).length;
50
+ const hasOnlyColumns = Object.keys(findManyArgs.columns || {}).length > 0;
51
+ if (findManyKeysLength === 0 || hasOnlyColumns) {
52
+ // Optimization - No need for joins => can simply use returning(). This is optimal for very simple collections
53
+ // without complex fields that live in separate tables like blocks, arrays, relationships, etc.
54
+ const selectedFields = {};
55
+ if (hasOnlyColumns) {
56
+ for (const [column, enabled] of Object.entries(findManyArgs.columns)){
57
+ if (enabled) {
58
+ selectedFields[column] = adapter.tables[tableName][column];
59
+ }
75
60
  }
61
+ }
62
+ const docs = await drizzle.update(adapter.tables[tableName]).set(row).where(eq(adapter.tables[tableName].id, id)).returning(Object.keys(selectedFields).length ? selectedFields : undefined);
63
+ return transform({
64
+ adapter,
65
+ config: adapter.payload.config,
66
+ data: docs[0],
67
+ fields,
68
+ joinQuery: false,
69
+ tableName
70
+ });
71
+ }
72
+ // DB Update that needs the result, potentially with joins => need to update first, then find. returning() does not work with joins.
73
+ await drizzle.update(adapter.tables[tableName]).set(row).where(eq(adapter.tables[tableName].id, id));
74
+ findManyArgs.where = eq(adapter.tables[tableName].id, insertedRow.id);
75
+ const doc = await db.query[tableName].findFirst(findManyArgs);
76
+ return transform({
77
+ adapter,
78
+ config: adapter.payload.config,
79
+ data: doc,
80
+ fields,
81
+ joinQuery: false,
82
+ tableName
83
+ });
84
+ }
85
+ // Split out the incoming data into the corresponding:
86
+ // base row, locales, relationships, blocks, and arrays
87
+ const rowToInsert = transformForWrite({
88
+ adapter,
89
+ data,
90
+ enableAtomicWrites: false,
91
+ fields,
92
+ path,
93
+ tableName
94
+ });
95
+ // First, we insert the main row
96
+ try {
97
+ if (operation === 'update') {
98
+ const target = upsertTarget || adapter.tables[tableName].id;
99
+ if (id) {
100
+ rowToInsert.row.id = id;
101
+ [insertedRow] = await adapter.insert({
102
+ db,
103
+ onConflictDoUpdate: {
104
+ set: rowToInsert.row,
105
+ target
106
+ },
107
+ tableName,
108
+ values: rowToInsert.row
109
+ });
76
110
  } else {
77
- if (adapter.allowIDOnCreate && data.id) {
78
- rowToInsert.row.id = data.id;
79
- }
80
111
  ;
81
112
  [insertedRow] = await adapter.insert({
82
113
  db,
114
+ onConflictDoUpdate: {
115
+ set: rowToInsert.row,
116
+ target,
117
+ where
118
+ },
83
119
  tableName,
84
120
  values: rowToInsert.row
85
121
  });
86
122
  }
87
- const localesToInsert = [];
88
- const relationsToInsert = [];
89
- const textsToInsert = [];
90
- const numbersToInsert = [];
91
- const blocksToInsert = {};
92
- const selectsToInsert = {};
93
- // If there are locale rows with data, add the parent and locale to each
94
- if (Object.keys(rowToInsert.locales).length > 0) {
95
- Object.entries(rowToInsert.locales).forEach(([locale, localeRow])=>{
96
- localeRow._parentID = insertedRow.id;
97
- localeRow._locale = locale;
98
- localesToInsert.push(localeRow);
99
- });
100
- }
101
- // If there are relationships, add parent to each
102
- if (rowToInsert.relationships.length > 0) {
103
- rowToInsert.relationships.forEach((relation)=>{
104
- relation.parent = insertedRow.id;
105
- relationsToInsert.push(relation);
106
- });
107
- }
108
- // If there are texts, add parent to each
109
- if (rowToInsert.texts.length > 0) {
110
- rowToInsert.texts.forEach((textRow)=>{
111
- textRow.parent = insertedRow.id;
112
- textsToInsert.push(textRow);
113
- });
114
- }
115
- // If there are numbers, add parent to each
116
- if (rowToInsert.numbers.length > 0) {
117
- rowToInsert.numbers.forEach((numberRow)=>{
118
- numberRow.parent = insertedRow.id;
119
- numbersToInsert.push(numberRow);
120
- });
121
- }
122
- // If there are selects, add parent to each, and then
123
- // store by table name and rows
124
- if (Object.keys(rowToInsert.selects).length > 0) {
125
- Object.entries(rowToInsert.selects).forEach(([selectTableName, selectRows])=>{
126
- selectsToInsert[selectTableName] = [];
127
- selectRows.forEach((row)=>{
128
- if (typeof row.parent === 'undefined') {
129
- row.parent = insertedRow.id;
130
- }
131
- selectsToInsert[selectTableName].push(row);
132
- });
133
- });
123
+ } else {
124
+ if (adapter.allowIDOnCreate && data.id) {
125
+ rowToInsert.row.id = data.id;
134
126
  }
135
- // If there are blocks, add parent to each, and then
136
- // store by table name and rows
137
- Object.keys(rowToInsert.blocks).forEach((tableName)=>{
138
- rowToInsert.blocks[tableName].forEach((blockRow)=>{
139
- blockRow.row._parentID = insertedRow.id;
140
- if (!blocksToInsert[tableName]) {
141
- blocksToInsert[tableName] = [];
142
- }
143
- if (blockRow.row.uuid) {
144
- delete blockRow.row.uuid;
127
+ ;
128
+ [insertedRow] = await adapter.insert({
129
+ db,
130
+ tableName,
131
+ values: rowToInsert.row
132
+ });
133
+ }
134
+ const localesToInsert = [];
135
+ const relationsToInsert = [];
136
+ const textsToInsert = [];
137
+ const numbersToInsert = [];
138
+ const blocksToInsert = {};
139
+ const selectsToInsert = {};
140
+ // If there are locale rows with data, add the parent and locale to each
141
+ if (Object.keys(rowToInsert.locales).length > 0) {
142
+ Object.entries(rowToInsert.locales).forEach(([locale, localeRow])=>{
143
+ localeRow._parentID = insertedRow.id;
144
+ localeRow._locale = locale;
145
+ localesToInsert.push(localeRow);
146
+ });
147
+ }
148
+ // If there are relationships, add parent to each
149
+ if (rowToInsert.relationships.length > 0) {
150
+ rowToInsert.relationships.forEach((relation)=>{
151
+ relation.parent = insertedRow.id;
152
+ relationsToInsert.push(relation);
153
+ });
154
+ }
155
+ // If there are texts, add parent to each
156
+ if (rowToInsert.texts.length > 0) {
157
+ rowToInsert.texts.forEach((textRow)=>{
158
+ textRow.parent = insertedRow.id;
159
+ textsToInsert.push(textRow);
160
+ });
161
+ }
162
+ // If there are numbers, add parent to each
163
+ if (rowToInsert.numbers.length > 0) {
164
+ rowToInsert.numbers.forEach((numberRow)=>{
165
+ numberRow.parent = insertedRow.id;
166
+ numbersToInsert.push(numberRow);
167
+ });
168
+ }
169
+ // If there are selects, add parent to each, and then
170
+ // store by table name and rows
171
+ if (Object.keys(rowToInsert.selects).length > 0) {
172
+ Object.entries(rowToInsert.selects).forEach(([selectTableName, selectRows])=>{
173
+ selectsToInsert[selectTableName] = [];
174
+ selectRows.forEach((row)=>{
175
+ if (typeof row.parent === 'undefined') {
176
+ row.parent = insertedRow.id;
145
177
  }
146
- blocksToInsert[tableName].push(blockRow);
178
+ selectsToInsert[selectTableName].push(row);
147
179
  });
148
180
  });
149
- // //////////////////////////////////
150
- // INSERT LOCALES
151
- // //////////////////////////////////
152
- if (localesToInsert.length > 0) {
153
- const localeTableName = `${tableName}${adapter.localesSuffix}`;
154
- const localeTable = adapter.tables[`${tableName}${adapter.localesSuffix}`];
155
- if (operation === 'update') {
156
- await adapter.deleteWhere({
157
- db,
158
- tableName: localeTableName,
159
- where: eq(localeTable._parentID, insertedRow.id)
160
- });
181
+ }
182
+ // If there are blocks, add parent to each, and then
183
+ // store by table name and rows
184
+ Object.keys(rowToInsert.blocks).forEach((tableName)=>{
185
+ rowToInsert.blocks[tableName].forEach((blockRow)=>{
186
+ blockRow.row._parentID = insertedRow.id;
187
+ if (!blocksToInsert[tableName]) {
188
+ blocksToInsert[tableName] = [];
161
189
  }
162
- await adapter.insert({
190
+ if (blockRow.row.uuid) {
191
+ delete blockRow.row.uuid;
192
+ }
193
+ blocksToInsert[tableName].push(blockRow);
194
+ });
195
+ });
196
+ // //////////////////////////////////
197
+ // INSERT LOCALES
198
+ // //////////////////////////////////
199
+ if (localesToInsert.length > 0) {
200
+ const localeTableName = `${tableName}${adapter.localesSuffix}`;
201
+ const localeTable = adapter.tables[`${tableName}${adapter.localesSuffix}`];
202
+ if (operation === 'update') {
203
+ await adapter.deleteWhere({
163
204
  db,
164
205
  tableName: localeTableName,
165
- values: localesToInsert
206
+ where: eq(localeTable._parentID, insertedRow.id)
166
207
  });
167
208
  }
168
- // //////////////////////////////////
169
- // INSERT RELATIONSHIPS
170
- // //////////////////////////////////
171
- const relationshipsTableName = `${tableName}${adapter.relationshipsSuffix}`;
172
- if (operation === 'update') {
173
- await deleteExistingRowsByPath({
174
- adapter,
209
+ await adapter.insert({
210
+ db,
211
+ tableName: localeTableName,
212
+ values: localesToInsert
213
+ });
214
+ }
215
+ // //////////////////////////////////
216
+ // INSERT RELATIONSHIPS
217
+ // //////////////////////////////////
218
+ const relationshipsTableName = `${tableName}${adapter.relationshipsSuffix}`;
219
+ if (operation === 'update') {
220
+ await deleteExistingRowsByPath({
221
+ adapter,
222
+ db,
223
+ localeColumnName: 'locale',
224
+ parentColumnName: 'parent',
225
+ parentID: insertedRow.id,
226
+ pathColumnName: 'path',
227
+ rows: [
228
+ ...relationsToInsert,
229
+ ...rowToInsert.relationshipsToDelete
230
+ ],
231
+ tableName: relationshipsTableName
232
+ });
233
+ }
234
+ if (relationsToInsert.length > 0) {
235
+ await adapter.insert({
236
+ db,
237
+ tableName: relationshipsTableName,
238
+ values: relationsToInsert
239
+ });
240
+ }
241
+ // //////////////////////////////////
242
+ // INSERT hasMany TEXTS
243
+ // //////////////////////////////////
244
+ const textsTableName = `${tableName}_texts`;
245
+ if (operation === 'update') {
246
+ await deleteExistingRowsByPath({
247
+ adapter,
248
+ db,
249
+ localeColumnName: 'locale',
250
+ parentColumnName: 'parent',
251
+ parentID: insertedRow.id,
252
+ pathColumnName: 'path',
253
+ rows: [
254
+ ...textsToInsert,
255
+ ...rowToInsert.textsToDelete
256
+ ],
257
+ tableName: textsTableName
258
+ });
259
+ }
260
+ if (textsToInsert.length > 0) {
261
+ await adapter.insert({
262
+ db,
263
+ tableName: textsTableName,
264
+ values: textsToInsert
265
+ });
266
+ }
267
+ // //////////////////////////////////
268
+ // INSERT hasMany NUMBERS
269
+ // //////////////////////////////////
270
+ const numbersTableName = `${tableName}_numbers`;
271
+ if (operation === 'update') {
272
+ await deleteExistingRowsByPath({
273
+ adapter,
274
+ db,
275
+ localeColumnName: 'locale',
276
+ parentColumnName: 'parent',
277
+ parentID: insertedRow.id,
278
+ pathColumnName: 'path',
279
+ rows: [
280
+ ...numbersToInsert,
281
+ ...rowToInsert.numbersToDelete
282
+ ],
283
+ tableName: numbersTableName
284
+ });
285
+ }
286
+ if (numbersToInsert.length > 0) {
287
+ await adapter.insert({
288
+ db,
289
+ tableName: numbersTableName,
290
+ values: numbersToInsert
291
+ });
292
+ }
293
+ // //////////////////////////////////
294
+ // INSERT BLOCKS
295
+ // //////////////////////////////////
296
+ const insertedBlockRows = {};
297
+ if (operation === 'update') {
298
+ for (const tableName of rowToInsert.blocksToDelete){
299
+ const blockTable = adapter.tables[tableName];
300
+ await adapter.deleteWhere({
175
301
  db,
176
- localeColumnName: 'locale',
177
- parentColumnName: 'parent',
178
- parentID: insertedRow.id,
179
- pathColumnName: 'path',
180
- rows: [
181
- ...relationsToInsert,
182
- ...rowToInsert.relationshipsToDelete
183
- ],
184
- tableName: relationshipsTableName
302
+ tableName,
303
+ where: eq(blockTable._parentID, insertedRow.id)
185
304
  });
186
305
  }
187
- if (relationsToInsert.length > 0) {
306
+ }
307
+ // When versions are enabled, adapter is used to track mapping between blocks/arrays ObjectID to their numeric generated representation, then we use it for nested to arrays/blocks select hasMany in versions.
308
+ const arraysBlocksUUIDMap = {};
309
+ for (const [tableName, blockRows] of Object.entries(blocksToInsert)){
310
+ insertedBlockRows[tableName] = await adapter.insert({
311
+ db,
312
+ tableName,
313
+ values: blockRows.map(({ row })=>row)
314
+ });
315
+ insertedBlockRows[tableName].forEach((row, i)=>{
316
+ blockRows[i].row = row;
317
+ if (typeof row._uuid === 'string' && (typeof row.id === 'string' || typeof row.id === 'number')) {
318
+ arraysBlocksUUIDMap[row._uuid] = row.id;
319
+ }
320
+ });
321
+ const blockLocaleIndexMap = [];
322
+ const blockLocaleRowsToInsert = blockRows.reduce((acc, blockRow, i)=>{
323
+ if (Object.entries(blockRow.locales).length > 0) {
324
+ Object.entries(blockRow.locales).forEach(([blockLocale, blockLocaleData])=>{
325
+ if (Object.keys(blockLocaleData).length > 0) {
326
+ blockLocaleData._parentID = blockRow.row.id;
327
+ blockLocaleData._locale = blockLocale;
328
+ acc.push(blockLocaleData);
329
+ blockLocaleIndexMap.push(i);
330
+ }
331
+ });
332
+ }
333
+ return acc;
334
+ }, []);
335
+ if (blockLocaleRowsToInsert.length > 0) {
188
336
  await adapter.insert({
189
337
  db,
190
- tableName: relationshipsTableName,
191
- values: relationsToInsert
338
+ tableName: `${tableName}${adapter.localesSuffix}`,
339
+ values: blockLocaleRowsToInsert
192
340
  });
193
341
  }
194
- // //////////////////////////////////
195
- // INSERT hasMany TEXTS
196
- // //////////////////////////////////
197
- const textsTableName = `${tableName}_texts`;
198
- if (operation === 'update') {
199
- await deleteExistingRowsByPath({
342
+ await insertArrays({
343
+ adapter,
344
+ arrays: blockRows.map(({ arrays })=>arrays),
345
+ db,
346
+ parentRows: insertedBlockRows[tableName],
347
+ uuidMap: arraysBlocksUUIDMap
348
+ });
349
+ }
350
+ // //////////////////////////////////
351
+ // INSERT ARRAYS RECURSIVELY
352
+ // //////////////////////////////////
353
+ if (operation === 'update') {
354
+ for (const arrayTableName of Object.keys(rowToInsert.arrays)){
355
+ await deleteExistingArrayRows({
200
356
  adapter,
201
357
  db,
202
- localeColumnName: 'locale',
203
- parentColumnName: 'parent',
204
358
  parentID: insertedRow.id,
205
- pathColumnName: 'path',
206
- rows: [
207
- ...textsToInsert,
208
- ...rowToInsert.textsToDelete
209
- ],
210
- tableName: textsTableName
359
+ tableName: arrayTableName
211
360
  });
212
361
  }
213
- if (textsToInsert.length > 0) {
214
- await adapter.insert({
215
- db,
216
- tableName: textsTableName,
217
- values: textsToInsert
218
- });
219
- }
220
- // //////////////////////////////////
221
- // INSERT hasMany NUMBERS
222
- // //////////////////////////////////
223
- const numbersTableName = `${tableName}_numbers`;
362
+ }
363
+ await insertArrays({
364
+ adapter,
365
+ arrays: [
366
+ rowToInsert.arrays
367
+ ],
368
+ db,
369
+ parentRows: [
370
+ insertedRow
371
+ ],
372
+ uuidMap: arraysBlocksUUIDMap
373
+ });
374
+ // //////////////////////////////////
375
+ // INSERT hasMany SELECTS
376
+ // //////////////////////////////////
377
+ for (const [selectTableName, tableRows] of Object.entries(selectsToInsert)){
378
+ const selectTable = adapter.tables[selectTableName];
224
379
  if (operation === 'update') {
225
- await deleteExistingRowsByPath({
226
- adapter,
380
+ await adapter.deleteWhere({
227
381
  db,
228
- localeColumnName: 'locale',
229
- parentColumnName: 'parent',
230
- parentID: insertedRow.id,
231
- pathColumnName: 'path',
232
- rows: [
233
- ...numbersToInsert,
234
- ...rowToInsert.numbersToDelete
235
- ],
236
- tableName: numbersTableName
382
+ tableName: selectTableName,
383
+ where: eq(selectTable.parent, insertedRow.id)
237
384
  });
238
385
  }
239
- if (numbersToInsert.length > 0) {
240
- await adapter.insert({
241
- db,
242
- tableName: numbersTableName,
243
- values: numbersToInsert
244
- });
245
- }
246
- // //////////////////////////////////
247
- // INSERT BLOCKS
248
- // //////////////////////////////////
249
- const insertedBlockRows = {};
250
- if (operation === 'update') {
251
- for (const tableName of rowToInsert.blocksToDelete){
252
- const blockTable = adapter.tables[tableName];
253
- await adapter.deleteWhere({
254
- db,
255
- tableName,
256
- where: eq(blockTable._parentID, insertedRow.id)
257
- });
258
- }
259
- }
260
- // When versions are enabled, adapter is used to track mapping between blocks/arrays ObjectID to their numeric generated representation, then we use it for nested to arrays/blocks select hasMany in versions.
261
- const arraysBlocksUUIDMap = {};
262
- for (const [tableName, blockRows] of Object.entries(blocksToInsert)){
263
- insertedBlockRows[tableName] = await adapter.insert({
264
- db,
265
- tableName,
266
- values: blockRows.map(({ row })=>row)
267
- });
268
- insertedBlockRows[tableName].forEach((row, i)=>{
269
- blockRows[i].row = row;
270
- if (typeof row._uuid === 'string' && (typeof row.id === 'string' || typeof row.id === 'number')) {
271
- arraysBlocksUUIDMap[row._uuid] = row.id;
386
+ if (Object.keys(arraysBlocksUUIDMap).length > 0) {
387
+ tableRows.forEach((row)=>{
388
+ if (row.parent in arraysBlocksUUIDMap) {
389
+ row.parent = arraysBlocksUUIDMap[row.parent];
272
390
  }
273
391
  });
274
- const blockLocaleIndexMap = [];
275
- const blockLocaleRowsToInsert = blockRows.reduce((acc, blockRow, i)=>{
276
- if (Object.entries(blockRow.locales).length > 0) {
277
- Object.entries(blockRow.locales).forEach(([blockLocale, blockLocaleData])=>{
278
- if (Object.keys(blockLocaleData).length > 0) {
279
- blockLocaleData._parentID = blockRow.row.id;
280
- blockLocaleData._locale = blockLocale;
281
- acc.push(blockLocaleData);
282
- blockLocaleIndexMap.push(i);
283
- }
284
- });
285
- }
286
- return acc;
287
- }, []);
288
- if (blockLocaleRowsToInsert.length > 0) {
289
- await adapter.insert({
290
- db,
291
- tableName: `${tableName}${adapter.localesSuffix}`,
292
- values: blockLocaleRowsToInsert
293
- });
294
- }
295
- await insertArrays({
296
- adapter,
297
- arrays: blockRows.map(({ arrays })=>arrays),
392
+ }
393
+ if (tableRows.length) {
394
+ await adapter.insert({
298
395
  db,
299
- parentRows: insertedBlockRows[tableName],
300
- uuidMap: arraysBlocksUUIDMap
396
+ tableName: selectTableName,
397
+ values: tableRows
301
398
  });
302
399
  }
303
- // //////////////////////////////////
304
- // INSERT ARRAYS RECURSIVELY
305
- // //////////////////////////////////
306
- if (operation === 'update') {
307
- for (const arrayTableName of Object.keys(rowToInsert.arrays)){
308
- await deleteExistingArrayRows({
309
- adapter,
310
- db,
311
- parentID: insertedRow.id,
312
- tableName: arrayTableName
313
- });
314
- }
315
- }
316
- await insertArrays({
317
- adapter,
318
- arrays: [
319
- rowToInsert.arrays
320
- ],
321
- db,
322
- parentRows: [
323
- insertedRow
324
- ],
325
- uuidMap: arraysBlocksUUIDMap
326
- });
327
- // //////////////////////////////////
328
- // INSERT hasMany SELECTS
329
- // //////////////////////////////////
330
- for (const [selectTableName, tableRows] of Object.entries(selectsToInsert)){
331
- const selectTable = adapter.tables[selectTableName];
332
- if (operation === 'update') {
333
- await adapter.deleteWhere({
334
- db,
335
- tableName: selectTableName,
336
- where: eq(selectTable.parent, insertedRow.id)
337
- });
338
- }
339
- if (Object.keys(arraysBlocksUUIDMap).length > 0) {
340
- tableRows.forEach((row)=>{
341
- if (row.parent in arraysBlocksUUIDMap) {
342
- row.parent = arraysBlocksUUIDMap[row.parent];
400
+ }
401
+ // //////////////////////////////////
402
+ // Error Handling
403
+ // //////////////////////////////////
404
+ } catch (caughtError) {
405
+ // Unique constraint violation error
406
+ // '23505' is the code for PostgreSQL, and 'SQLITE_CONSTRAINT_UNIQUE' is for SQLite
407
+ let error = caughtError;
408
+ if (typeof caughtError === 'object' && 'cause' in caughtError) {
409
+ error = caughtError.cause;
410
+ }
411
+ if (error.code === '23505' || error.code === 'SQLITE_CONSTRAINT_UNIQUE') {
412
+ let fieldName = null;
413
+ // We need to try and find the right constraint for the field but if we can't we fallback to a generic message
414
+ if (error.code === '23505') {
415
+ // For PostgreSQL, we can try to extract the field name from the error constraint
416
+ if (adapter.fieldConstraints?.[tableName]?.[error.constraint]) {
417
+ fieldName = adapter.fieldConstraints[tableName]?.[error.constraint];
418
+ } else {
419
+ const replacement = `${tableName}_`;
420
+ if (error.constraint.includes(replacement)) {
421
+ const replacedConstraint = error.constraint.replace(replacement, '');
422
+ if (replacedConstraint && adapter.fieldConstraints[tableName]?.[replacedConstraint]) {
423
+ fieldName = adapter.fieldConstraints[tableName][replacedConstraint];
343
424
  }
344
- });
425
+ }
345
426
  }
346
- if (tableRows.length) {
347
- await adapter.insert({
348
- db,
349
- tableName: selectTableName,
350
- values: tableRows
351
- });
427
+ if (!fieldName) {
428
+ // Last case scenario we extract the key and value from the detail on the error
429
+ const detail = error.detail;
430
+ const regex = /Key \(([^)]+)\)=\(([^)]+)\)/;
431
+ const match = detail.match(regex);
432
+ if (match && match[1]) {
433
+ const key = match[1];
434
+ fieldName = key;
435
+ }
352
436
  }
353
- }
354
- // //////////////////////////////////
355
- // Error Handling
356
- // //////////////////////////////////
357
- } catch (caughtError) {
358
- // Unique constraint violation error
359
- // '23505' is the code for PostgreSQL, and 'SQLITE_CONSTRAINT_UNIQUE' is for SQLite
360
- let error = caughtError;
361
- if (typeof caughtError === 'object' && 'cause' in caughtError) {
362
- error = caughtError.cause;
363
- }
364
- if (error.code === '23505' || error.code === 'SQLITE_CONSTRAINT_UNIQUE') {
365
- let fieldName = null;
366
- // We need to try and find the right constraint for the field but if we can't we fallback to a generic message
367
- if (error.code === '23505') {
368
- // For PostgreSQL, we can try to extract the field name from the error constraint
369
- if (adapter.fieldConstraints?.[tableName]?.[error.constraint]) {
370
- fieldName = adapter.fieldConstraints[tableName]?.[error.constraint];
371
- } else {
372
- const replacement = `${tableName}_`;
373
- if (error.constraint.includes(replacement)) {
374
- const replacedConstraint = error.constraint.replace(replacement, '');
375
- if (replacedConstraint && adapter.fieldConstraints[tableName]?.[replacedConstraint]) {
376
- fieldName = adapter.fieldConstraints[tableName][replacedConstraint];
377
- }
378
- }
437
+ } else if (error.code === 'SQLITE_CONSTRAINT_UNIQUE') {
438
+ /**
439
+ * For SQLite, we can try to extract the field name from the error message
440
+ * The message typically looks like:
441
+ * "UNIQUE constraint failed: table_name.field_name"
442
+ */ const regex = /UNIQUE constraint failed: ([^.]+)\.([^.]+)/;
443
+ const match = error.message.match(regex);
444
+ if (match && match[2]) {
445
+ if (adapter.fieldConstraints[tableName]) {
446
+ fieldName = adapter.fieldConstraints[tableName][`${match[2]}_idx`];
379
447
  }
380
448
  if (!fieldName) {
381
- // Last case scenario we extract the key and value from the detail on the error
382
- const detail = error.detail;
383
- const regex = /Key \(([^)]+)\)=\(([^)]+)\)/;
384
- const match = detail.match(regex);
385
- if (match && match[1]) {
386
- const key = match[1];
387
- fieldName = key;
388
- }
389
- }
390
- } else if (error.code === 'SQLITE_CONSTRAINT_UNIQUE') {
391
- /**
392
- * For SQLite, we can try to extract the field name from the error message
393
- * The message typically looks like:
394
- * "UNIQUE constraint failed: table_name.field_name"
395
- */ const regex = /UNIQUE constraint failed: ([^.]+)\.([^.]+)/;
396
- const match = error.message.match(regex);
397
- if (match && match[2]) {
398
- if (adapter.fieldConstraints[tableName]) {
399
- fieldName = adapter.fieldConstraints[tableName][`${match[2]}_idx`];
400
- }
401
- if (!fieldName) {
402
- fieldName = match[2];
403
- }
449
+ fieldName = match[2];
404
450
  }
405
451
  }
406
- throw new ValidationError({
407
- id,
408
- errors: [
409
- {
410
- message: req?.t ? req.t('error:valueMustBeUnique') : 'Value must be unique',
411
- path: fieldName
412
- }
413
- ],
414
- req
415
- }, req?.t);
416
- } else {
417
- throw error;
418
452
  }
453
+ throw new ValidationError({
454
+ id,
455
+ errors: [
456
+ {
457
+ message: req?.t ? req.t('error:valueMustBeUnique') : 'Value must be unique',
458
+ path: fieldName
459
+ }
460
+ ],
461
+ req
462
+ }, req?.t);
463
+ } else {
464
+ throw error;
419
465
  }
420
466
  }
421
467
  if (ignoreResult === 'idOnly') {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/upsertRow/index.ts"],"sourcesContent":["import type { LibSQLDatabase } from 'drizzle-orm/libsql'\nimport type { TypeWithID } from 'payload'\n\nimport { eq } from 'drizzle-orm'\nimport { ValidationError } from 'payload'\n\nimport type { BlockRowToInsert } from '../transform/write/types.js'\nimport type { Args } from './types.js'\n\nimport { buildFindManyArgs } from '../find/buildFindManyArgs.js'\nimport { transform } from '../transform/read/index.js'\nimport { transformForWrite } from '../transform/write/index.js'\nimport { deleteExistingArrayRows } from './deleteExistingArrayRows.js'\nimport { deleteExistingRowsByPath } from './deleteExistingRowsByPath.js'\nimport { insertArrays } from './insertArrays.js'\nimport { shouldUseOptimizedUpsertRow } from './shouldUseOptimizedUpsertRow.js'\n\n/**\n * If `id` is provided, it will update the row with that ID.\n * If `where` is provided, it will update the row that matches the `where`\n * If neither `id` nor `where` is provided, it will create a new row.\n *\n * adapter function replaces the entire row and does not support partial updates.\n */\nexport const upsertRow = async <T extends Record<string, unknown> | TypeWithID>({\n id,\n adapter,\n data,\n db,\n fields,\n ignoreResult,\n // TODO:\n // When we support joins for write operations (create/update) - pass collectionSlug to the buildFindManyArgs\n // Make a new argument in upsertRow.ts and pass the slug from every operation.\n joinQuery: _joinQuery,\n operation,\n path = '',\n req,\n select,\n tableName,\n upsertTarget,\n where,\n}: Args): Promise<T> => {\n let insertedRow: Record<string, unknown> = { id }\n if (id && shouldUseOptimizedUpsertRow({ data, fields })) {\n const { row } = transformForWrite({\n adapter,\n data,\n enableAtomicWrites: true,\n fields,\n tableName,\n })\n\n const drizzle = db as LibSQLDatabase\n\n await drizzle\n .update(adapter.tables[tableName])\n .set(row)\n // TODO: we can skip fetching idToUpdate here with using the incoming where\n .where(eq(adapter.tables[tableName].id, id))\n } else {\n // Split out the incoming data into the corresponding:\n // base row, locales, relationships, blocks, and arrays\n const rowToInsert = transformForWrite({\n adapter,\n data,\n enableAtomicWrites: false,\n fields,\n path,\n tableName,\n })\n\n // First, we insert the main row\n try {\n if (operation === 'update') {\n const target = upsertTarget || adapter.tables[tableName].id\n\n if (id) {\n rowToInsert.row.id = id\n ;[insertedRow] = await adapter.insert({\n db,\n onConflictDoUpdate: { set: rowToInsert.row, target },\n tableName,\n values: rowToInsert.row,\n })\n } else {\n ;[insertedRow] = await adapter.insert({\n db,\n onConflictDoUpdate: { set: rowToInsert.row, target, where },\n tableName,\n values: rowToInsert.row,\n })\n }\n } else {\n if (adapter.allowIDOnCreate && data.id) {\n rowToInsert.row.id = data.id\n }\n ;[insertedRow] = await adapter.insert({\n db,\n tableName,\n values: rowToInsert.row,\n })\n }\n\n const localesToInsert: Record<string, unknown>[] = []\n const relationsToInsert: Record<string, unknown>[] = []\n const textsToInsert: Record<string, unknown>[] = []\n const numbersToInsert: Record<string, unknown>[] = []\n const blocksToInsert: { [blockType: string]: BlockRowToInsert[] } = {}\n const selectsToInsert: { [selectTableName: string]: Record<string, unknown>[] } = {}\n\n // If there are locale rows with data, add the parent and locale to each\n if (Object.keys(rowToInsert.locales).length > 0) {\n Object.entries(rowToInsert.locales).forEach(([locale, localeRow]) => {\n localeRow._parentID = insertedRow.id\n localeRow._locale = locale\n localesToInsert.push(localeRow)\n })\n }\n\n // If there are relationships, add parent to each\n if (rowToInsert.relationships.length > 0) {\n rowToInsert.relationships.forEach((relation) => {\n relation.parent = insertedRow.id\n relationsToInsert.push(relation)\n })\n }\n\n // If there are texts, add parent to each\n if (rowToInsert.texts.length > 0) {\n rowToInsert.texts.forEach((textRow) => {\n textRow.parent = insertedRow.id\n textsToInsert.push(textRow)\n })\n }\n\n // If there are numbers, add parent to each\n if (rowToInsert.numbers.length > 0) {\n rowToInsert.numbers.forEach((numberRow) => {\n numberRow.parent = insertedRow.id\n numbersToInsert.push(numberRow)\n })\n }\n\n // If there are selects, add parent to each, and then\n // store by table name and rows\n if (Object.keys(rowToInsert.selects).length > 0) {\n Object.entries(rowToInsert.selects).forEach(([selectTableName, selectRows]) => {\n selectsToInsert[selectTableName] = []\n\n selectRows.forEach((row) => {\n if (typeof row.parent === 'undefined') {\n row.parent = insertedRow.id\n }\n\n selectsToInsert[selectTableName].push(row)\n })\n })\n }\n\n // If there are blocks, add parent to each, and then\n // store by table name and rows\n Object.keys(rowToInsert.blocks).forEach((tableName) => {\n rowToInsert.blocks[tableName].forEach((blockRow) => {\n blockRow.row._parentID = insertedRow.id\n if (!blocksToInsert[tableName]) {\n blocksToInsert[tableName] = []\n }\n if (blockRow.row.uuid) {\n delete blockRow.row.uuid\n }\n blocksToInsert[tableName].push(blockRow)\n })\n })\n\n // //////////////////////////////////\n // INSERT LOCALES\n // //////////////////////////////////\n\n if (localesToInsert.length > 0) {\n const localeTableName = `${tableName}${adapter.localesSuffix}`\n const localeTable = adapter.tables[`${tableName}${adapter.localesSuffix}`]\n\n if (operation === 'update') {\n await adapter.deleteWhere({\n db,\n tableName: localeTableName,\n where: eq(localeTable._parentID, insertedRow.id),\n })\n }\n\n await adapter.insert({\n db,\n tableName: localeTableName,\n values: localesToInsert,\n })\n }\n\n // //////////////////////////////////\n // INSERT RELATIONSHIPS\n // //////////////////////////////////\n\n const relationshipsTableName = `${tableName}${adapter.relationshipsSuffix}`\n\n if (operation === 'update') {\n await deleteExistingRowsByPath({\n adapter,\n db,\n localeColumnName: 'locale',\n parentColumnName: 'parent',\n parentID: insertedRow.id,\n pathColumnName: 'path',\n rows: [...relationsToInsert, ...rowToInsert.relationshipsToDelete],\n tableName: relationshipsTableName,\n })\n }\n\n if (relationsToInsert.length > 0) {\n await adapter.insert({\n db,\n tableName: relationshipsTableName,\n values: relationsToInsert,\n })\n }\n\n // //////////////////////////////////\n // INSERT hasMany TEXTS\n // //////////////////////////////////\n\n const textsTableName = `${tableName}_texts`\n\n if (operation === 'update') {\n await deleteExistingRowsByPath({\n adapter,\n db,\n localeColumnName: 'locale',\n parentColumnName: 'parent',\n parentID: insertedRow.id,\n pathColumnName: 'path',\n rows: [...textsToInsert, ...rowToInsert.textsToDelete],\n tableName: textsTableName,\n })\n }\n\n if (textsToInsert.length > 0) {\n await adapter.insert({\n db,\n tableName: textsTableName,\n values: textsToInsert,\n })\n }\n\n // //////////////////////////////////\n // INSERT hasMany NUMBERS\n // //////////////////////////////////\n\n const numbersTableName = `${tableName}_numbers`\n\n if (operation === 'update') {\n await deleteExistingRowsByPath({\n adapter,\n db,\n localeColumnName: 'locale',\n parentColumnName: 'parent',\n parentID: insertedRow.id,\n pathColumnName: 'path',\n rows: [...numbersToInsert, ...rowToInsert.numbersToDelete],\n tableName: numbersTableName,\n })\n }\n\n if (numbersToInsert.length > 0) {\n await adapter.insert({\n db,\n tableName: numbersTableName,\n values: numbersToInsert,\n })\n }\n\n // //////////////////////////////////\n // INSERT BLOCKS\n // //////////////////////////////////\n\n const insertedBlockRows: Record<string, Record<string, unknown>[]> = {}\n\n if (operation === 'update') {\n for (const tableName of rowToInsert.blocksToDelete) {\n const blockTable = adapter.tables[tableName]\n await adapter.deleteWhere({\n db,\n tableName,\n where: eq(blockTable._parentID, insertedRow.id),\n })\n }\n }\n\n // When versions are enabled, adapter is used to track mapping between blocks/arrays ObjectID to their numeric generated representation, then we use it for nested to arrays/blocks select hasMany in versions.\n const arraysBlocksUUIDMap: Record<string, number | string> = {}\n\n for (const [tableName, blockRows] of Object.entries(blocksToInsert)) {\n insertedBlockRows[tableName] = await adapter.insert({\n db,\n tableName,\n values: blockRows.map(({ row }) => row),\n })\n\n insertedBlockRows[tableName].forEach((row, i) => {\n blockRows[i].row = row\n if (\n typeof row._uuid === 'string' &&\n (typeof row.id === 'string' || typeof row.id === 'number')\n ) {\n arraysBlocksUUIDMap[row._uuid] = row.id\n }\n })\n\n const blockLocaleIndexMap: number[] = []\n\n const blockLocaleRowsToInsert = blockRows.reduce((acc, blockRow, i) => {\n if (Object.entries(blockRow.locales).length > 0) {\n Object.entries(blockRow.locales).forEach(([blockLocale, blockLocaleData]) => {\n if (Object.keys(blockLocaleData).length > 0) {\n blockLocaleData._parentID = blockRow.row.id\n blockLocaleData._locale = blockLocale\n acc.push(blockLocaleData)\n blockLocaleIndexMap.push(i)\n }\n })\n }\n\n return acc\n }, [])\n\n if (blockLocaleRowsToInsert.length > 0) {\n await adapter.insert({\n db,\n tableName: `${tableName}${adapter.localesSuffix}`,\n values: blockLocaleRowsToInsert,\n })\n }\n\n await insertArrays({\n adapter,\n arrays: blockRows.map(({ arrays }) => arrays),\n db,\n parentRows: insertedBlockRows[tableName],\n uuidMap: arraysBlocksUUIDMap,\n })\n }\n\n // //////////////////////////////////\n // INSERT ARRAYS RECURSIVELY\n // //////////////////////////////////\n\n if (operation === 'update') {\n for (const arrayTableName of Object.keys(rowToInsert.arrays)) {\n await deleteExistingArrayRows({\n adapter,\n db,\n parentID: insertedRow.id,\n tableName: arrayTableName,\n })\n }\n }\n\n await insertArrays({\n adapter,\n arrays: [rowToInsert.arrays],\n db,\n parentRows: [insertedRow],\n uuidMap: arraysBlocksUUIDMap,\n })\n\n // //////////////////////////////////\n // INSERT hasMany SELECTS\n // //////////////////////////////////\n\n for (const [selectTableName, tableRows] of Object.entries(selectsToInsert)) {\n const selectTable = adapter.tables[selectTableName]\n if (operation === 'update') {\n await adapter.deleteWhere({\n db,\n tableName: selectTableName,\n where: eq(selectTable.parent, insertedRow.id),\n })\n }\n\n if (Object.keys(arraysBlocksUUIDMap).length > 0) {\n tableRows.forEach((row: any) => {\n if (row.parent in arraysBlocksUUIDMap) {\n row.parent = arraysBlocksUUIDMap[row.parent]\n }\n })\n }\n\n if (tableRows.length) {\n await adapter.insert({\n db,\n tableName: selectTableName,\n values: tableRows,\n })\n }\n }\n\n // //////////////////////////////////\n // Error Handling\n // //////////////////////////////////\n } catch (caughtError) {\n // Unique constraint violation error\n // '23505' is the code for PostgreSQL, and 'SQLITE_CONSTRAINT_UNIQUE' is for SQLite\n\n let error = caughtError\n if (typeof caughtError === 'object' && 'cause' in caughtError) {\n error = caughtError.cause\n }\n\n if (error.code === '23505' || error.code === 'SQLITE_CONSTRAINT_UNIQUE') {\n let fieldName: null | string = null\n // We need to try and find the right constraint for the field but if we can't we fallback to a generic message\n if (error.code === '23505') {\n // For PostgreSQL, we can try to extract the field name from the error constraint\n if (adapter.fieldConstraints?.[tableName]?.[error.constraint]) {\n fieldName = adapter.fieldConstraints[tableName]?.[error.constraint]\n } else {\n const replacement = `${tableName}_`\n\n if (error.constraint.includes(replacement)) {\n const replacedConstraint = error.constraint.replace(replacement, '')\n\n if (replacedConstraint && adapter.fieldConstraints[tableName]?.[replacedConstraint]) {\n fieldName = adapter.fieldConstraints[tableName][replacedConstraint]\n }\n }\n }\n\n if (!fieldName) {\n // Last case scenario we extract the key and value from the detail on the error\n const detail = error.detail\n const regex = /Key \\(([^)]+)\\)=\\(([^)]+)\\)/\n const match: string[] = detail.match(regex)\n\n if (match && match[1]) {\n const key = match[1]\n\n fieldName = key\n }\n }\n } else if (error.code === 'SQLITE_CONSTRAINT_UNIQUE') {\n /**\n * For SQLite, we can try to extract the field name from the error message\n * The message typically looks like:\n * \"UNIQUE constraint failed: table_name.field_name\"\n */\n const regex = /UNIQUE constraint failed: ([^.]+)\\.([^.]+)/\n const match: string[] = error.message.match(regex)\n\n if (match && match[2]) {\n if (adapter.fieldConstraints[tableName]) {\n fieldName = adapter.fieldConstraints[tableName][`${match[2]}_idx`]\n }\n\n if (!fieldName) {\n fieldName = match[2]\n }\n }\n }\n\n throw new ValidationError(\n {\n id,\n errors: [\n {\n message: req?.t ? req.t('error:valueMustBeUnique') : 'Value must be unique',\n path: fieldName,\n },\n ],\n req,\n },\n req?.t,\n )\n } else {\n throw error\n }\n }\n }\n\n if (ignoreResult === 'idOnly') {\n return { id: insertedRow.id } as T\n }\n\n if (ignoreResult) {\n return data as T\n }\n\n // //////////////////////////////////\n // RETRIEVE NEWLY UPDATED ROW\n // //////////////////////////////////\n\n const findManyArgs = buildFindManyArgs({\n adapter,\n depth: 0,\n fields,\n joinQuery: false,\n select,\n tableName,\n })\n\n findManyArgs.where = eq(adapter.tables[tableName].id, insertedRow.id)\n\n const doc = await db.query[tableName].findFirst(findManyArgs)\n\n // //////////////////////////////////\n // TRANSFORM DATA\n // //////////////////////////////////\n\n const result = transform<T>({\n adapter,\n config: adapter.payload.config,\n data: doc,\n fields,\n joinQuery: false,\n tableName,\n })\n\n return result\n}\n"],"names":["eq","ValidationError","buildFindManyArgs","transform","transformForWrite","deleteExistingArrayRows","deleteExistingRowsByPath","insertArrays","shouldUseOptimizedUpsertRow","upsertRow","id","adapter","data","db","fields","ignoreResult","joinQuery","_joinQuery","operation","path","req","select","tableName","upsertTarget","where","insertedRow","row","enableAtomicWrites","drizzle","update","tables","set","rowToInsert","target","insert","onConflictDoUpdate","values","allowIDOnCreate","localesToInsert","relationsToInsert","textsToInsert","numbersToInsert","blocksToInsert","selectsToInsert","Object","keys","locales","length","entries","forEach","locale","localeRow","_parentID","_locale","push","relationships","relation","parent","texts","textRow","numbers","numberRow","selects","selectTableName","selectRows","blocks","blockRow","uuid","localeTableName","localesSuffix","localeTable","deleteWhere","relationshipsTableName","relationshipsSuffix","localeColumnName","parentColumnName","parentID","pathColumnName","rows","relationshipsToDelete","textsTableName","textsToDelete","numbersTableName","numbersToDelete","insertedBlockRows","blocksToDelete","blockTable","arraysBlocksUUIDMap","blockRows","map","i","_uuid","blockLocaleIndexMap","blockLocaleRowsToInsert","reduce","acc","blockLocale","blockLocaleData","arrays","parentRows","uuidMap","arrayTableName","tableRows","selectTable","caughtError","error","cause","code","fieldName","fieldConstraints","constraint","replacement","includes","replacedConstraint","replace","detail","regex","match","key","message","errors","t","findManyArgs","depth","doc","query","findFirst","result","config","payload"],"mappings":"AAGA,SAASA,EAAE,QAAQ,cAAa;AAChC,SAASC,eAAe,QAAQ,UAAS;AAKzC,SAASC,iBAAiB,QAAQ,+BAA8B;AAChE,SAASC,SAAS,QAAQ,6BAA4B;AACtD,SAASC,iBAAiB,QAAQ,8BAA6B;AAC/D,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,wBAAwB,QAAQ,gCAA+B;AACxE,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,2BAA2B,QAAQ,mCAAkC;AAE9E;;;;;;CAMC,GACD,OAAO,MAAMC,YAAY,OAAuD,EAC9EC,EAAE,EACFC,OAAO,EACPC,IAAI,EACJC,EAAE,EACFC,MAAM,EACNC,YAAY,EACZ,QAAQ;AACR,4GAA4G;AAC5G,8EAA8E;AAC9EC,WAAWC,UAAU,EACrBC,SAAS,EACTC,OAAO,EAAE,EACTC,GAAG,EACHC,MAAM,EACNC,SAAS,EACTC,YAAY,EACZC,KAAK,EACA;IACL,IAAIC,cAAuC;QAAEf;IAAG;IAChD,IAAIA,MAAMF,4BAA4B;QAAEI;QAAME;IAAO,IAAI;QACvD,MAAM,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;IAEA,qCAAqC;IACrC,6BAA6B;IAC7B,qCAAqC;IAErC,MAAM8G,eAAexH,kBAAkB;QACrCS;QACAgH,OAAO;QACP7G;QACAE,WAAW;QACXK;QACAC;IACF;IAEAoG,aAAalG,KAAK,GAAGxB,GAAGW,QAAQmB,MAAM,CAACR,UAAU,CAACZ,EAAE,EAAEe,YAAYf,EAAE;IAEpE,MAAMkH,MAAM,MAAM/G,GAAGgH,KAAK,CAACvG,UAAU,CAACwG,SAAS,CAACJ;IAEhD,qCAAqC;IACrC,iBAAiB;IACjB,qCAAqC;IAErC,MAAMK,SAAS5H,UAAa;QAC1BQ;QACAqH,QAAQrH,QAAQsH,OAAO,CAACD,MAAM;QAC9BpH,MAAMgH;QACN9G;QACAE,WAAW;QACXM;IACF;IAEA,OAAOyG;AACT,EAAC"}
1
+ {"version":3,"sources":["../../src/upsertRow/index.ts"],"sourcesContent":["import type { LibSQLDatabase } from 'drizzle-orm/libsql'\nimport type { SelectedFields } from 'drizzle-orm/sqlite-core'\nimport type { TypeWithID } from 'payload'\n\nimport { eq } from 'drizzle-orm'\nimport { ValidationError } from 'payload'\n\nimport type { BlockRowToInsert } from '../transform/write/types.js'\nimport type { Args } from './types.js'\n\nimport { buildFindManyArgs } from '../find/buildFindManyArgs.js'\nimport { transform } from '../transform/read/index.js'\nimport { transformForWrite } from '../transform/write/index.js'\nimport { deleteExistingArrayRows } from './deleteExistingArrayRows.js'\nimport { deleteExistingRowsByPath } from './deleteExistingRowsByPath.js'\nimport { insertArrays } from './insertArrays.js'\nimport { shouldUseOptimizedUpsertRow } from './shouldUseOptimizedUpsertRow.js'\n\n/**\n * If `id` is provided, it will update the row with that ID.\n * If `where` is provided, it will update the row that matches the `where`\n * If neither `id` nor `where` is provided, it will create a new row.\n *\n * adapter function replaces the entire row and does not support partial updates.\n */\nexport const upsertRow = async <T extends Record<string, unknown> | TypeWithID>({\n id,\n adapter,\n data,\n db,\n fields,\n ignoreResult,\n // TODO:\n // When we support joins for write operations (create/update) - pass collectionSlug to the buildFindManyArgs\n // Make a new argument in upsertRow.ts and pass the slug from every operation.\n joinQuery: _joinQuery,\n operation,\n path = '',\n req,\n select,\n tableName,\n upsertTarget,\n where,\n}: Args): Promise<T> => {\n let insertedRow: Record<string, unknown> = { id }\n if (id && shouldUseOptimizedUpsertRow({ data, fields })) {\n const { row } = transformForWrite({\n adapter,\n data,\n enableAtomicWrites: true,\n fields,\n tableName,\n })\n\n const drizzle = db as LibSQLDatabase\n\n if (ignoreResult) {\n await drizzle\n .update(adapter.tables[tableName])\n .set(row)\n .where(eq(adapter.tables[tableName].id, id))\n return ignoreResult === 'idOnly' ? ({ id } as T) : null\n }\n\n const findManyArgs = buildFindManyArgs({\n adapter,\n depth: 0,\n fields,\n joinQuery: false,\n select,\n tableName,\n })\n\n const findManyKeysLength = Object.keys(findManyArgs).length\n const hasOnlyColumns = Object.keys(findManyArgs.columns || {}).length > 0\n\n if (findManyKeysLength === 0 || hasOnlyColumns) {\n // Optimization - No need for joins => can simply use returning(). This is optimal for very simple collections\n // without complex fields that live in separate tables like blocks, arrays, relationships, etc.\n\n const selectedFields: SelectedFields = {}\n if (hasOnlyColumns) {\n for (const [column, enabled] of Object.entries(findManyArgs.columns)) {\n if (enabled) {\n selectedFields[column] = adapter.tables[tableName][column]\n }\n }\n }\n\n const docs = await drizzle\n .update(adapter.tables[tableName])\n .set(row)\n .where(eq(adapter.tables[tableName].id, id))\n .returning(Object.keys(selectedFields).length ? selectedFields : undefined)\n\n return transform<T>({\n adapter,\n config: adapter.payload.config,\n data: docs[0],\n fields,\n joinQuery: false,\n tableName,\n })\n }\n\n // DB Update that needs the result, potentially with joins => need to update first, then find. returning() does not work with joins.\n\n await drizzle\n .update(adapter.tables[tableName])\n .set(row)\n .where(eq(adapter.tables[tableName].id, id))\n\n findManyArgs.where = eq(adapter.tables[tableName].id, insertedRow.id)\n\n const doc = await db.query[tableName].findFirst(findManyArgs)\n\n return transform<T>({\n adapter,\n config: adapter.payload.config,\n data: doc,\n fields,\n joinQuery: false,\n tableName,\n })\n }\n // Split out the incoming data into the corresponding:\n // base row, locales, relationships, blocks, and arrays\n const rowToInsert = transformForWrite({\n adapter,\n data,\n enableAtomicWrites: false,\n fields,\n path,\n tableName,\n })\n\n // First, we insert the main row\n try {\n if (operation === 'update') {\n const target = upsertTarget || adapter.tables[tableName].id\n\n if (id) {\n rowToInsert.row.id = id\n ;[insertedRow] = await adapter.insert({\n db,\n onConflictDoUpdate: { set: rowToInsert.row, target },\n tableName,\n values: rowToInsert.row,\n })\n } else {\n ;[insertedRow] = await adapter.insert({\n db,\n onConflictDoUpdate: { set: rowToInsert.row, target, where },\n tableName,\n values: rowToInsert.row,\n })\n }\n } else {\n if (adapter.allowIDOnCreate && data.id) {\n rowToInsert.row.id = data.id\n }\n ;[insertedRow] = await adapter.insert({\n db,\n tableName,\n values: rowToInsert.row,\n })\n }\n\n const localesToInsert: Record<string, unknown>[] = []\n const relationsToInsert: Record<string, unknown>[] = []\n const textsToInsert: Record<string, unknown>[] = []\n const numbersToInsert: Record<string, unknown>[] = []\n const blocksToInsert: { [blockType: string]: BlockRowToInsert[] } = {}\n const selectsToInsert: { [selectTableName: string]: Record<string, unknown>[] } = {}\n\n // If there are locale rows with data, add the parent and locale to each\n if (Object.keys(rowToInsert.locales).length > 0) {\n Object.entries(rowToInsert.locales).forEach(([locale, localeRow]) => {\n localeRow._parentID = insertedRow.id\n localeRow._locale = locale\n localesToInsert.push(localeRow)\n })\n }\n\n // If there are relationships, add parent to each\n if (rowToInsert.relationships.length > 0) {\n rowToInsert.relationships.forEach((relation) => {\n relation.parent = insertedRow.id\n relationsToInsert.push(relation)\n })\n }\n\n // If there are texts, add parent to each\n if (rowToInsert.texts.length > 0) {\n rowToInsert.texts.forEach((textRow) => {\n textRow.parent = insertedRow.id\n textsToInsert.push(textRow)\n })\n }\n\n // If there are numbers, add parent to each\n if (rowToInsert.numbers.length > 0) {\n rowToInsert.numbers.forEach((numberRow) => {\n numberRow.parent = insertedRow.id\n numbersToInsert.push(numberRow)\n })\n }\n\n // If there are selects, add parent to each, and then\n // store by table name and rows\n if (Object.keys(rowToInsert.selects).length > 0) {\n Object.entries(rowToInsert.selects).forEach(([selectTableName, selectRows]) => {\n selectsToInsert[selectTableName] = []\n\n selectRows.forEach((row) => {\n if (typeof row.parent === 'undefined') {\n row.parent = insertedRow.id\n }\n\n selectsToInsert[selectTableName].push(row)\n })\n })\n }\n\n // If there are blocks, add parent to each, and then\n // store by table name and rows\n Object.keys(rowToInsert.blocks).forEach((tableName) => {\n rowToInsert.blocks[tableName].forEach((blockRow) => {\n blockRow.row._parentID = insertedRow.id\n if (!blocksToInsert[tableName]) {\n blocksToInsert[tableName] = []\n }\n if (blockRow.row.uuid) {\n delete blockRow.row.uuid\n }\n blocksToInsert[tableName].push(blockRow)\n })\n })\n\n // //////////////////////////////////\n // INSERT LOCALES\n // //////////////////////////////////\n\n if (localesToInsert.length > 0) {\n const localeTableName = `${tableName}${adapter.localesSuffix}`\n const localeTable = adapter.tables[`${tableName}${adapter.localesSuffix}`]\n\n if (operation === 'update') {\n await adapter.deleteWhere({\n db,\n tableName: localeTableName,\n where: eq(localeTable._parentID, insertedRow.id),\n })\n }\n\n await adapter.insert({\n db,\n tableName: localeTableName,\n values: localesToInsert,\n })\n }\n\n // //////////////////////////////////\n // INSERT RELATIONSHIPS\n // //////////////////////////////////\n\n const relationshipsTableName = `${tableName}${adapter.relationshipsSuffix}`\n\n if (operation === 'update') {\n await deleteExistingRowsByPath({\n adapter,\n db,\n localeColumnName: 'locale',\n parentColumnName: 'parent',\n parentID: insertedRow.id,\n pathColumnName: 'path',\n rows: [...relationsToInsert, ...rowToInsert.relationshipsToDelete],\n tableName: relationshipsTableName,\n })\n }\n\n if (relationsToInsert.length > 0) {\n await adapter.insert({\n db,\n tableName: relationshipsTableName,\n values: relationsToInsert,\n })\n }\n\n // //////////////////////////////////\n // INSERT hasMany TEXTS\n // //////////////////////////////////\n\n const textsTableName = `${tableName}_texts`\n\n if (operation === 'update') {\n await deleteExistingRowsByPath({\n adapter,\n db,\n localeColumnName: 'locale',\n parentColumnName: 'parent',\n parentID: insertedRow.id,\n pathColumnName: 'path',\n rows: [...textsToInsert, ...rowToInsert.textsToDelete],\n tableName: textsTableName,\n })\n }\n\n if (textsToInsert.length > 0) {\n await adapter.insert({\n db,\n tableName: textsTableName,\n values: textsToInsert,\n })\n }\n\n // //////////////////////////////////\n // INSERT hasMany NUMBERS\n // //////////////////////////////////\n\n const numbersTableName = `${tableName}_numbers`\n\n if (operation === 'update') {\n await deleteExistingRowsByPath({\n adapter,\n db,\n localeColumnName: 'locale',\n parentColumnName: 'parent',\n parentID: insertedRow.id,\n pathColumnName: 'path',\n rows: [...numbersToInsert, ...rowToInsert.numbersToDelete],\n tableName: numbersTableName,\n })\n }\n\n if (numbersToInsert.length > 0) {\n await adapter.insert({\n db,\n tableName: numbersTableName,\n values: numbersToInsert,\n })\n }\n\n // //////////////////////////////////\n // INSERT BLOCKS\n // //////////////////////////////////\n\n const insertedBlockRows: Record<string, Record<string, unknown>[]> = {}\n\n if (operation === 'update') {\n for (const tableName of rowToInsert.blocksToDelete) {\n const blockTable = adapter.tables[tableName]\n await adapter.deleteWhere({\n db,\n tableName,\n where: eq(blockTable._parentID, insertedRow.id),\n })\n }\n }\n\n // When versions are enabled, adapter is used to track mapping between blocks/arrays ObjectID to their numeric generated representation, then we use it for nested to arrays/blocks select hasMany in versions.\n const arraysBlocksUUIDMap: Record<string, number | string> = {}\n\n for (const [tableName, blockRows] of Object.entries(blocksToInsert)) {\n insertedBlockRows[tableName] = await adapter.insert({\n db,\n tableName,\n values: blockRows.map(({ row }) => row),\n })\n\n insertedBlockRows[tableName].forEach((row, i) => {\n blockRows[i].row = row\n if (\n typeof row._uuid === 'string' &&\n (typeof row.id === 'string' || typeof row.id === 'number')\n ) {\n arraysBlocksUUIDMap[row._uuid] = row.id\n }\n })\n\n const blockLocaleIndexMap: number[] = []\n\n const blockLocaleRowsToInsert = blockRows.reduce((acc, blockRow, i) => {\n if (Object.entries(blockRow.locales).length > 0) {\n Object.entries(blockRow.locales).forEach(([blockLocale, blockLocaleData]) => {\n if (Object.keys(blockLocaleData).length > 0) {\n blockLocaleData._parentID = blockRow.row.id\n blockLocaleData._locale = blockLocale\n acc.push(blockLocaleData)\n blockLocaleIndexMap.push(i)\n }\n })\n }\n\n return acc\n }, [])\n\n if (blockLocaleRowsToInsert.length > 0) {\n await adapter.insert({\n db,\n tableName: `${tableName}${adapter.localesSuffix}`,\n values: blockLocaleRowsToInsert,\n })\n }\n\n await insertArrays({\n adapter,\n arrays: blockRows.map(({ arrays }) => arrays),\n db,\n parentRows: insertedBlockRows[tableName],\n uuidMap: arraysBlocksUUIDMap,\n })\n }\n\n // //////////////////////////////////\n // INSERT ARRAYS RECURSIVELY\n // //////////////////////////////////\n\n if (operation === 'update') {\n for (const arrayTableName of Object.keys(rowToInsert.arrays)) {\n await deleteExistingArrayRows({\n adapter,\n db,\n parentID: insertedRow.id,\n tableName: arrayTableName,\n })\n }\n }\n\n await insertArrays({\n adapter,\n arrays: [rowToInsert.arrays],\n db,\n parentRows: [insertedRow],\n uuidMap: arraysBlocksUUIDMap,\n })\n\n // //////////////////////////////////\n // INSERT hasMany SELECTS\n // //////////////////////////////////\n\n for (const [selectTableName, tableRows] of Object.entries(selectsToInsert)) {\n const selectTable = adapter.tables[selectTableName]\n if (operation === 'update') {\n await adapter.deleteWhere({\n db,\n tableName: selectTableName,\n where: eq(selectTable.parent, insertedRow.id),\n })\n }\n\n if (Object.keys(arraysBlocksUUIDMap).length > 0) {\n tableRows.forEach((row: any) => {\n if (row.parent in arraysBlocksUUIDMap) {\n row.parent = arraysBlocksUUIDMap[row.parent]\n }\n })\n }\n\n if (tableRows.length) {\n await adapter.insert({\n db,\n tableName: selectTableName,\n values: tableRows,\n })\n }\n }\n\n // //////////////////////////////////\n // Error Handling\n // //////////////////////////////////\n } catch (caughtError) {\n // Unique constraint violation error\n // '23505' is the code for PostgreSQL, and 'SQLITE_CONSTRAINT_UNIQUE' is for SQLite\n\n let error = caughtError\n if (typeof caughtError === 'object' && 'cause' in caughtError) {\n error = caughtError.cause\n }\n\n if (error.code === '23505' || error.code === 'SQLITE_CONSTRAINT_UNIQUE') {\n let fieldName: null | string = null\n // We need to try and find the right constraint for the field but if we can't we fallback to a generic message\n if (error.code === '23505') {\n // For PostgreSQL, we can try to extract the field name from the error constraint\n if (adapter.fieldConstraints?.[tableName]?.[error.constraint]) {\n fieldName = adapter.fieldConstraints[tableName]?.[error.constraint]\n } else {\n const replacement = `${tableName}_`\n\n if (error.constraint.includes(replacement)) {\n const replacedConstraint = error.constraint.replace(replacement, '')\n\n if (replacedConstraint && adapter.fieldConstraints[tableName]?.[replacedConstraint]) {\n fieldName = adapter.fieldConstraints[tableName][replacedConstraint]\n }\n }\n }\n\n if (!fieldName) {\n // Last case scenario we extract the key and value from the detail on the error\n const detail = error.detail\n const regex = /Key \\(([^)]+)\\)=\\(([^)]+)\\)/\n const match: string[] = detail.match(regex)\n\n if (match && match[1]) {\n const key = match[1]\n\n fieldName = key\n }\n }\n } else if (error.code === 'SQLITE_CONSTRAINT_UNIQUE') {\n /**\n * For SQLite, we can try to extract the field name from the error message\n * The message typically looks like:\n * \"UNIQUE constraint failed: table_name.field_name\"\n */\n const regex = /UNIQUE constraint failed: ([^.]+)\\.([^.]+)/\n const match: string[] = error.message.match(regex)\n\n if (match && match[2]) {\n if (adapter.fieldConstraints[tableName]) {\n fieldName = adapter.fieldConstraints[tableName][`${match[2]}_idx`]\n }\n\n if (!fieldName) {\n fieldName = match[2]\n }\n }\n }\n\n throw new ValidationError(\n {\n id,\n errors: [\n {\n message: req?.t ? req.t('error:valueMustBeUnique') : 'Value must be unique',\n path: fieldName,\n },\n ],\n req,\n },\n req?.t,\n )\n } else {\n throw error\n }\n }\n\n if (ignoreResult === 'idOnly') {\n return { id: insertedRow.id } as T\n }\n\n if (ignoreResult) {\n return data as T\n }\n\n // //////////////////////////////////\n // RETRIEVE NEWLY UPDATED ROW\n // //////////////////////////////////\n\n const findManyArgs = buildFindManyArgs({\n adapter,\n depth: 0,\n fields,\n joinQuery: false,\n select,\n tableName,\n })\n\n findManyArgs.where = eq(adapter.tables[tableName].id, insertedRow.id)\n\n const doc = await db.query[tableName].findFirst(findManyArgs)\n\n // //////////////////////////////////\n // TRANSFORM DATA\n // //////////////////////////////////\n\n const result = transform<T>({\n adapter,\n config: adapter.payload.config,\n data: doc,\n fields,\n joinQuery: false,\n tableName,\n })\n\n return result\n}\n"],"names":["eq","ValidationError","buildFindManyArgs","transform","transformForWrite","deleteExistingArrayRows","deleteExistingRowsByPath","insertArrays","shouldUseOptimizedUpsertRow","upsertRow","id","adapter","data","db","fields","ignoreResult","joinQuery","_joinQuery","operation","path","req","select","tableName","upsertTarget","where","insertedRow","row","enableAtomicWrites","drizzle","update","tables","set","findManyArgs","depth","findManyKeysLength","Object","keys","length","hasOnlyColumns","columns","selectedFields","column","enabled","entries","docs","returning","undefined","config","payload","doc","query","findFirst","rowToInsert","target","insert","onConflictDoUpdate","values","allowIDOnCreate","localesToInsert","relationsToInsert","textsToInsert","numbersToInsert","blocksToInsert","selectsToInsert","locales","forEach","locale","localeRow","_parentID","_locale","push","relationships","relation","parent","texts","textRow","numbers","numberRow","selects","selectTableName","selectRows","blocks","blockRow","uuid","localeTableName","localesSuffix","localeTable","deleteWhere","relationshipsTableName","relationshipsSuffix","localeColumnName","parentColumnName","parentID","pathColumnName","rows","relationshipsToDelete","textsTableName","textsToDelete","numbersTableName","numbersToDelete","insertedBlockRows","blocksToDelete","blockTable","arraysBlocksUUIDMap","blockRows","map","i","_uuid","blockLocaleIndexMap","blockLocaleRowsToInsert","reduce","acc","blockLocale","blockLocaleData","arrays","parentRows","uuidMap","arrayTableName","tableRows","selectTable","caughtError","error","cause","code","fieldName","fieldConstraints","constraint","replacement","includes","replacedConstraint","replace","detail","regex","match","key","message","errors","t","result"],"mappings":"AAIA,SAASA,EAAE,QA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G,SAASvI,UAAa;QAC1BQ;QACAoC,QAAQpC,QAAQqC,OAAO,CAACD,MAAM;QAC9BnC,MAAMqC;QACNnC;QACAE,WAAW;QACXM;IACF;IAEA,OAAOoH;AACT,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"createSchemaGenerator.d.ts","sourceRoot":"","sources":["../../src/utilities/createSchemaGenerator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAM7C,OAAO,KAAK,EAAE,qBAAqB,EAAkB,MAAM,aAAa,CAAA;AAkCxE,eAAO,MAAM,qBAAqB,4GAO/B;IACD,qBAAqB,EAAE,qBAAqB,CAAA;IAC5C,iBAAiB,EAAE,MAAM,CAAA;IACzB,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,WAAW,EAAE,MAAM,CAAA;CACpB,KAAG,cAkQH,CAAA"}
1
+ {"version":3,"file":"createSchemaGenerator.d.ts","sourceRoot":"","sources":["../../src/utilities/createSchemaGenerator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAM7C,OAAO,KAAK,EAAE,qBAAqB,EAAkB,MAAM,aAAa,CAAA;AAkCxE,eAAO,MAAM,qBAAqB,4GAO/B;IACD,qBAAqB,EAAE,qBAAqB,CAAA;IAC5C,iBAAiB,EAAE,MAAM,CAAA;IACzB,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,WAAW,EAAE,MAAM,CAAA;CACpB,KAAG,cAmQH,CAAA"}
@@ -202,15 +202,15 @@ declare module '${this.packageName}' {
202
202
  }
203
203
  if (prettify) {
204
204
  try {
205
- const prettier = await import('prettier');
205
+ const prettier = await eval('import("prettier")');
206
206
  const configPath = await prettier.resolveConfigFile();
207
207
  const config = configPath ? await prettier.resolveConfig(configPath) : {};
208
208
  code = await prettier.format(code, {
209
209
  ...config,
210
210
  parser: 'typescript'
211
211
  });
212
- // eslint-disable-next-line no-empty
213
- } catch {}
212
+ } catch {
213
+ /* empty */ }
214
214
  }
215
215
  await writeFile(outputFile, code, 'utf-8');
216
216
  if (log) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utilities/createSchemaGenerator.ts"],"sourcesContent":["import type { GenerateSchema } from 'payload'\n\nimport { existsSync } from 'fs'\nimport { writeFile } from 'fs/promises'\nimport path from 'path'\n\nimport type { ColumnToCodeConverter, DrizzleAdapter } from '../types.js'\n\n/**\n * @example\n * console.log(sanitizeObjectKey(\"oneTwo\")); // oneTwo\n * console.log(sanitizeObjectKey(\"one-two\")); // 'one-two'\n * console.log(sanitizeObjectKey(\"_one$Two3\")); // _one$Two3\n * console.log(sanitizeObjectKey(\"3invalid\")); // '3invalid'\n */\nconst sanitizeObjectKey = (key: string) => {\n // Regular expression for a valid identifier\n const identifierRegex = /^[a-z_$][\\w$]*$/i\n if (identifierRegex.test(key)) {\n return key\n }\n\n return `'${key}'`\n}\n\n/**\n * @example\n * (columns default-valuesID) -> columns['default-valuesID']\n * (columns defaultValues) -> columns.defaultValues\n */\nconst accessProperty = (objName: string, key: string) => {\n const sanitized = sanitizeObjectKey(key)\n\n if (sanitized.startsWith(\"'\")) {\n return `${objName}[${sanitized}]`\n }\n\n return `${objName}.${key}`\n}\n\nexport const createSchemaGenerator = ({\n columnToCodeConverter,\n corePackageSuffix,\n defaultOutputFile,\n enumImport,\n schemaImport,\n tableImport,\n}: {\n columnToCodeConverter: ColumnToCodeConverter\n corePackageSuffix: string\n defaultOutputFile?: string\n enumImport?: string\n schemaImport?: string\n tableImport: string\n}): GenerateSchema => {\n return async function generateSchema(\n this: DrizzleAdapter,\n { log = true, outputFile = defaultOutputFile, prettify = true } = {},\n ) {\n const importDeclarations: Record<string, Set<string>> = {}\n\n const tableDeclarations: string[] = []\n const enumDeclarations: string[] = []\n const relationsDeclarations: string[] = []\n\n const addImport = (from: string, name: string) => {\n if (!importDeclarations[from]) {\n importDeclarations[from] = new Set()\n }\n\n importDeclarations[from].add(name)\n }\n\n const corePackage = `${this.packageName}/drizzle/${corePackageSuffix}`\n\n let schemaDeclaration: null | string = null\n\n if (this.schemaName) {\n addImport(corePackage, schemaImport)\n schemaDeclaration = `export const db_schema = ${schemaImport}('${this.schemaName}')`\n }\n\n const enumFn = this.schemaName ? `db_schema.enum` : enumImport\n\n const enumsList: string[] = []\n const addEnum = (name: string, options: string[]) => {\n if (enumsList.some((each) => each === name)) {\n return\n }\n enumsList.push(name)\n enumDeclarations.push(\n `export const ${name} = ${enumFn}('${name}', [${options.map((option) => `'${option}'`).join(', ')}])`,\n )\n }\n\n if (this.payload.config.localization && enumImport) {\n addEnum('enum__locales', this.payload.config.localization.localeCodes)\n }\n\n const tableFn = this.schemaName ? `db_schema.table` : tableImport\n\n if (!this.schemaName) {\n addImport(corePackage, tableImport)\n }\n\n addImport(corePackage, 'index')\n addImport(corePackage, 'uniqueIndex')\n addImport(corePackage, 'foreignKey')\n\n addImport(`${this.packageName}/drizzle`, 'sql')\n addImport(`${this.packageName}/drizzle`, 'relations')\n\n for (const tableName in this.rawTables) {\n const table = this.rawTables[tableName]\n\n const extrasDeclarations: string[] = []\n\n if (table.indexes) {\n for (const key in table.indexes) {\n const index = table.indexes[key]\n let indexDeclaration = `${sanitizeObjectKey(key)}: ${index.unique ? 'uniqueIndex' : 'index'}('${index.name}')`\n indexDeclaration += `.on(${typeof index.on === 'string' ? `${accessProperty('columns', index.on)}` : `${index.on.map((on) => `${accessProperty('columns', on)}`).join(', ')}`}),`\n extrasDeclarations.push(indexDeclaration)\n }\n }\n\n if (table.foreignKeys) {\n for (const key in table.foreignKeys) {\n const foreignKey = table.foreignKeys[key]\n\n let foreignKeyDeclaration = `${sanitizeObjectKey(key)}: foreignKey({\n columns: [${foreignKey.columns.map((col) => `columns['${col}']`).join(', ')}],\n foreignColumns: [${foreignKey.foreignColumns.map((col) => `${accessProperty(col.table, col.name)}`).join(', ')}],\n name: '${foreignKey.name}'\n })`\n\n if (foreignKey.onDelete) {\n foreignKeyDeclaration += `.onDelete('${foreignKey.onDelete}')`\n }\n if (foreignKey.onUpdate) {\n foreignKeyDeclaration += `.onUpdate('${foreignKey.onDelete}')`\n }\n\n foreignKeyDeclaration += ','\n\n extrasDeclarations.push(foreignKeyDeclaration)\n }\n }\n\n const tableCode = `\nexport const ${tableName} = ${tableFn}('${tableName}', {\n${Object.entries(table.columns)\n .map(\n ([key, column]) =>\n ` ${sanitizeObjectKey(key)}: ${columnToCodeConverter({\n adapter: this,\n addEnum,\n addImport,\n column,\n locales: this.payload.config.localization\n ? this.payload.config.localization.localeCodes\n : undefined,\n tableKey: tableName,\n })},`,\n )\n .join('\\n')}\n}${\n extrasDeclarations.length\n ? `, (columns) => ({\n ${extrasDeclarations.join('\\n ')}\n })`\n : ''\n }\n)\n`\n\n tableDeclarations.push(tableCode)\n }\n\n for (const tableName in this.rawRelations) {\n const relations = this.rawRelations[tableName]\n const properties: string[] = []\n\n for (const key in relations) {\n const relation = relations[key]\n let declaration: string\n\n if (relation.type === 'one') {\n declaration = `${sanitizeObjectKey(key)}: one(${relation.to}, {\n ${relation.fields.some((field) => field.table !== tableName) ? '// @ts-expect-error Drizzle TypeScript bug for ONE relationships with a field in different table' : ''}\n fields: [${relation.fields.map((field) => `${accessProperty(field.table, field.name)}`).join(', ')}],\n references: [${relation.references.map((col) => `${accessProperty(relation.to, col)}`).join(', ')}],\n ${relation.relationName ? `relationName: '${relation.relationName}',` : ''}\n }),`\n } else {\n declaration = `${sanitizeObjectKey(key)}: many(${relation.to}, {\n ${relation.relationName ? `relationName: '${relation.relationName}',` : ''}\n }),`\n }\n\n properties.push(declaration)\n }\n\n // beautify / lintify relations callback output, when no many for example, don't add it\n const args = []\n\n if (Object.values(relations).some((rel) => rel.type === 'one')) {\n args.push('one')\n }\n\n if (Object.values(relations).some((rel) => rel.type === 'many')) {\n args.push('many')\n }\n\n const arg = args.length ? `{ ${args.join(', ')} }` : ''\n\n const declaration = `export const relations_${tableName} = relations(${tableName}, (${arg}) => ({\n ${properties.join('\\n ')}\n }))`\n\n relationsDeclarations.push(declaration)\n }\n\n if (enumDeclarations.length && !this.schemaName) {\n addImport(corePackage, enumImport)\n }\n\n const importDeclarationsSanitized: string[] = []\n\n for (const moduleName in importDeclarations) {\n const moduleImports = importDeclarations[moduleName]\n\n importDeclarationsSanitized.push(\n `import { ${Array.from(moduleImports).join(', ')} } from '${moduleName}'`,\n )\n }\n\n const schemaType = `\ntype DatabaseSchema = {\n ${[\n this.schemaName ? 'db_schema' : null,\n ...enumsList,\n ...Object.keys(this.rawTables),\n ...Object.keys(this.rawRelations).map((table) => `relations_${table}`),\n ]\n .filter(Boolean)\n .map((name) => `${name}: typeof ${name}`)\n .join('\\n ')}\n}\n `\n\n const finalDeclaration = `\ndeclare module '${this.packageName}' {\n export interface GeneratedDatabaseSchema {\n schema: DatabaseSchema\n }\n}\n `\n\n const warning = `\n/* tslint:disable */\n/* eslint-disable */\n/**\n * This file was automatically generated by Payload.\n * DO NOT MODIFY IT BY HAND. Instead, modify your source Payload config,\n * and re-run \\`payload generate:db-schema\\` to regenerate this file.\n */\n`\n\n const importTypes = `import type {} from '${this.packageName}'`\n\n let code = [\n warning,\n importTypes,\n ...importDeclarationsSanitized,\n schemaDeclaration,\n ...enumDeclarations,\n ...tableDeclarations,\n ...relationsDeclarations,\n schemaType,\n finalDeclaration,\n ]\n .filter(Boolean)\n .join('\\n')\n\n if (!outputFile) {\n const cwd = process.cwd()\n const srcDir = path.resolve(cwd, 'src')\n\n if (existsSync(srcDir)) {\n outputFile = path.resolve(srcDir, 'payload-generated-schema.ts')\n } else {\n outputFile = path.resolve(cwd, 'payload-generated-schema.ts')\n }\n }\n\n if (prettify) {\n try {\n const prettier = await import('prettier')\n const configPath = await prettier.resolveConfigFile()\n const config = configPath ? await prettier.resolveConfig(configPath) : {}\n code = await prettier.format(code, { ...config, parser: 'typescript' })\n // eslint-disable-next-line no-empty\n } catch {}\n }\n\n await writeFile(outputFile, code, 'utf-8')\n\n if (log) {\n this.payload.logger.info(`Written ${outputFile}`)\n }\n }\n}\n"],"names":["existsSync","writeFile","path","sanitizeObjectKey","key","identifierRegex","test","accessProperty","objName","sanitized","startsWith","createSchemaGenerator","columnToCodeConverter","corePackageSuffix","defaultOutputFile","enumImport","schemaImport","tableImport","generateSchema","log","outputFile","prettify","importDeclarations","tableDeclarations","enumDeclarations","relationsDeclarations","addImport","from","name","Set","add","corePackage","packageName","schemaDeclaration","schemaName","enumFn","enumsList","addEnum","options","some","each","push","map","option","join","payload","config","localization","localeCodes","tableFn","tableName","rawTables","table","extrasDeclarations","indexes","index","indexDeclaration","unique","on","foreignKeys","foreignKey","foreignKeyDeclaration","columns","col","foreignColumns","onDelete","onUpdate","tableCode","Object","entries","column","adapter","locales","undefined","tableKey","length","rawRelations","relations","properties","relation","declaration","type","to","fields","field","references","relationName","args","values","rel","arg","importDeclarationsSanitized","moduleName","moduleImports","Array","schemaType","keys","filter","Boolean","finalDeclaration","warning","importTypes","code","cwd","process","srcDir","resolve","prettier","configPath","resolveConfigFile","resolveConfig","format","parser","logger","info"],"mappings":"AAEA,SAASA,UAAU,QAAQ,KAAI;AAC/B,SAASC,SAAS,QAAQ,cAAa;AACvC,OAAOC,UAAU,OAAM;AAIvB;;;;;;CAMC,GACD,MAAMC,oBAAoB,CAACC;IACzB,4CAA4C;IAC5C,MAAMC,kBAAkB;IACxB,IAAIA,gBAAgBC,IAAI,CAACF,MAAM;QAC7B,OAAOA;IACT;IAEA,OAAO,CAAC,CAAC,EAAEA,IAAI,CAAC,CAAC;AACnB;AAEA;;;;CAIC,GACD,MAAMG,iBAAiB,CAACC,SAAiBJ;IACvC,MAAMK,YAAYN,kBAAkBC;IAEpC,IAAIK,UAAUC,UAAU,CAAC,MAAM;QA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createSchemaGenerator.ts"],"sourcesContent":["import type { GenerateSchema } from 'payload'\n\nimport { existsSync } from 'fs'\nimport { writeFile } from 'fs/promises'\nimport path from 'path'\n\nimport type { ColumnToCodeConverter, DrizzleAdapter } from '../types.js'\n\n/**\n * @example\n * console.log(sanitizeObjectKey(\"oneTwo\")); // oneTwo\n * console.log(sanitizeObjectKey(\"one-two\")); // 'one-two'\n * console.log(sanitizeObjectKey(\"_one$Two3\")); // _one$Two3\n * console.log(sanitizeObjectKey(\"3invalid\")); // '3invalid'\n */\nconst sanitizeObjectKey = (key: string) => {\n // Regular expression for a valid identifier\n const identifierRegex = /^[a-z_$][\\w$]*$/i\n if (identifierRegex.test(key)) {\n return key\n }\n\n return `'${key}'`\n}\n\n/**\n * @example\n * (columns default-valuesID) -> columns['default-valuesID']\n * (columns defaultValues) -> columns.defaultValues\n */\nconst accessProperty = (objName: string, key: string) => {\n const sanitized = sanitizeObjectKey(key)\n\n if (sanitized.startsWith(\"'\")) {\n return `${objName}[${sanitized}]`\n }\n\n return `${objName}.${key}`\n}\n\nexport const createSchemaGenerator = ({\n columnToCodeConverter,\n corePackageSuffix,\n defaultOutputFile,\n enumImport,\n schemaImport,\n tableImport,\n}: {\n columnToCodeConverter: ColumnToCodeConverter\n corePackageSuffix: string\n defaultOutputFile?: string\n enumImport?: string\n schemaImport?: string\n tableImport: string\n}): GenerateSchema => {\n return async function generateSchema(\n this: DrizzleAdapter,\n { log = true, outputFile = defaultOutputFile, prettify = true } = {},\n ) {\n const importDeclarations: Record<string, Set<string>> = {}\n\n const tableDeclarations: string[] = []\n const enumDeclarations: string[] = []\n const relationsDeclarations: string[] = []\n\n const addImport = (from: string, name: string) => {\n if (!importDeclarations[from]) {\n importDeclarations[from] = new Set()\n }\n\n importDeclarations[from].add(name)\n }\n\n const corePackage = `${this.packageName}/drizzle/${corePackageSuffix}`\n\n let schemaDeclaration: null | string = null\n\n if (this.schemaName) {\n addImport(corePackage, schemaImport)\n schemaDeclaration = `export const db_schema = ${schemaImport}('${this.schemaName}')`\n }\n\n const enumFn = this.schemaName ? `db_schema.enum` : enumImport\n\n const enumsList: string[] = []\n const addEnum = (name: string, options: string[]) => {\n if (enumsList.some((each) => each === name)) {\n return\n }\n enumsList.push(name)\n enumDeclarations.push(\n `export const ${name} = ${enumFn}('${name}', [${options.map((option) => `'${option}'`).join(', ')}])`,\n )\n }\n\n if (this.payload.config.localization && enumImport) {\n addEnum('enum__locales', this.payload.config.localization.localeCodes)\n }\n\n const tableFn = this.schemaName ? `db_schema.table` : tableImport\n\n if (!this.schemaName) {\n addImport(corePackage, tableImport)\n }\n\n addImport(corePackage, 'index')\n addImport(corePackage, 'uniqueIndex')\n addImport(corePackage, 'foreignKey')\n\n addImport(`${this.packageName}/drizzle`, 'sql')\n addImport(`${this.packageName}/drizzle`, 'relations')\n\n for (const tableName in this.rawTables) {\n const table = this.rawTables[tableName]\n\n const extrasDeclarations: string[] = []\n\n if (table.indexes) {\n for (const key in table.indexes) {\n const index = table.indexes[key]\n let indexDeclaration = `${sanitizeObjectKey(key)}: ${index.unique ? 'uniqueIndex' : 'index'}('${index.name}')`\n indexDeclaration += `.on(${typeof index.on === 'string' ? `${accessProperty('columns', index.on)}` : `${index.on.map((on) => `${accessProperty('columns', on)}`).join(', ')}`}),`\n extrasDeclarations.push(indexDeclaration)\n }\n }\n\n if (table.foreignKeys) {\n for (const key in table.foreignKeys) {\n const foreignKey = table.foreignKeys[key]\n\n let foreignKeyDeclaration = `${sanitizeObjectKey(key)}: foreignKey({\n columns: [${foreignKey.columns.map((col) => `columns['${col}']`).join(', ')}],\n foreignColumns: [${foreignKey.foreignColumns.map((col) => `${accessProperty(col.table, col.name)}`).join(', ')}],\n name: '${foreignKey.name}'\n })`\n\n if (foreignKey.onDelete) {\n foreignKeyDeclaration += `.onDelete('${foreignKey.onDelete}')`\n }\n if (foreignKey.onUpdate) {\n foreignKeyDeclaration += `.onUpdate('${foreignKey.onDelete}')`\n }\n\n foreignKeyDeclaration += ','\n\n extrasDeclarations.push(foreignKeyDeclaration)\n }\n }\n\n const tableCode = `\nexport const ${tableName} = ${tableFn}('${tableName}', {\n${Object.entries(table.columns)\n .map(\n ([key, column]) =>\n ` ${sanitizeObjectKey(key)}: ${columnToCodeConverter({\n adapter: this,\n addEnum,\n addImport,\n column,\n locales: this.payload.config.localization\n ? this.payload.config.localization.localeCodes\n : undefined,\n tableKey: tableName,\n })},`,\n )\n .join('\\n')}\n}${\n extrasDeclarations.length\n ? `, (columns) => ({\n ${extrasDeclarations.join('\\n ')}\n })`\n : ''\n }\n)\n`\n\n tableDeclarations.push(tableCode)\n }\n\n for (const tableName in this.rawRelations) {\n const relations = this.rawRelations[tableName]\n const properties: string[] = []\n\n for (const key in relations) {\n const relation = relations[key]\n let declaration: string\n\n if (relation.type === 'one') {\n declaration = `${sanitizeObjectKey(key)}: one(${relation.to}, {\n ${relation.fields.some((field) => field.table !== tableName) ? '// @ts-expect-error Drizzle TypeScript bug for ONE relationships with a field in different table' : ''}\n fields: [${relation.fields.map((field) => `${accessProperty(field.table, field.name)}`).join(', ')}],\n references: [${relation.references.map((col) => `${accessProperty(relation.to, col)}`).join(', ')}],\n ${relation.relationName ? `relationName: '${relation.relationName}',` : ''}\n }),`\n } else {\n declaration = `${sanitizeObjectKey(key)}: many(${relation.to}, {\n ${relation.relationName ? `relationName: '${relation.relationName}',` : ''}\n }),`\n }\n\n properties.push(declaration)\n }\n\n // beautify / lintify relations callback output, when no many for example, don't add it\n const args = []\n\n if (Object.values(relations).some((rel) => rel.type === 'one')) {\n args.push('one')\n }\n\n if (Object.values(relations).some((rel) => rel.type === 'many')) {\n args.push('many')\n }\n\n const arg = args.length ? `{ ${args.join(', ')} }` : ''\n\n const declaration = `export const relations_${tableName} = relations(${tableName}, (${arg}) => ({\n ${properties.join('\\n ')}\n }))`\n\n relationsDeclarations.push(declaration)\n }\n\n if (enumDeclarations.length && !this.schemaName) {\n addImport(corePackage, enumImport)\n }\n\n const importDeclarationsSanitized: string[] = []\n\n for (const moduleName in importDeclarations) {\n const moduleImports = importDeclarations[moduleName]\n\n importDeclarationsSanitized.push(\n `import { ${Array.from(moduleImports).join(', ')} } from '${moduleName}'`,\n )\n }\n\n const schemaType = `\ntype DatabaseSchema = {\n ${[\n this.schemaName ? 'db_schema' : null,\n ...enumsList,\n ...Object.keys(this.rawTables),\n ...Object.keys(this.rawRelations).map((table) => `relations_${table}`),\n ]\n .filter(Boolean)\n .map((name) => `${name}: typeof ${name}`)\n .join('\\n ')}\n}\n `\n\n const finalDeclaration = `\ndeclare module '${this.packageName}' {\n export interface GeneratedDatabaseSchema {\n schema: DatabaseSchema\n }\n}\n `\n\n const warning = `\n/* tslint:disable */\n/* eslint-disable */\n/**\n * This file was automatically generated by Payload.\n * DO NOT MODIFY IT BY HAND. Instead, modify your source Payload config,\n * and re-run \\`payload generate:db-schema\\` to regenerate this file.\n */\n`\n\n const importTypes = `import type {} from '${this.packageName}'`\n\n let code = [\n warning,\n importTypes,\n ...importDeclarationsSanitized,\n schemaDeclaration,\n ...enumDeclarations,\n ...tableDeclarations,\n ...relationsDeclarations,\n schemaType,\n finalDeclaration,\n ]\n .filter(Boolean)\n .join('\\n')\n\n if (!outputFile) {\n const cwd = process.cwd()\n const srcDir = path.resolve(cwd, 'src')\n\n if (existsSync(srcDir)) {\n outputFile = path.resolve(srcDir, 'payload-generated-schema.ts')\n } else {\n outputFile = path.resolve(cwd, 'payload-generated-schema.ts')\n }\n }\n\n if (prettify) {\n try {\n const prettier = await eval('import(\"prettier\")')\n const configPath = await prettier.resolveConfigFile()\n const config = configPath ? await prettier.resolveConfig(configPath) : {}\n code = await prettier.format(code, { ...config, parser: 'typescript' })\n } catch {\n /* empty */\n }\n }\n\n await writeFile(outputFile, code, 'utf-8')\n\n if (log) {\n this.payload.logger.info(`Written ${outputFile}`)\n }\n }\n}\n"],"names":["existsSync","writeFile","path","sanitizeObjectKey","key","identifierRegex","test","accessProperty","objName","sanitized","startsWith","createSchemaGenerator","columnToCodeConverter","corePackageSuffix","defaultOutputFile","enumImport","schemaImport","tableImport","generateSchema","log","outputFile","prettify","importDeclarations","tableDeclarations","enumDeclarations","relationsDeclarations","addImport","from","name","Set","add","corePackage","packageName","schemaDeclaration","schemaName","enumFn","enumsList","addEnum","options","some","each","push","map","option","join","payload","config","localization","localeCodes","tableFn","tableName","rawTables","table","extrasDeclarations","indexes","index","indexDeclaration","unique","on","foreignKeys","foreignKey","foreignKeyDeclaration","columns","col","foreignColumns","onDelete","onUpdate","tableCode","Object","entries","column","adapter","locales","undefined","tableKey","length","rawRelations","relations","properties","relation","declaration","type","to","fields","field","references","relationName","args","values","rel","arg","importDeclarationsSanitized","moduleName","moduleImports","Array","schemaType","keys","filter","Boolean","finalDeclaration","warning","importTypes","code","cwd","process","srcDir","resolve","prettier","eval","configPath","resolveConfigFile","resolveConfig","format","parser","logger","info"],"mappings":"AAEA,SAASA,UAAU,QAAQ,KAAI;AAC/B,SAASC,SAAS,QAAQ,cAAa;AACvC,OAAOC,UAAU,OAAM;AAIvB;;;;;;CAMC,GACD,MAAMC,oBAAoB,CAACC;IACzB,4CAA4C;IAC5C,MAAMC,kBAAkB;IACxB,IAAIA,gBAAgBC,IAAI,CAACF,MAAM;QAC7B,OAAOA;IACT;IAEA,OAAO,CAAC,CAAC,EAAEA,IAAI,CAAC,CAAC;AACnB;AAEA;;;;CAIC,GACD,MAAMG,iBAAiB,CAACC,SAAiBJ;IACvC,MAAMK,YAAYN,kBAAkBC;IAEpC,IAAIK,UAAUC,UAAU,CAAC,MAAM;QAC7B,OAAO,GAAGF,QAAQ,CAAC,EAAEC,UAAU,CAAC,CAAC;IACnC;IAEA,OAAO,GAAGD,QAAQ,CAAC,EAAEJ,KAAK;AAC5B;AAEA,OAAO,MAAMO,wBAAwB,CAAC,EACpCC,qBAAqB,EACrBC,iBAAiB,EACjBC,iBAAiB,EACjBC,UAAU,EACVC,YAAY,EACZC,WAAW,EAQZ;IACC,OAAO,eAAeC,eAEpB,EAAEC,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B,CAAC;QAEG,MAAMC,cAAc,CAAC,qBAAqB,EAAE,IAAI,CAACrE,WAAW,CAAC,CAAC,CAAC;QAE/D,IAAIsE,OAAO;YACTF;YACAC;eACGV;YACH1D;eACGT;eACAD;eACAE;YACHsE;YACAI;SACD,CACEF,MAAM,CAACC,SACPtD,IAAI,CAAC;QAER,IAAI,CAACxB,YAAY;YACf,MAAMmF,MAAMC,QAAQD,GAAG;YACvB,MAAME,SAASvG,KAAKwG,OAAO,CAACH,KAAK;YAEjC,IAAIvG,WAAWyG,SAAS;gBACtBrF,aAAalB,KAAKwG,OAAO,CAACD,QAAQ;YACpC,OAAO;gBACLrF,aAAalB,KAAKwG,OAAO,CAACH,KAAK;YACjC;QACF;QAEA,IAAIlF,UAAU;YACZ,IAAI;gBACF,MAAMsF,WAAW,MAAMC,KAAK;gBAC5B,MAAMC,aAAa,MAAMF,SAASG,iBAAiB;gBACnD,MAAMhE,SAAS+D,aAAa,MAAMF,SAASI,aAAa,CAACF,cAAc,CAAC;gBACxEP,OAAO,MAAMK,SAASK,MAAM,CAACV,MAAM;oBAAE,GAAGxD,MAAM;oBAAEmE,QAAQ;gBAAa;YACvE,EAAE,OAAM;YACN,SAAS,GACX;QACF;QAEA,MAAMhH,UAAUmB,YAAYkF,MAAM;QAElC,IAAInF,KAAK;YACP,IAAI,CAAC0B,OAAO,CAACqE,MAAM,CAACC,IAAI,CAAC,CAAC,QAAQ,EAAE/F,YAAY;QAClD;IACF;AACF,EAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@payloadcms/drizzle",
3
- "version": "3.49.0-canary.4",
3
+ "version": "3.49.0-canary.6",
4
4
  "description": "A library of shared functions used by different payload database adapters",
5
5
  "homepage": "https://payloadcms.com",
6
6
  "repository": {
@@ -55,10 +55,10 @@
55
55
  "@types/pg": "8.10.2",
56
56
  "@types/to-snake-case": "1.0.0",
57
57
  "@payloadcms/eslint-config": "3.28.0",
58
- "payload": "3.49.0-canary.4"
58
+ "payload": "3.49.0-canary.6"
59
59
  },
60
60
  "peerDependencies": {
61
- "payload": "3.49.0-canary.4"
61
+ "payload": "3.49.0-canary.6"
62
62
  },
63
63
  "scripts": {
64
64
  "build": "pnpm build:swc && pnpm build:types",