@payloadcms/drizzle 3.81.0-internal.181753b → 3.81.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/create.d.ts.map +1 -1
  2. package/dist/create.js +2 -1
  3. package/dist/create.js.map +1 -1
  4. package/dist/deleteMany.d.ts.map +1 -1
  5. package/dist/deleteMany.js +2 -0
  6. package/dist/deleteMany.js.map +1 -1
  7. package/dist/deleteOne.d.ts.map +1 -1
  8. package/dist/deleteOne.js +2 -0
  9. package/dist/deleteOne.js.map +1 -1
  10. package/dist/deleteVersions.d.ts.map +1 -1
  11. package/dist/deleteVersions.js +2 -0
  12. package/dist/deleteVersions.js.map +1 -1
  13. package/dist/find/buildFindManyArgs.d.ts +3 -28
  14. package/dist/find/buildFindManyArgs.d.ts.map +1 -1
  15. package/dist/find/buildFindManyArgs.js +1 -4
  16. package/dist/find/buildFindManyArgs.js.map +1 -1
  17. package/dist/find/findMany.d.ts.map +1 -1
  18. package/dist/find/findMany.js +1 -61
  19. package/dist/find/findMany.js.map +1 -1
  20. package/dist/find/traverseFields.d.ts.map +1 -1
  21. package/dist/find/traverseFields.js +27 -53
  22. package/dist/find/traverseFields.js.map +1 -1
  23. package/dist/queries/getTableColumnFromPath.d.ts.map +1 -1
  24. package/dist/queries/getTableColumnFromPath.js +27 -5
  25. package/dist/queries/getTableColumnFromPath.js.map +1 -1
  26. package/dist/types.d.ts +18 -0
  27. package/dist/types.d.ts.map +1 -1
  28. package/dist/types.js.map +1 -1
  29. package/dist/updateJobs.d.ts.map +1 -1
  30. package/dist/updateJobs.js +2 -1
  31. package/dist/updateJobs.js.map +1 -1
  32. package/dist/updateMany.d.ts.map +1 -1
  33. package/dist/updateMany.js +2 -1
  34. package/dist/updateMany.js.map +1 -1
  35. package/dist/updateOne.d.ts.map +1 -1
  36. package/dist/updateOne.js +2 -1
  37. package/dist/updateOne.js.map +1 -1
  38. package/dist/upsertRow/index.d.ts.map +1 -1
  39. package/dist/upsertRow/index.js +2 -0
  40. package/dist/upsertRow/index.js.map +1 -1
  41. package/dist/utilities/getPrimaryDb.d.ts +6 -0
  42. package/dist/utilities/getPrimaryDb.d.ts.map +1 -0
  43. package/dist/utilities/getPrimaryDb.js +10 -0
  44. package/dist/utilities/getPrimaryDb.js.map +1 -0
  45. package/dist/utilities/getTransaction.d.ts +3 -0
  46. package/dist/utilities/getTransaction.d.ts.map +1 -1
  47. package/dist/utilities/getTransaction.js +7 -0
  48. package/dist/utilities/getTransaction.js.map +1 -1
  49. package/dist/utilities/readAfterWrite.d.ts +17 -0
  50. package/dist/utilities/readAfterWrite.d.ts.map +1 -0
  51. package/dist/utilities/readAfterWrite.js +21 -0
  52. package/dist/utilities/readAfterWrite.js.map +1 -0
  53. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/updateOne.ts"],"sourcesContent":["import type { LibSQLDatabase } from 'drizzle-orm/libsql'\nimport type { UpdateOne } from 'payload'\n\nimport toSnakeCase from 'to-snake-case'\n\nimport type { DrizzleAdapter } from './types.js'\n\nimport { buildQuery } from './queries/buildQuery.js'\nimport { selectDistinct } from './queries/selectDistinct.js'\nimport { upsertRow } from './upsertRow/index.js'\nimport { getTransaction } from './utilities/getTransaction.js'\n\nexport const updateOne: UpdateOne = async function updateOne(\n this: DrizzleAdapter,\n {\n id,\n collection: collectionSlug,\n data,\n joins: joinQuery,\n locale,\n options = { upsert: false },\n req,\n returning,\n select,\n where: whereArg,\n },\n) {\n const collection = this.payload.collections[collectionSlug].config\n const tableName = this.tableNameMap.get(toSnakeCase(collection.slug))\n let idToUpdate = id\n\n const db = await getTransaction(this, req)\n\n if (!idToUpdate) {\n const { joins, selectFields, where } = buildQuery({\n adapter: this,\n fields: collection.flattenedFields,\n locale,\n tableName,\n where: whereArg,\n })\n\n // selectDistinct will only return if there are joins\n const selectDistinctResult = await selectDistinct({\n adapter: this,\n db,\n joins,\n query: ({ query }) => query.limit(1),\n selectFields,\n tableName,\n where,\n })\n\n if (selectDistinctResult?.[0]?.id) {\n idToUpdate = selectDistinctResult?.[0]?.id\n // If id wasn't passed but `where` without any joins, retrieve it with findFirst\n } else if (whereArg && !joins.length) {\n const table = this.tables[tableName]\n\n const docsToUpdate = await (db as LibSQLDatabase)\n .select({\n id: table.id,\n })\n .from(table)\n .where(where)\n .limit(1)\n idToUpdate = docsToUpdate?.[0]?.id\n }\n }\n\n if (!idToUpdate && !options.upsert) {\n // TODO: In 4.0, if returning === false, we should differentiate between:\n // - No document found to update\n // - Document found, but returning === false\n return null\n }\n\n const result = await upsertRow({\n id: idToUpdate,\n adapter: this,\n collectionSlug,\n data,\n db,\n fields: collection.flattenedFields,\n ignoreResult: returning === false,\n joinQuery,\n operation: 'update',\n req,\n select,\n tableName,\n })\n\n if (returning === false) {\n return null\n }\n\n return result\n}\n"],"names":["toSnakeCase","buildQuery","selectDistinct","upsertRow","getTransaction","updateOne","id","collection","collectionSlug","data","joins","joinQuery","locale","options","upsert","req","returning","select","where","whereArg","payload","collections","config","tableName","tableNameMap","get","slug","idToUpdate","db","selectFields","adapter","fields","flattenedFields","selectDistinctResult","query","limit","length","table","tables","docsToUpdate","from","result","ignoreResult","operation"],"mappings":"AAGA,OAAOA,iBAAiB,gBAAe;AAIvC,SAASC,UAAU,QAAQ,0BAAyB;AACpD,SAASC,cAAc,QAAQ,8BAA6B;AAC5D,SAASC,SAAS,QAAQ,uBAAsB;AAChD,SAASC,cAAc,QAAQ,gCAA+B;AAE9D,OAAO,MAAMC,YAAuB,eAAeA,UAEjD,EACEC,EAAE,EACFC,YAAYC,cAAc,EAC1BC,IAAI,EACJC,OAAOC,SAAS,EAChBC,MAAM,EACNC,UAAU;IAAEC,QAAQ;AAAM,CAAC,EAC3BC,GAAG,EACHC,SAAS,EACTC,MAAM,EACNC,OAAOC,QAAQ,EAChB;IAED,MAAMZ,aAAa,IAAI,CAACa,OAAO,CAACC,WAAW,CAACb,eAAe,CAACc,MAAM;IACl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,OAAO;IACT;IAEA,OAAOyB;AACT,EAAC"}
1
+ {"version":3,"sources":["../src/updateOne.ts"],"sourcesContent":["import type { LibSQLDatabase } from 'drizzle-orm/libsql'\nimport type { UpdateOne } from 'payload'\n\nimport toSnakeCase from 'to-snake-case'\n\nimport type { DrizzleAdapter } from './types.js'\n\nimport { buildQuery } from './queries/buildQuery.js'\nimport { selectDistinct } from './queries/selectDistinct.js'\nimport { upsertRow } from './upsertRow/index.js'\nimport { getPrimaryDb } from './utilities/getPrimaryDb.js'\nimport { getTransaction } from './utilities/getTransaction.js'\n\nexport const updateOne: UpdateOne = async function updateOne(\n this: DrizzleAdapter,\n {\n id,\n collection: collectionSlug,\n data,\n joins: joinQuery,\n locale,\n options = { upsert: false },\n req,\n returning,\n select,\n where: whereArg,\n },\n) {\n const collection = this.payload.collections[collectionSlug].config\n const tableName = this.tableNameMap.get(toSnakeCase(collection.slug))\n let idToUpdate = id\n\n const db = getPrimaryDb(this, await getTransaction(this, req))\n\n if (!idToUpdate) {\n const { joins, selectFields, where } = buildQuery({\n adapter: this,\n fields: collection.flattenedFields,\n locale,\n tableName,\n where: whereArg,\n })\n\n // selectDistinct will only return if there are joins\n const selectDistinctResult = await selectDistinct({\n adapter: this,\n db,\n joins,\n query: ({ query }) => query.limit(1),\n selectFields,\n tableName,\n where,\n })\n\n if (selectDistinctResult?.[0]?.id) {\n idToUpdate = selectDistinctResult?.[0]?.id\n // If id wasn't passed but `where` without any joins, retrieve it with findFirst\n } else if (whereArg && !joins.length) {\n const table = this.tables[tableName]\n\n const docsToUpdate = await (db as LibSQLDatabase)\n .select({\n id: table.id,\n })\n .from(table)\n .where(where)\n .limit(1)\n idToUpdate = docsToUpdate?.[0]?.id\n }\n }\n\n if (!idToUpdate && !options.upsert) {\n // TODO: In 4.0, if returning === false, we should differentiate between:\n // - No document found to update\n // - Document found, but returning === false\n return null\n }\n\n const result = await upsertRow({\n id: idToUpdate,\n adapter: this,\n collectionSlug,\n data,\n db,\n fields: collection.flattenedFields,\n ignoreResult: returning === false,\n joinQuery,\n operation: 'update',\n req,\n select,\n tableName,\n })\n\n if (returning === false) {\n return null\n }\n\n return result\n}\n"],"names":["toSnakeCase","buildQuery","selectDistinct","upsertRow","getPrimaryDb","getTransaction","updateOne","id","collection","collectionSlug","data","joins","joinQuery","locale","options","upsert","req","returning","select","where","whereArg","payload","collections","config","tableName","tableNameMap","get","slug","idToUpdate","db","selectFields","adapter","fields","flattenedFields","selectDistinctResult","query","limit","length","table","tables","docsToUpdate","from","result","ignoreResult","operation"],"mappings":"AAGA,OAAOA,iBAAiB,gBAAe;AAIvC,SAASC,UAAU,QAAQ,0BAAyB;AACpD,SAASC,cAAc,QAAQ,8BAA6B;AAC5D,SAASC,SAAS,QAAQ,uBAAsB;AAChD,SAASC,YAAY,QAAQ,8BAA6B;AAC1D,SAASC,cAAc,QAAQ,gCAA+B;AAE9D,OAAO,MAAMC,YAAuB,eAAeA,UAEjD,EACEC,EAAE,EACFC,YAAYC,cAAc,EAC1BC,IAAI,EACJC,OAAOC,SAAS,EAChBC,MAAM,EACNC,UAAU;IAAEC,QAAQ;AAAM,CAAC,EAC3BC,GAAG,EACHC,SAAS,EACTC,MAAM,EACNC,OAAOC,QAAQ,EAChB;IAED,MAAMZ,aAAa,IAAI,CAACa,OAAO,CAACC,WAAW,CAACb,eAAe,CAACc,MAAM;IAClE,MAAMC,YAAY,IAAI,CAACC,YAAY,CAACC,GAAG,CAAC1B,YAAYQ,WAAWmB,IAAI;IACnE,IAAIC,aAAarB;IAEjB,MAAMsB,KAAKzB,aAAa,IAAI,EAAE,MAAMC,eAAe,IAAI,EAAEW;IAEzD,IAAI,CAACY,YAAY;QACf,MAAM,EAAEjB,KAAK,EAAEmB,YAAY,EAAEX,KAAK,EAAE,GAAGlB,WAAW;YAChD8B,SAAS,IAAI;YACbC,QAAQxB,WAAWyB,eAAe;YAClCpB;YACAW;YACAL,OAAOC;QACT;QAEA,qDAAqD;QACrD,MAAMc,uBAAuB,MAAMhC,eAAe;YAChD6B,SAAS,IAAI;YACbF;YACAlB;YACAwB,OAAO,CAAC,EAAEA,KAAK,EAAE,GAAKA,MAAMC,KAAK,CAAC;YAClCN;YACAN;YACAL;QACF;QAEA,IAAIe,sBAAsB,CAAC,EAAE,EAAE3B,IAAI;YACjCqB,aAAaM,sBAAsB,CAAC,EAAE,EAAE3B;QACxC,gFAAgF;QAClF,OAAO,IAAIa,YAAY,CAACT,MAAM0B,MAAM,EAAE;YACpC,MAAMC,QAAQ,IAAI,CAACC,MAAM,CAACf,UAAU;YAEpC,MAAMgB,eAAe,MAAM,AAACX,GACzBX,MAAM,CAAC;gBACNX,IAAI+B,MAAM/B,EAAE;YACd,GACCkC,IAAI,CAACH,OACLnB,KAAK,CAACA,OACNiB,KAAK,CAAC;YACTR,aAAaY,cAAc,CAAC,EAAE,EAAEjC;QAClC;IACF;IAEA,IAAI,CAACqB,cAAc,CAACd,QAAQC,MAAM,EAAE;QAClC,yEAAyE;QACzE,gCAAgC;QAChC,4CAA4C;QAC5C,OAAO;IACT;IAEA,MAAM2B,SAAS,MAAMvC,UAAU;QAC7BI,IAAIqB;QACJG,SAAS,IAAI;QACbtB;QACAC;QACAmB;QACAG,QAAQxB,WAAWyB,eAAe;QAClCU,cAAc1B,cAAc;QAC5BL;QACAgC,WAAW;QACX5B;QACAE;QACAM;IACF;IAEA,IAAIP,cAAc,OAAO;QACvB,OAAO;IACT;IAEA,OAAOyB;AACT,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/upsertRow/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAKzC,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAA;AAoBtC;;;;;;GAMG;AACH,eAAO,MAAM,SAAS,GAAU,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,UAAU,+KAqB3E,IAAI,KAAG,OAAO,CAAC,CAAC,CA8sBlB,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;AAKzC,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAA;AAqBtC;;;;;;GAMG;AACH,eAAO,MAAM,SAAS,GAAU,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,UAAU,+KAqB3E,IAAI,KAAG,OAAO,CAAC,CAAC,CAgtBlB,CAAA"}
@@ -2,6 +2,7 @@ import { and, desc, eq, isNull, or } from 'drizzle-orm';
2
2
  import { buildFindManyArgs } from '../find/buildFindManyArgs.js';
3
3
  import { transform } from '../transform/read/index.js';
4
4
  import { transformForWrite } from '../transform/write/index.js';
5
+ import { markWrite } from '../utilities/readAfterWrite.js';
5
6
  import { deleteExistingArrayRows } from './deleteExistingArrayRows.js';
6
7
  import { deleteExistingRowsByPath } from './deleteExistingRowsByPath.js';
7
8
  import { handleUpsertError } from './handleUpsertError.js';
@@ -20,6 +21,7 @@ customID, joinQuery: _joinQuery, operation, path = '', req, select, tableName, u
20
21
  if (operation === 'create' && !data.createdAt) {
21
22
  data.createdAt = new Date().toISOString();
22
23
  }
24
+ markWrite(adapter);
23
25
  let insertedRow = {
24
26
  id
25
27
  };
@@ -1 +1 @@
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 { and, desc, eq, isNull, or } from 'drizzle-orm'\n\nimport type { BlockRowToInsert } from '../transform/write/types.js'\nimport type { Args } from './types.js'\n\ntype RelationshipRow = {\n [key: string]: number | string | undefined // For relationship ID columns like categoriesID, moviesID, etc.\n id?: number | string\n locale?: string\n order: number\n parent: number | string // Drizzle table uses 'parent' key\n path: string\n}\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 { handleUpsertError } from './handleUpsertError.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 collectionSlug,\n data,\n db,\n fields,\n globalSlug,\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 customID,\n joinQuery: _joinQuery,\n operation,\n path = '',\n req,\n select,\n tableName,\n upsertTarget,\n where,\n}: Args): Promise<T> => {\n if (operation === 'create' && !data.createdAt) {\n data.createdAt = new Date().toISOString()\n }\n\n let insertedRow: Record<string, unknown> = { id }\n if (id && shouldUseOptimizedUpsertRow({ data, fields })) {\n try {\n const transformedForWrite = transformForWrite({\n adapter,\n data,\n enableAtomicWrites: true,\n fields,\n tableName,\n })\n const { row } = transformedForWrite\n const { arraysToPush } = transformedForWrite\n\n const drizzle = db as LibSQLDatabase\n\n // First, handle $push arrays\n\n if (arraysToPush && Object.keys(arraysToPush)?.length) {\n await insertArrays({\n adapter,\n arrays: [arraysToPush],\n db,\n parentRows: [insertedRow],\n uuidMap: {},\n })\n }\n\n // If row.updatedAt is not set, delete it to avoid triggering hasDataToUpdate. `updatedAt` may be explicitly set to null to\n // disable triggering hasDataToUpdate.\n if (typeof row.updatedAt === 'undefined' || row.updatedAt === null) {\n delete row.updatedAt\n }\n\n const hasDataToUpdate = row && Object.keys(row)?.length\n\n // Then, handle regular row update\n if (ignoreResult) {\n if (hasDataToUpdate) {\n // Only update row if there is something to update.\n // Example: if the data only consists of a single $push, calling insertArrays is enough - we don't need to update the row.\n await drizzle\n .update(adapter.tables[tableName])\n .set(row)\n .where(eq(adapter.tables[tableName].id, id))\n }\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 (!hasDataToUpdate) {\n // Nothing to update => just fetch current row and return\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\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 } catch (error) {\n handleUpsertError({ id, adapter, collectionSlug, error, globalSlug, req, 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 if (customID) {\n rowToInsert.row.id = customID\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 // Check if we only have relationship operations and no main row data to update\n // Exclude timestamp-only updates when we only have relationship operations\n const rowKeys = Object.keys(rowToInsert.row)\n const hasMainRowData =\n rowKeys.length > 0 && !rowKeys.every((key) => key === 'updatedAt' || key === 'createdAt')\n\n if (hasMainRowData) {\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 // No main row data to update, just use the existing ID\n insertedRow = { id }\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 // Filter out specific item deletions (those with itemToRemove) from general path deletions\n const generalRelationshipDeletes = rowToInsert.relationshipsToDelete.filter(\n (rel) => !('itemToRemove' in rel),\n )\n\n await deleteExistingRowsByPath({\n adapter,\n db,\n localeColumnName: 'locale',\n parentColumnName: 'parent',\n parentID: insertedRow.id,\n pathColumnName: 'path',\n rows: [...relationsToInsert, ...generalRelationshipDeletes],\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 // HANDLE RELATIONSHIP $push OPERATIONS\n // //////////////////////////////////\n\n if (rowToInsert.relationshipsToAppend.length > 0) {\n // Prepare all relationships for batch insert (order will be set after max query)\n const relationshipsToInsert = rowToInsert.relationshipsToAppend.map((rel) => {\n const parentId = id || insertedRow.id\n const row: Record<string, unknown> = {\n parent: parentId as number | string, // Use 'parent' key for Drizzle table\n path: rel.path,\n }\n\n // Only add locale if this relationship table has a locale column\n const relationshipTable = adapter.rawTables[relationshipsTableName]\n if (rel.locale && relationshipTable && relationshipTable.columns.locale) {\n row.locale = rel.locale\n }\n\n if (rel.relationTo) {\n // Use camelCase key for Drizzle table (e.g., categoriesID not categories_id)\n row[`${rel.relationTo}ID`] = rel.value\n }\n\n return row\n })\n\n if (relationshipsToInsert.length > 0) {\n // Check for potential duplicates\n const relationshipTable = adapter.tables[relationshipsTableName]\n\n if (relationshipTable) {\n // Build conditions only if we have relationships to check\n if (relationshipsToInsert.length === 0) {\n return // No relationships to insert\n }\n\n const conditions = relationshipsToInsert.map((row: RelationshipRow) => {\n const parts = [\n eq(relationshipTable.parent, row.parent),\n eq(relationshipTable.path, row.path),\n ]\n\n // Add locale condition\n if (row.locale !== undefined && relationshipTable.locale) {\n parts.push(eq(relationshipTable.locale, row.locale))\n } else if (relationshipTable.locale) {\n parts.push(isNull(relationshipTable.locale))\n }\n\n // Add all relationship ID matches using schema fields\n for (const [key, value] of Object.entries(row)) {\n if (key.endsWith('ID') && value != null) {\n const column = relationshipTable[key]\n if (column && typeof column === 'object') {\n parts.push(eq(column, value))\n }\n }\n }\n\n return and(...parts)\n })\n\n // Get both existing relationships AND max order in a single query\n let existingRels: Record<string, unknown>[] = []\n let maxOrder = 0\n\n if (conditions.length > 0) {\n // Query for existing relationships\n existingRels = await (db as any)\n .select()\n .from(relationshipTable)\n .where(or(...conditions))\n }\n\n // Get max order for this parent across all paths in a single query\n const parentId = id || insertedRow.id\n const maxOrderResult = await (db as any)\n .select({ maxOrder: relationshipTable.order })\n .from(relationshipTable)\n .where(eq(relationshipTable.parent, parentId))\n .orderBy(desc(relationshipTable.order))\n .limit(1)\n\n if (maxOrderResult.length > 0 && maxOrderResult[0].maxOrder) {\n maxOrder = maxOrderResult[0].maxOrder\n }\n\n // Set order values for all relationships based on max order\n relationshipsToInsert.forEach((row, index) => {\n row.order = maxOrder + index + 1\n })\n\n // Filter out relationships that already exist\n const relationshipsToActuallyInsert = relationshipsToInsert.filter((newRow) => {\n return !existingRels.some((existingRow: Record<string, unknown>) => {\n // Check if this relationship already exists\n let matches = existingRow.parent === newRow.parent && existingRow.path === newRow.path\n\n if (newRow.locale !== undefined) {\n matches = matches && existingRow.locale === newRow.locale\n }\n\n // Check relationship value matches - convert to camelCase for comparison\n for (const key of Object.keys(newRow)) {\n if (key.endsWith('ID')) {\n // Now using camelCase keys\n matches = matches && existingRow[key] === newRow[key]\n }\n }\n\n return matches\n })\n })\n\n // Insert only non-duplicate relationships\n if (relationshipsToActuallyInsert.length > 0) {\n await adapter.insert({\n db,\n tableName: relationshipsTableName,\n values: relationshipsToActuallyInsert,\n })\n }\n }\n }\n }\n\n // //////////////////////////////////\n // HANDLE RELATIONSHIP $remove OPERATIONS\n // //////////////////////////////////\n\n if (rowToInsert.relationshipsToDelete.some((rel) => 'itemToRemove' in rel)) {\n const relationshipTable = adapter.tables[relationshipsTableName]\n\n if (relationshipTable) {\n for (const relToDelete of rowToInsert.relationshipsToDelete) {\n if ('itemToRemove' in relToDelete && relToDelete.itemToRemove) {\n const item = relToDelete.itemToRemove\n const parentId = (id || insertedRow.id) as number | string\n\n const conditions = [\n eq(relationshipTable.parent, parentId),\n eq(relationshipTable.path, relToDelete.path),\n ]\n\n // Add locale condition if this relationship table has a locale column\n if (adapter.rawTables[relationshipsTableName]?.columns.locale) {\n if (relToDelete.locale) {\n conditions.push(eq(relationshipTable.locale, relToDelete.locale))\n } else {\n conditions.push(isNull(relationshipTable.locale))\n }\n }\n\n // Handle polymorphic vs simple relationships\n if (typeof item === 'object' && 'relationTo' in item) {\n // Polymorphic relationship - convert to camelCase key\n const camelKey = `${item.relationTo}ID`\n if (relationshipTable[camelKey]) {\n conditions.push(eq(relationshipTable[camelKey], item.value))\n }\n } else if (relToDelete.relationTo) {\n // Simple relationship - convert to camelCase key\n const camelKey = `${relToDelete.relationTo}ID`\n if (relationshipTable[camelKey]) {\n conditions.push(eq(relationshipTable[camelKey], item))\n }\n }\n\n // Execute DELETE using Drizzle query builder\n await adapter.deleteWhere({\n db,\n tableName: relationshipsTableName,\n where: and(...conditions),\n })\n }\n }\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, rowToInsert.arraysToPush],\n db,\n parentRows: [insertedRow, 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: RelationshipRow) => {\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 } catch (error) {\n handleUpsertError({ id, adapter, collectionSlug, error, globalSlug, req, tableName })\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":["and","desc","eq","isNull","or","buildFindManyArgs","transform","transformForWrite","deleteExistingArrayRows","deleteExistingRowsByPath","handleUpsertError","insertArrays","shouldUseOptimizedUpsertRow","upsertRow","id","adapter","collectionSlug","data","db","fields","globalSlug","ignoreResult","customID","joinQuery","_joinQuery","operation","path","req","select","tableName","upsertTarget","where","createdAt","Date","toISOString","insertedRow","transformedForWrite","enableAtomicWrites","row","arraysToPush","drizzle","Object","keys","length","arrays","parentRows","uuidMap","updatedAt","hasDataToUpdate","update","tables","set","findManyArgs","depth","findManyKeysLength","hasOnlyColumns","columns","doc","query","findFirst","config","payload","selectedFields","column","enabled","entries","docs","returning","undefined","error","rowToInsert","target","rowKeys","hasMainRowData","every","key","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","generalRelationshipDeletes","relationshipsToDelete","filter","rel","localeColumnName","parentColumnName","parentID","pathColumnName","rows","relationshipsToAppend","relationshipsToInsert","map","parentId","relationshipTable","rawTables","relationTo","value","conditions","parts","endsWith","existingRels","maxOrder","from","maxOrderResult","order","orderBy","limit","index","relationshipsToActuallyInsert","newRow","some","existingRow","matches","relToDelete","itemToRemove","item","camelKey","textsTableName","textsToDelete","numbersTableName","numbersToDelete","insertedBlockRows","blocksToDelete","blockTable","arraysBlocksUUIDMap","blockRows","i","_uuid","blockLocaleIndexMap","blockLocaleRowsToInsert","reduce","acc","blockLocale","blockLocaleData","arrayTableName","tableRows","selectTable","result"],"mappings":"AAIA,SAASA,GAAG,EAAEC,IAAI,EAAEC,EAAE,EAAEC,MAAM,EAAEC,EAAE,QAAQ,cAAa;AAcvD,SAASC,iBAAiB,QAAQ,+BAA8B;AAChE,SAASC,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C"}
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 { and, desc, eq, isNull, or } from 'drizzle-orm'\n\nimport type { BlockRowToInsert } from '../transform/write/types.js'\nimport type { Args } from './types.js'\n\ntype RelationshipRow = {\n [key: string]: number | string | undefined // For relationship ID columns like categoriesID, moviesID, etc.\n id?: number | string\n locale?: string\n order: number\n parent: number | string // Drizzle table uses 'parent' key\n path: string\n}\n\nimport { buildFindManyArgs } from '../find/buildFindManyArgs.js'\nimport { transform } from '../transform/read/index.js'\nimport { transformForWrite } from '../transform/write/index.js'\nimport { markWrite } from '../utilities/readAfterWrite.js'\nimport { deleteExistingArrayRows } from './deleteExistingArrayRows.js'\nimport { deleteExistingRowsByPath } from './deleteExistingRowsByPath.js'\nimport { handleUpsertError } from './handleUpsertError.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 collectionSlug,\n data,\n db,\n fields,\n globalSlug,\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 customID,\n joinQuery: _joinQuery,\n operation,\n path = '',\n req,\n select,\n tableName,\n upsertTarget,\n where,\n}: Args): Promise<T> => {\n if (operation === 'create' && !data.createdAt) {\n data.createdAt = new Date().toISOString()\n }\n\n markWrite(adapter)\n\n let insertedRow: Record<string, unknown> = { id }\n if (id && shouldUseOptimizedUpsertRow({ data, fields })) {\n try {\n const transformedForWrite = transformForWrite({\n adapter,\n data,\n enableAtomicWrites: true,\n fields,\n tableName,\n })\n const { row } = transformedForWrite\n const { arraysToPush } = transformedForWrite\n\n const drizzle = db as LibSQLDatabase\n\n // First, handle $push arrays\n\n if (arraysToPush && Object.keys(arraysToPush)?.length) {\n await insertArrays({\n adapter,\n arrays: [arraysToPush],\n db,\n parentRows: [insertedRow],\n uuidMap: {},\n })\n }\n\n // If row.updatedAt is not set, delete it to avoid triggering hasDataToUpdate. `updatedAt` may be explicitly set to null to\n // disable triggering hasDataToUpdate.\n if (typeof row.updatedAt === 'undefined' || row.updatedAt === null) {\n delete row.updatedAt\n }\n\n const hasDataToUpdate = row && Object.keys(row)?.length\n\n // Then, handle regular row update\n if (ignoreResult) {\n if (hasDataToUpdate) {\n // Only update row if there is something to update.\n // Example: if the data only consists of a single $push, calling insertArrays is enough - we don't need to update the row.\n await drizzle\n .update(adapter.tables[tableName])\n .set(row)\n .where(eq(adapter.tables[tableName].id, id))\n }\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 (!hasDataToUpdate) {\n // Nothing to update => just fetch current row and return\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\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 } catch (error) {\n handleUpsertError({ id, adapter, collectionSlug, error, globalSlug, req, 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 if (customID) {\n rowToInsert.row.id = customID\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 // Check if we only have relationship operations and no main row data to update\n // Exclude timestamp-only updates when we only have relationship operations\n const rowKeys = Object.keys(rowToInsert.row)\n const hasMainRowData =\n rowKeys.length > 0 && !rowKeys.every((key) => key === 'updatedAt' || key === 'createdAt')\n\n if (hasMainRowData) {\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 // No main row data to update, just use the existing ID\n insertedRow = { id }\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 // Filter out specific item deletions (those with itemToRemove) from general path deletions\n const generalRelationshipDeletes = rowToInsert.relationshipsToDelete.filter(\n (rel) => !('itemToRemove' in rel),\n )\n\n await deleteExistingRowsByPath({\n adapter,\n db,\n localeColumnName: 'locale',\n parentColumnName: 'parent',\n parentID: insertedRow.id,\n pathColumnName: 'path',\n rows: [...relationsToInsert, ...generalRelationshipDeletes],\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 // HANDLE RELATIONSHIP $push OPERATIONS\n // //////////////////////////////////\n\n if (rowToInsert.relationshipsToAppend.length > 0) {\n // Prepare all relationships for batch insert (order will be set after max query)\n const relationshipsToInsert = rowToInsert.relationshipsToAppend.map((rel) => {\n const parentId = id || insertedRow.id\n const row: Record<string, unknown> = {\n parent: parentId as number | string, // Use 'parent' key for Drizzle table\n path: rel.path,\n }\n\n // Only add locale if this relationship table has a locale column\n const relationshipTable = adapter.rawTables[relationshipsTableName]\n if (rel.locale && relationshipTable && relationshipTable.columns.locale) {\n row.locale = rel.locale\n }\n\n if (rel.relationTo) {\n // Use camelCase key for Drizzle table (e.g., categoriesID not categories_id)\n row[`${rel.relationTo}ID`] = rel.value\n }\n\n return row\n })\n\n if (relationshipsToInsert.length > 0) {\n // Check for potential duplicates\n const relationshipTable = adapter.tables[relationshipsTableName]\n\n if (relationshipTable) {\n // Build conditions only if we have relationships to check\n if (relationshipsToInsert.length === 0) {\n return // No relationships to insert\n }\n\n const conditions = relationshipsToInsert.map((row: RelationshipRow) => {\n const parts = [\n eq(relationshipTable.parent, row.parent),\n eq(relationshipTable.path, row.path),\n ]\n\n // Add locale condition\n if (row.locale !== undefined && relationshipTable.locale) {\n parts.push(eq(relationshipTable.locale, row.locale))\n } else if (relationshipTable.locale) {\n parts.push(isNull(relationshipTable.locale))\n }\n\n // Add all relationship ID matches using schema fields\n for (const [key, value] of Object.entries(row)) {\n if (key.endsWith('ID') && value != null) {\n const column = relationshipTable[key]\n if (column && typeof column === 'object') {\n parts.push(eq(column, value))\n }\n }\n }\n\n return and(...parts)\n })\n\n // Get both existing relationships AND max order in a single query\n let existingRels: Record<string, unknown>[] = []\n let maxOrder = 0\n\n if (conditions.length > 0) {\n // Query for existing relationships\n existingRels = await (db as any)\n .select()\n .from(relationshipTable)\n .where(or(...conditions))\n }\n\n // Get max order for this parent across all paths in a single query\n const parentId = id || insertedRow.id\n const maxOrderResult = await (db as any)\n .select({ maxOrder: relationshipTable.order })\n .from(relationshipTable)\n .where(eq(relationshipTable.parent, parentId))\n .orderBy(desc(relationshipTable.order))\n .limit(1)\n\n if (maxOrderResult.length > 0 && maxOrderResult[0].maxOrder) {\n maxOrder = maxOrderResult[0].maxOrder\n }\n\n // Set order values for all relationships based on max order\n relationshipsToInsert.forEach((row, index) => {\n row.order = maxOrder + index + 1\n })\n\n // Filter out relationships that already exist\n const relationshipsToActuallyInsert = relationshipsToInsert.filter((newRow) => {\n return !existingRels.some((existingRow: Record<string, unknown>) => {\n // Check if this relationship already exists\n let matches = existingRow.parent === newRow.parent && existingRow.path === newRow.path\n\n if (newRow.locale !== undefined) {\n matches = matches && existingRow.locale === newRow.locale\n }\n\n // Check relationship value matches - convert to camelCase for comparison\n for (const key of Object.keys(newRow)) {\n if (key.endsWith('ID')) {\n // Now using camelCase keys\n matches = matches && existingRow[key] === newRow[key]\n }\n }\n\n return matches\n })\n })\n\n // Insert only non-duplicate relationships\n if (relationshipsToActuallyInsert.length > 0) {\n await adapter.insert({\n db,\n tableName: relationshipsTableName,\n values: relationshipsToActuallyInsert,\n })\n }\n }\n }\n }\n\n // //////////////////////////////////\n // HANDLE RELATIONSHIP $remove OPERATIONS\n // //////////////////////////////////\n\n if (rowToInsert.relationshipsToDelete.some((rel) => 'itemToRemove' in rel)) {\n const relationshipTable = adapter.tables[relationshipsTableName]\n\n if (relationshipTable) {\n for (const relToDelete of rowToInsert.relationshipsToDelete) {\n if ('itemToRemove' in relToDelete && relToDelete.itemToRemove) {\n const item = relToDelete.itemToRemove\n const parentId = (id || insertedRow.id) as number | string\n\n const conditions = [\n eq(relationshipTable.parent, parentId),\n eq(relationshipTable.path, relToDelete.path),\n ]\n\n // Add locale condition if this relationship table has a locale column\n if (adapter.rawTables[relationshipsTableName]?.columns.locale) {\n if (relToDelete.locale) {\n conditions.push(eq(relationshipTable.locale, relToDelete.locale))\n } else {\n conditions.push(isNull(relationshipTable.locale))\n }\n }\n\n // Handle polymorphic vs simple relationships\n if (typeof item === 'object' && 'relationTo' in item) {\n // Polymorphic relationship - convert to camelCase key\n const camelKey = `${item.relationTo}ID`\n if (relationshipTable[camelKey]) {\n conditions.push(eq(relationshipTable[camelKey], item.value))\n }\n } else if (relToDelete.relationTo) {\n // Simple relationship - convert to camelCase key\n const camelKey = `${relToDelete.relationTo}ID`\n if (relationshipTable[camelKey]) {\n conditions.push(eq(relationshipTable[camelKey], item))\n }\n }\n\n // Execute DELETE using Drizzle query builder\n await adapter.deleteWhere({\n db,\n tableName: relationshipsTableName,\n where: and(...conditions),\n })\n }\n }\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, rowToInsert.arraysToPush],\n db,\n parentRows: [insertedRow, 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: RelationshipRow) => {\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 } catch (error) {\n handleUpsertError({ id, adapter, collectionSlug, error, globalSlug, req, tableName })\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":["and","desc","eq","isNull","or","buildFindManyArgs","transform","transformForWrite","markWrite","deleteExistingArrayRows","deleteExistingRowsByPath","handleUpsertError","insertArrays","shouldUseOptimizedUpsertRow","upsertRow","id","adapter","collectionSlug","data","db","fields","globalSlug","ignoreResult","customID","joinQuery","_joinQuery","operation","path","req","select","tableName","upsertTarget","where","createdAt","Date","toISOString","insertedRow","transformedForWrite","enableAtomicWrites","row","arraysToPush","drizzle","Object","keys","length","arrays","parentRows","uuidMap","updatedAt","hasDataToUpdate","update","tables","set","findManyArgs","depth","findManyKeysLength","hasOnlyColumns","columns","doc","query","findFirst","config","payload","selectedFields","column","enabled","entries","docs","returning","undefined","error","rowToInsert","target","rowKeys","hasMainRowData","every","key","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","generalRelationshipDeletes","relationshipsToDelete","filter","rel","localeColumnName","parentColumnName","parentID","pathColumnName","rows","relationshipsToAppend","relationshipsToInsert","map","parentId","relationshipTable","rawTables","relationTo","value","conditions","parts","endsWith","existingRels","maxOrder","from","maxOrderResult","order","orderBy","limit","index","relationshipsToActuallyInsert","newRow","some","existingRow","matches","relToDelete","itemToRemove","item","camelKey","textsTableName","textsToDelete","numbersTableName","numbersToDelete","insertedBlockRows","blocksToDelete","blockTable","arraysBlocksUUIDMap","blockRows","i","_uuid","blockLocaleIndexMap","blockLocaleRowsToInsert","reduce","acc","blockLocale","blockLocaleData","arrayTableName","tableRows","selectTable","result"],"mappings":"AAIA,SAASA,GAAG,EAAEC,IAAI,EAAEC,EAAE,EAAEC,MAAM,EAAEC,EAAE,QAAQ,cAAa;AAcvD,SAASC,iBAAiB,QAAQ,+BAA8B;AAChE,SAASC,SAAS,QAAQ,6BAA4B;AACtD,SAASC,iBAAiB,QAAQ,8BAA6B;AAC/D,SAASC,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,wBAAwB,QAAQ,gCAA+B;AACxE,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,2BAA2B,QAAQ,mCAAkC;AAE9E;;;;;;CAMC,GACD,OAAO,MAAMC,YAAY,OAAuD,EAC9EC,EAAE,EACFC,OAAO,EACPC,cAAc,EACdC,IAAI,EACJC,EAAE,EACFC,MAAM,EACNC,UAAU,EACVC,YAAY,EACZ,QAAQ;AACR,4GAA4G;AAC5G,8EAA8E;AAC9EC,QAAQ,EACRC,WAAWC,UAAU,EACrBC,SAAS,EACTC,OAAO,EAAE,EACTC,GAAG,EACHC,MAAM,EACNC,SAAS,EACTC,YAAY,EACZC,KAAK,EACA;IACL,IAAIN,cAAc,YAAY,CAACR,KAAKe,SAAS,EAAE;QAC7Cf,KAAKe,SAAS,GAAG,IAAIC,OAAOC,WAAW;IACzC;IAEA3B,UAAUQ;IAEV,IAAIoB,cAAuC;QAAErB;IAAG;IAChD,IAAIA,MAAMF,4BAA4B;QAAEK;QAAME;IAAO,IAAI;QACvD,IAAI;YACF,MAAMiB,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,eAAehD,kBAAkB;QACrCW;QACAsC,OAAO;QACPlC;QACAI,WAAW;QACXK;QACAC;IACF;IAEAuB,aAAarB,KAAK,GAAG9B,GAAGc,QAAQmC,MAAM,CAACrB,UAAU,CAACf,EAAE,EAAEqB,YAAYrB,EAAE;IAEpE,MAAM2C,MAAM,MAAMvC,GAAGwC,KAAK,CAAC7B,UAAU,CAAC8B,SAAS,CAACP;IAEhD,qCAAqC;IACrC,iBAAiB;IACjB,qCAAqC;IAErC,MAAMqH,SAASpK,UAAa;QAC1BU;QACA6C,QAAQ7C,QAAQ8C,OAAO,CAACD,MAAM;QAC9B3C,MAAMwC;QACNtC;QACAI,WAAW;QACXM;IACF;IAEA,OAAO4I;AACT,EAAC"}
@@ -0,0 +1,6 @@
1
+ import type { DrizzleAdapter, DrizzleTransaction } from '../types.js';
2
+ /**
3
+ * Returns the correct database instance for reads that are part of a write operation.
4
+ */
5
+ export declare const getPrimaryDb: (adapter: DrizzleAdapter, db: DrizzleAdapter["drizzle"] | DrizzleTransaction) => import("../types.js").PostgresDB | DrizzleTransaction | import("drizzle-orm/libsql").LibSQLDatabase<Record<string, never>>;
6
+ //# sourceMappingURL=getPrimaryDb.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getPrimaryDb.d.ts","sourceRoot":"","sources":["../../src/utilities/getPrimaryDb.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAA;AAErE;;GAEG;AACH,eAAO,MAAM,YAAY,YACd,cAAc,MACnB,cAAc,CAAC,SAAS,CAAC,GAAG,kBAAkB,+HAMnD,CAAA"}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Returns the correct database instance for reads that are part of a write operation.
3
+ */ export const getPrimaryDb = (adapter, db)=>{
4
+ if (adapter.primaryDrizzle && db === adapter.drizzle) {
5
+ return adapter.primaryDrizzle;
6
+ }
7
+ return db;
8
+ };
9
+
10
+ //# sourceMappingURL=getPrimaryDb.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/utilities/getPrimaryDb.ts"],"sourcesContent":["import type { DrizzleAdapter, DrizzleTransaction } from '../types.js'\n\n/**\n * Returns the correct database instance for reads that are part of a write operation.\n */\nexport const getPrimaryDb = (\n adapter: DrizzleAdapter,\n db: DrizzleAdapter['drizzle'] | DrizzleTransaction,\n) => {\n if (adapter.primaryDrizzle && db === adapter.drizzle) {\n return adapter.primaryDrizzle\n }\n return db\n}\n"],"names":["getPrimaryDb","adapter","db","primaryDrizzle","drizzle"],"mappings":"AAEA;;CAEC,GACD,OAAO,MAAMA,eAAe,CAC1BC,SACAC;IAEA,IAAID,QAAQE,cAAc,IAAID,OAAOD,QAAQG,OAAO,EAAE;QACpD,OAAOH,QAAQE,cAAc;IAC/B;IACA,OAAOD;AACT,EAAC"}
@@ -5,6 +5,9 @@ import type { DrizzleAdapter } from '../types.js';
5
5
  *
6
6
  * If a transaction session doesn't exist (e.g., it was already committed/rolled back),
7
7
  * falls back to the default adapter.drizzle instance to prevent errors.
8
+ *
9
+ * When read replicas are configured and a write happened recently, returns the
10
+ * unwrapped primary to avoid replication-lag stale reads.
8
11
  */
9
12
  export declare const getTransaction: <T extends DrizzleAdapter = DrizzleAdapter>(adapter: T, req?: Partial<PayloadRequest>) => Promise<T["drizzle"]>;
10
13
  //# sourceMappingURL=getTransaction.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"getTransaction.d.ts","sourceRoot":"","sources":["../../src/utilities/getTransaction.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAE7C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAEjD;;;;;GAKG;AACH,eAAO,MAAM,cAAc,GAAU,CAAC,SAAS,cAAc,4BAClD,CAAC,QACJ,OAAO,CAAC,cAAc,CAAC,KAC5B,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAMtB,CAAA"}
1
+ {"version":3,"file":"getTransaction.d.ts","sourceRoot":"","sources":["../../src/utilities/getTransaction.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAE7C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAIjD;;;;;;;;GAQG;AACH,eAAO,MAAM,cAAc,GAAU,CAAC,SAAS,cAAc,4BAClD,CAAC,QACJ,OAAO,CAAC,cAAc,CAAC,KAC5B,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAStB,CAAA"}
@@ -1,10 +1,17 @@
1
+ import { shouldReadFromPrimary } from './readAfterWrite.js';
1
2
  /**
2
3
  * Returns current db transaction instance from req or adapter.drizzle itself
3
4
  *
4
5
  * If a transaction session doesn't exist (e.g., it was already committed/rolled back),
5
6
  * falls back to the default adapter.drizzle instance to prevent errors.
7
+ *
8
+ * When read replicas are configured and a write happened recently, returns the
9
+ * unwrapped primary to avoid replication-lag stale reads.
6
10
  */ export const getTransaction = async (adapter, req)=>{
7
11
  if (!req?.transactionID) {
12
+ if (shouldReadFromPrimary(adapter)) {
13
+ return adapter.primaryDrizzle;
14
+ }
8
15
  return adapter.drizzle;
9
16
  }
10
17
  return adapter.sessions[await req.transactionID]?.db || adapter.drizzle;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utilities/getTransaction.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport type { DrizzleAdapter } from '../types.js'\n\n/**\n * Returns current db transaction instance from req or adapter.drizzle itself\n *\n * If a transaction session doesn't exist (e.g., it was already committed/rolled back),\n * falls back to the default adapter.drizzle instance to prevent errors.\n */\nexport const getTransaction = async <T extends DrizzleAdapter = DrizzleAdapter>(\n adapter: T,\n req?: Partial<PayloadRequest>,\n): Promise<T['drizzle']> => {\n if (!req?.transactionID) {\n return adapter.drizzle\n }\n\n return (adapter.sessions[await req.transactionID]?.db as T['drizzle']) || adapter.drizzle\n}\n"],"names":["getTransaction","adapter","req","transactionID","drizzle","sessions","db"],"mappings":"AAIA;;;;;CAKC,GACD,OAAO,MAAMA,iBAAiB,OAC5BC,SACAC;IAEA,IAAI,CAACA,KAAKC,eAAe;QACvB,OAAOF,QAAQG,OAAO;IACxB;IAEA,OAAO,AAACH,QAAQI,QAAQ,CAAC,MAAMH,IAAIC,aAAa,CAAC,EAAEG,MAAuBL,QAAQG,OAAO;AAC3F,EAAC"}
1
+ {"version":3,"sources":["../../src/utilities/getTransaction.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport type { DrizzleAdapter } from '../types.js'\n\nimport { shouldReadFromPrimary } from './readAfterWrite.js'\n\n/**\n * Returns current db transaction instance from req or adapter.drizzle itself\n *\n * If a transaction session doesn't exist (e.g., it was already committed/rolled back),\n * falls back to the default adapter.drizzle instance to prevent errors.\n *\n * When read replicas are configured and a write happened recently, returns the\n * unwrapped primary to avoid replication-lag stale reads.\n */\nexport const getTransaction = async <T extends DrizzleAdapter = DrizzleAdapter>(\n adapter: T,\n req?: Partial<PayloadRequest>,\n): Promise<T['drizzle']> => {\n if (!req?.transactionID) {\n if (shouldReadFromPrimary(adapter)) {\n return adapter.primaryDrizzle as T['drizzle']\n }\n return adapter.drizzle\n }\n\n return (adapter.sessions[await req.transactionID]?.db as T['drizzle']) || adapter.drizzle\n}\n"],"names":["shouldReadFromPrimary","getTransaction","adapter","req","transactionID","primaryDrizzle","drizzle","sessions","db"],"mappings":"AAIA,SAASA,qBAAqB,QAAQ,sBAAqB;AAE3D;;;;;;;;CAQC,GACD,OAAO,MAAMC,iBAAiB,OAC5BC,SACAC;IAEA,IAAI,CAACA,KAAKC,eAAe;QACvB,IAAIJ,sBAAsBE,UAAU;YAClC,OAAOA,QAAQG,cAAc;QAC/B;QACA,OAAOH,QAAQI,OAAO;IACxB;IAEA,OAAO,AAACJ,QAAQK,QAAQ,CAAC,MAAMJ,IAAIC,aAAa,CAAC,EAAEI,MAAuBN,QAAQI,OAAO;AAC3F,EAAC"}
@@ -0,0 +1,17 @@
1
+ import type { DrizzleAdapter } from '../types.js';
2
+ /**
3
+ * Tracks the last write timestamp on the adapter so that reads within a
4
+ * configurable window after a write are routed to the primary instead of a
5
+ * read replica.
6
+ *
7
+ * This avoids stale-read issues caused by replication lag when application
8
+ * code writes then immediately reads (e.g. create → findByID).
9
+ */
10
+ /** Call after any successful write to mark the adapter. */
11
+ export declare function markWrite(adapter: DrizzleAdapter): void;
12
+ /**
13
+ * Returns true when a recent write happened and reads should be routed to the
14
+ * primary to guarantee read-after-write consistency.
15
+ */
16
+ export declare function shouldReadFromPrimary(adapter: DrizzleAdapter): boolean;
17
+ //# sourceMappingURL=readAfterWrite.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"readAfterWrite.d.ts","sourceRoot":"","sources":["../../src/utilities/readAfterWrite.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAEjD;;;;;;;GAOG;AAEH,2DAA2D;AAC3D,wBAAgB,SAAS,CAAC,OAAO,EAAE,cAAc,GAAG,IAAI,CAEvD;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAKtE"}
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Tracks the last write timestamp on the adapter so that reads within a
3
+ * configurable window after a write are routed to the primary instead of a
4
+ * read replica.
5
+ *
6
+ * This avoids stale-read issues caused by replication lag when application
7
+ * code writes then immediately reads (e.g. create → findByID).
8
+ */ /** Call after any successful write to mark the adapter. */ export function markWrite(adapter) {
9
+ adapter.lastWriteTimestamp = Date.now();
10
+ }
11
+ /**
12
+ * Returns true when a recent write happened and reads should be routed to the
13
+ * primary to guarantee read-after-write consistency.
14
+ */ export function shouldReadFromPrimary(adapter) {
15
+ if (!adapter.primaryDrizzle || !adapter.lastWriteTimestamp) {
16
+ return false;
17
+ }
18
+ return Date.now() - adapter.lastWriteTimestamp < adapter.readReplicasAfterWriteInterval;
19
+ }
20
+
21
+ //# sourceMappingURL=readAfterWrite.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/utilities/readAfterWrite.ts"],"sourcesContent":["import type { DrizzleAdapter } from '../types.js'\n\n/**\n * Tracks the last write timestamp on the adapter so that reads within a\n * configurable window after a write are routed to the primary instead of a\n * read replica.\n *\n * This avoids stale-read issues caused by replication lag when application\n * code writes then immediately reads (e.g. create → findByID).\n */\n\n/** Call after any successful write to mark the adapter. */\nexport function markWrite(adapter: DrizzleAdapter): void {\n adapter.lastWriteTimestamp = Date.now()\n}\n\n/**\n * Returns true when a recent write happened and reads should be routed to the\n * primary to guarantee read-after-write consistency.\n */\nexport function shouldReadFromPrimary(adapter: DrizzleAdapter): boolean {\n if (!adapter.primaryDrizzle || !adapter.lastWriteTimestamp) {\n return false\n }\n return Date.now() - adapter.lastWriteTimestamp < adapter.readReplicasAfterWriteInterval\n}\n"],"names":["markWrite","adapter","lastWriteTimestamp","Date","now","shouldReadFromPrimary","primaryDrizzle","readReplicasAfterWriteInterval"],"mappings":"AAEA;;;;;;;CAOC,GAED,yDAAyD,GACzD,OAAO,SAASA,UAAUC,OAAuB;IAC/CA,QAAQC,kBAAkB,GAAGC,KAAKC,GAAG;AACvC;AAEA;;;CAGC,GACD,OAAO,SAASC,sBAAsBJ,OAAuB;IAC3D,IAAI,CAACA,QAAQK,cAAc,IAAI,CAACL,QAAQC,kBAAkB,EAAE;QAC1D,OAAO;IACT;IACA,OAAOC,KAAKC,GAAG,KAAKH,QAAQC,kBAAkB,GAAGD,QAAQM,8BAA8B;AACzF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@payloadcms/drizzle",
3
- "version": "3.81.0-internal.181753b",
3
+ "version": "3.81.0",
4
4
  "description": "A library of shared functions used by different payload database adapters",
5
5
  "homepage": "https://payloadcms.com",
6
6
  "repository": {
@@ -60,10 +60,10 @@
60
60
  "@types/pg": "8.10.2",
61
61
  "@types/to-snake-case": "1.0.0",
62
62
  "@payloadcms/eslint-config": "3.28.0",
63
- "payload": "3.81.0-internal.181753b"
63
+ "payload": "3.81.0"
64
64
  },
65
65
  "peerDependencies": {
66
- "payload": "3.81.0-internal.181753b"
66
+ "payload": "3.81.0"
67
67
  },
68
68
  "scripts": {
69
69
  "build": "pnpm build:swc && pnpm build:types",