@payloadcms/db-postgres 3.0.0-beta.9 → 3.0.0-canary.220bb7c
Sign up to get free protection for your applications and to get access to all the features.
- package/dist/connect.d.ts.map +1 -1
- package/dist/connect.js +12 -7
- package/dist/connect.js.map +1 -1
- package/dist/count.d.ts +3 -0
- package/dist/count.d.ts.map +1 -0
- package/dist/count.js +41 -0
- package/dist/count.js.map +1 -0
- package/dist/create.d.ts.map +1 -1
- package/dist/create.js +3 -5
- package/dist/create.js.map +1 -1
- package/dist/createGlobal.d.ts.map +1 -1
- package/dist/createGlobal.js +3 -5
- package/dist/createGlobal.js.map +1 -1
- package/dist/createGlobalVersion.d.ts +1 -1
- package/dist/createGlobalVersion.d.ts.map +1 -1
- package/dist/createGlobalVersion.js +2 -6
- package/dist/createGlobalVersion.js.map +1 -1
- package/dist/createMigration.d.ts.map +1 -1
- package/dist/createMigration.js +58 -37
- package/dist/createMigration.js.map +1 -1
- package/dist/createVersion.d.ts.map +1 -1
- package/dist/createVersion.js +10 -18
- package/dist/createVersion.js.map +1 -1
- package/dist/deleteMany.d.ts.map +1 -1
- package/dist/deleteMany.js +2 -5
- package/dist/deleteMany.js.map +1 -1
- package/dist/deleteOne.d.ts.map +1 -1
- package/dist/deleteOne.js +4 -7
- package/dist/deleteOne.js.map +1 -1
- package/dist/deleteVersions.d.ts.map +1 -1
- package/dist/deleteVersions.js +2 -6
- package/dist/deleteVersions.js.map +1 -1
- package/dist/destroy.d.ts.map +1 -1
- package/dist/destroy.js +11 -7
- package/dist/destroy.js.map +1 -1
- package/dist/exports/migration-utils.d.ts +2 -0
- package/dist/exports/migration-utils.d.ts.map +1 -0
- package/dist/exports/migration-utils.js +3 -0
- package/dist/exports/migration-utils.js.map +1 -0
- package/dist/find/buildFindManyArgs.d.ts +5 -1
- package/dist/find/buildFindManyArgs.d.ts.map +1 -1
- package/dist/find/buildFindManyArgs.js +4 -3
- package/dist/find/buildFindManyArgs.js.map +1 -1
- package/dist/find/findMany.d.ts.map +1 -1
- package/dist/find/findMany.js +4 -15
- package/dist/find/findMany.js.map +1 -1
- package/dist/find/traverseFields.d.ts +3 -2
- package/dist/find/traverseFields.d.ts.map +1 -1
- package/dist/find/traverseFields.js +26 -24
- package/dist/find/traverseFields.js.map +1 -1
- package/dist/find.d.ts.map +1 -1
- package/dist/find.js +2 -5
- package/dist/find.js.map +1 -1
- package/dist/findGlobal.d.ts.map +1 -1
- package/dist/findGlobal.js +2 -5
- package/dist/findGlobal.js.map +1 -1
- package/dist/findGlobalVersions.d.ts.map +1 -1
- package/dist/findGlobalVersions.js +2 -6
- package/dist/findGlobalVersions.js.map +1 -1
- package/dist/findOne.d.ts.map +1 -1
- package/dist/findOne.js +2 -5
- package/dist/findOne.js.map +1 -1
- package/dist/findVersions.d.ts.map +1 -1
- package/dist/findVersions.js +2 -6
- package/dist/findVersions.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +17 -8
- package/dist/index.js.map +1 -1
- package/dist/init.d.ts.map +1 -1
- package/dist/init.js +19 -22
- package/dist/init.js.map +1 -1
- package/dist/migrate.js.map +1 -1
- package/dist/migrateDown.js.map +1 -1
- package/dist/migrateFresh.js.map +1 -1
- package/dist/migrateRefresh.js.map +1 -1
- package/dist/migrateReset.js.map +1 -1
- package/dist/predefinedMigrations/relationships-v2-v3.d.ts +4 -0
- package/dist/predefinedMigrations/relationships-v2-v3.d.ts.map +1 -0
- package/dist/predefinedMigrations/relationships-v2-v3.js.map +1 -0
- package/dist/predefinedMigrations/relationships-v2-v3.mjs +11 -0
- package/dist/predefinedMigrations/v2-v3/fetchAndResave/index.d.ts +20 -0
- package/dist/predefinedMigrations/v2-v3/fetchAndResave/index.d.ts.map +1 -0
- package/dist/predefinedMigrations/v2-v3/fetchAndResave/index.js +170 -0
- package/dist/predefinedMigrations/v2-v3/fetchAndResave/index.js.map +1 -0
- package/dist/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.d.ts +11 -0
- package/dist/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.d.ts.map +1 -0
- package/dist/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.js +191 -0
- package/dist/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.js.map +1 -0
- package/dist/predefinedMigrations/v2-v3/groupUpSQLStatements.d.ts +3 -0
- package/dist/predefinedMigrations/v2-v3/groupUpSQLStatements.d.ts.map +1 -0
- package/dist/predefinedMigrations/v2-v3/groupUpSQLStatements.js +56 -0
- package/dist/predefinedMigrations/v2-v3/groupUpSQLStatements.js.map +1 -0
- package/dist/predefinedMigrations/v2-v3/index.d.ts +24 -0
- package/dist/predefinedMigrations/v2-v3/index.d.ts.map +1 -0
- package/dist/predefinedMigrations/v2-v3/index.js +211 -0
- package/dist/predefinedMigrations/v2-v3/index.js.map +1 -0
- package/dist/predefinedMigrations/v2-v3/migrateRelationships.d.ts +19 -0
- package/dist/predefinedMigrations/v2-v3/migrateRelationships.d.ts.map +1 -0
- package/dist/predefinedMigrations/v2-v3/migrateRelationships.js +57 -0
- package/dist/predefinedMigrations/v2-v3/migrateRelationships.js.map +1 -0
- package/dist/predefinedMigrations/v2-v3/traverseFields.d.ts +23 -0
- package/dist/predefinedMigrations/v2-v3/traverseFields.d.ts.map +1 -0
- package/dist/predefinedMigrations/v2-v3/traverseFields.js +85 -0
- package/dist/predefinedMigrations/v2-v3/traverseFields.js.map +1 -0
- package/dist/predefinedMigrations/v2-v3/types.d.ts +9 -0
- package/dist/predefinedMigrations/v2-v3/types.d.ts.map +1 -0
- package/dist/predefinedMigrations/v2-v3/types.js +6 -0
- package/dist/predefinedMigrations/v2-v3/types.js.map +1 -0
- package/dist/queries/buildAndOrConditions.d.ts +3 -4
- package/dist/queries/buildAndOrConditions.d.ts.map +1 -1
- package/dist/queries/buildAndOrConditions.js +1 -2
- package/dist/queries/buildAndOrConditions.js.map +1 -1
- package/dist/queries/buildQuery.d.ts +1 -2
- package/dist/queries/buildQuery.d.ts.map +1 -1
- package/dist/queries/buildQuery.js +1 -5
- package/dist/queries/buildQuery.js.map +1 -1
- package/dist/queries/getTableColumnFromPath.d.ts +3 -4
- package/dist/queries/getTableColumnFromPath.d.ts.map +1 -1
- package/dist/queries/getTableColumnFromPath.js +248 -143
- package/dist/queries/getTableColumnFromPath.js.map +1 -1
- package/dist/queries/parseParams.d.ts +3 -4
- package/dist/queries/parseParams.d.ts.map +1 -1
- package/dist/queries/parseParams.js +7 -6
- package/dist/queries/parseParams.js.map +1 -1
- package/dist/queries/selectDistinct.d.ts +3 -4
- package/dist/queries/selectDistinct.d.ts.map +1 -1
- package/dist/queries/selectDistinct.js +3 -14
- package/dist/queries/selectDistinct.js.map +1 -1
- package/dist/queryDrafts.d.ts.map +1 -1
- package/dist/queryDrafts.js +2 -6
- package/dist/queryDrafts.js.map +1 -1
- package/dist/schema/build.d.ts +11 -6
- package/dist/schema/build.d.ts.map +1 -1
- package/dist/schema/build.js +208 -124
- package/dist/schema/build.js.map +1 -1
- package/dist/schema/{getTableName.d.ts → createTableName.d.ts} +5 -7
- package/dist/schema/createTableName.d.ts.map +1 -0
- package/dist/schema/createTableName.js +31 -0
- package/dist/schema/createTableName.js.map +1 -0
- package/dist/schema/traverseFields.d.ts +4 -6
- package/dist/schema/traverseFields.d.ts.map +1 -1
- package/dist/schema/traverseFields.js +145 -61
- package/dist/schema/traverseFields.js.map +1 -1
- package/dist/schema/validateExistingBlockIsIdentical.d.ts +2 -1
- package/dist/schema/validateExistingBlockIsIdentical.d.ts.map +1 -1
- package/dist/schema/validateExistingBlockIsIdentical.js +13 -7
- package/dist/schema/validateExistingBlockIsIdentical.js.map +1 -1
- package/dist/transactions/beginTransaction.d.ts.map +1 -1
- package/dist/transactions/beginTransaction.js +4 -0
- package/dist/transactions/beginTransaction.js.map +1 -1
- package/dist/transform/read/index.d.ts +3 -1
- package/dist/transform/read/index.d.ts.map +1 -1
- package/dist/transform/read/index.js +2 -1
- package/dist/transform/read/index.js.map +1 -1
- package/dist/transform/read/relationship.d.ts.map +1 -1
- package/dist/transform/read/relationship.js +0 -4
- package/dist/transform/read/relationship.js.map +1 -1
- package/dist/transform/read/traverseFields.d.ts +6 -1
- package/dist/transform/read/traverseFields.d.ts.map +1 -1
- package/dist/transform/read/traverseFields.js +69 -55
- package/dist/transform/read/traverseFields.js.map +1 -1
- package/dist/transform/write/array.d.ts.map +1 -1
- package/dist/transform/write/array.js.map +1 -1
- package/dist/transform/write/blocks.js +1 -1
- package/dist/transform/write/blocks.js.map +1 -1
- package/dist/transform/write/traverseFields.d.ts.map +1 -1
- package/dist/transform/write/traverseFields.js +22 -5
- package/dist/transform/write/traverseFields.js.map +1 -1
- package/dist/types.d.ts +7 -7
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/update.d.ts.map +1 -1
- package/dist/update.js +3 -7
- package/dist/update.js.map +1 -1
- package/dist/updateGlobal.d.ts.map +1 -1
- package/dist/updateGlobal.js +2 -5
- package/dist/updateGlobal.js.map +1 -1
- package/dist/updateGlobalVersion.d.ts.map +1 -1
- package/dist/updateGlobalVersion.js +2 -6
- package/dist/updateGlobalVersion.js.map +1 -1
- package/dist/updateVersion.d.ts.map +1 -1
- package/dist/updateVersion.js +2 -6
- package/dist/updateVersion.js.map +1 -1
- package/dist/upsertRow/index.d.ts +1 -1
- package/dist/upsertRow/index.d.ts.map +1 -1
- package/dist/upsertRow/index.js +9 -6
- package/dist/upsertRow/index.js.map +1 -1
- package/dist/upsertRow/insertArrays.d.ts.map +1 -1
- package/dist/upsertRow/insertArrays.js +3 -3
- package/dist/upsertRow/insertArrays.js.map +1 -1
- package/dist/upsertRow/types.d.ts +7 -2
- package/dist/upsertRow/types.d.ts.map +1 -1
- package/dist/upsertRow/types.js.map +1 -1
- package/package.json +29 -27
- package/dist/schema/getTableName.d.ts.map +0 -1
- package/dist/schema/getTableName.js +0 -31
- package/dist/schema/getTableName.js.map +0 -1
- package/src/index.ts +0 -156
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../src/upsertRow/index.ts"],"sourcesContent":["/* eslint-disable no-param-reassign */\nimport type { TypeWithID } from 'payload/types'\n\nimport { eq } from 'drizzle-orm'\nimport { ValidationError } from 'payload/errors'\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'\n\nexport const upsertRow = async <T extends TypeWithID>({\n id,\n adapter,\n data,\n db,\n fields,\n operation,\n path = '',\n req,\n tableName,\n upsertTarget,\n where,\n}: Args): Promise<T> => {\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 fields,\n path,\n tableName,\n })\n\n // First, we insert the main row\n let insertedRow: Record<string, unknown>\n\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 db\n .insert(adapter.tables[tableName])\n .values(rowToInsert.row)\n .onConflictDoUpdate({ set: rowToInsert.row, target })\n .returning()\n } else {\n ;[insertedRow] = await db\n .insert(adapter.tables[tableName])\n .values(rowToInsert.row)\n .onConflictDoUpdate({ set: rowToInsert.row, target, where })\n .returning()\n }\n } else {\n ;[insertedRow] = await db\n .insert(adapter.tables[tableName])\n .values(rowToInsert.row)\n .returning()\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 selectRows.forEach((row) => {\n if (typeof row.parent === 'undefined') {\n row.parent = insertedRow.id\n }\n if (!selectsToInsert[selectTableName]) selectsToInsert[selectTableName] = []\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((blockName) => {\n rowToInsert.blocks[blockName].forEach((blockRow) => {\n blockRow.row._parentID = insertedRow.id\n if (!blocksToInsert[blockName]) blocksToInsert[blockName] = []\n if (blockRow.row.uuid) {\n delete blockRow.row.uuid\n }\n blocksToInsert[blockName].push(blockRow)\n })\n })\n\n // //////////////////////////////////\n // INSERT LOCALES\n // //////////////////////////////////\n\n if (localesToInsert.length > 0) {\n const localeTable = adapter.tables[`${tableName}_locales`]\n\n if (operation === 'update') {\n await db.delete(localeTable).where(eq(localeTable._parentID, insertedRow.id))\n }\n\n await db.insert(localeTable).values(localesToInsert)\n }\n\n // //////////////////////////////////\n // INSERT RELATIONSHIPS\n // //////////////////////////////////\n\n const relationshipsTableName = `${tableName}_rels`\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 db.insert(adapter.tables[relationshipsTableName]).values(relationsToInsert)\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,\n tableName: textsTableName,\n })\n }\n\n if (textsToInsert.length > 0) {\n await db.insert(adapter.tables[textsTableName]).values(textsToInsert).returning()\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,\n tableName: numbersTableName,\n })\n }\n\n if (numbersToInsert.length > 0) {\n await db.insert(adapter.tables[numbersTableName]).values(numbersToInsert).returning()\n }\n\n // //////////////////////////////////\n // INSERT BLOCKS\n // //////////////////////////////////\n\n const insertedBlockRows: Record<string, Record<string, unknown>[]> = {}\n\n if (operation === 'update') {\n for (const blockName of rowToInsert.blocksToDelete) {\n const blockTableName = `${tableName}_blocks_${blockName}`\n const blockTable = adapter.tables[blockTableName]\n await db.delete(blockTable).where(eq(blockTable._parentID, insertedRow.id))\n }\n }\n\n for (const [blockName, blockRows] of Object.entries(blocksToInsert)) {\n insertedBlockRows[blockName] = await db\n .insert(adapter.tables[`${tableName}_blocks_${blockName}`])\n .values(blockRows.map(({ row }) => row))\n .returning()\n\n insertedBlockRows[blockName].forEach((row, i) => {\n blockRows[i].row = row\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 db\n .insert(adapter.tables[`${tableName}_blocks_${blockName}_locales`])\n .values(blockLocaleRowsToInsert)\n .returning()\n }\n\n await insertArrays({\n adapter,\n arrays: blockRows.map(({ arrays }) => arrays),\n db,\n parentRows: insertedBlockRows[blockName],\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 })\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 db.delete(selectTable).where(eq(selectTable.parent, insertedRow.id))\n }\n await db.insert(selectTable).values(tableRows).returning()\n }\n\n // //////////////////////////////////\n // Error Handling\n // //////////////////////////////////\n } catch (error) {\n throw error.code === '23505'\n ? new ValidationError(\n [\n {\n field: adapter.fieldConstraints[tableName][error.constraint],\n message: req.t('error:valueMustBeUnique'),\n },\n ],\n req.t,\n )\n : error\n }\n\n // //////////////////////////////////\n // RETRIEVE NEWLY UPDATED ROW\n // //////////////////////////////////\n\n const findManyArgs = buildFindManyArgs({\n adapter,\n depth: 0,\n fields,\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 config: adapter.payload.config,\n data: doc,\n fields,\n })\n\n return result\n}\n"],"names":["eq","ValidationError","buildFindManyArgs","transform","transformForWrite","deleteExistingArrayRows","deleteExistingRowsByPath","insertArrays","upsertRow","id","adapter","data","db","fields","operation","path","req","tableName","upsertTarget","where","rowToInsert","insertedRow","target","tables","row","insert","values","onConflictDoUpdate","set","returning","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","blockName","blockRow","uuid","localeTable","delete","relationshipsTableName","localeColumnName","parentColumnName","parentID","pathColumnName","rows","relationshipsToDelete","textsTableName","numbersTableName","insertedBlockRows","blocksToDelete","blockTableName","blockTable","blockRows","map","i","blockLocaleIndexMap","blockLocaleRowsToInsert","reduce","acc","blockLocale","blockLocaleData","arrays","parentRows","arrayTableName","tableRows","selectTable","error","code","field","fieldConstraints","constraint","message","t","findManyArgs","depth","doc","query","findFirst","result","config","payload"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,oCAAoC,GAGpC,SAASA,EAAE,QAAQ,cAAa;AAChC,SAASC,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,qCAAqC;IACrC,iBAAiB;IACjB,qCAAqC;IACvC,EAAE,OAAO6D,OAAO;QACd,MAAMA,MAAMC,IAAI,KAAK,UACjB,IAAI1F,gBACF;YACE;gBACE2F,OAAOlF,QAAQmF,gBAAgB,CAAC5E,UAAU,CAACyE,MAAMI,UAAU,CAAC;gBAC5DC,SAAS/E,IAAIgF,CAAC,CAAC;YACjB;SACD,EACDhF,IAAIgF,CAAC,IAEPN;IACN;IAEA,qCAAqC;IACrC,6BAA6B;IAC7B,qCAAqC;IAErC,MAAMO,eAAe/F,kBAAkB;QACrCQ;QACAwF,OAAO;QACPrF;QACAI;IACF;IAEAgF,aAAa9E,KAAK,GAAGnB,GAAGU,QAAQa,MAAM,CAACN,UAAU,CAACR,EAAE,EAAEY,YAAYZ,EAAE;IAEpE,MAAM0F,MAAM,MAAMvF,GAAGwF,KAAK,CAACnF,UAAU,CAACoF,SAAS,CAACJ;IAEhD,qCAAqC;IACrC,iBAAiB;IACjB,qCAAqC;IAErC,MAAMK,SAASnG,UAAa;QAC1BoG,QAAQ7F,QAAQ8F,OAAO,CAACD,MAAM;QAC9B5F,MAAMwF;QACNtF;IACF;IAEA,OAAOyF;AACT,EAAC"}
|
1
|
+
{"version":3,"sources":["../../src/upsertRow/index.ts"],"sourcesContent":["/* eslint-disable no-param-reassign */\nimport type { TypeWithID } from 'payload/types'\n\nimport { eq } from 'drizzle-orm'\nimport { ValidationError } from 'payload/errors'\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'\n\nexport const upsertRow = async <T extends TypeWithID>({\n id,\n adapter,\n data,\n db,\n fields,\n ignoreResult,\n operation,\n path = '',\n req,\n tableName,\n upsertTarget,\n where,\n}: Args): Promise<T> => {\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 fields,\n path,\n tableName,\n })\n\n // First, we insert the main row\n let insertedRow: Record<string, unknown>\n\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 db\n .insert(adapter.tables[tableName])\n .values(rowToInsert.row)\n .onConflictDoUpdate({ set: rowToInsert.row, target })\n .returning()\n } else {\n ;[insertedRow] = await db\n .insert(adapter.tables[tableName])\n .values(rowToInsert.row)\n .onConflictDoUpdate({ set: rowToInsert.row, target, where })\n .returning()\n }\n } else {\n ;[insertedRow] = await db\n .insert(adapter.tables[tableName])\n .values(rowToInsert.row)\n .returning()\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 selectRows.forEach((row) => {\n if (typeof row.parent === 'undefined') {\n row.parent = insertedRow.id\n }\n if (!selectsToInsert[selectTableName]) selectsToInsert[selectTableName] = []\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((blockName) => {\n rowToInsert.blocks[blockName].forEach((blockRow) => {\n blockRow.row._parentID = insertedRow.id\n if (!blocksToInsert[blockName]) blocksToInsert[blockName] = []\n if (blockRow.row.uuid) {\n delete blockRow.row.uuid\n }\n blocksToInsert[blockName].push(blockRow)\n })\n })\n\n // //////////////////////////////////\n // INSERT LOCALES\n // //////////////////////////////////\n\n if (localesToInsert.length > 0) {\n const localeTable = adapter.tables[`${tableName}${adapter.localesSuffix}`]\n\n if (operation === 'update') {\n await db.delete(localeTable).where(eq(localeTable._parentID, insertedRow.id))\n }\n\n await db.insert(localeTable).values(localesToInsert)\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 db.insert(adapter.tables[relationshipsTableName]).values(relationsToInsert)\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,\n tableName: textsTableName,\n })\n }\n\n if (textsToInsert.length > 0) {\n await db.insert(adapter.tables[textsTableName]).values(textsToInsert).returning()\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,\n tableName: numbersTableName,\n })\n }\n\n if (numbersToInsert.length > 0) {\n await db.insert(adapter.tables[numbersTableName]).values(numbersToInsert).returning()\n }\n\n // //////////////////////////////////\n // INSERT BLOCKS\n // //////////////////////////////////\n\n const insertedBlockRows: Record<string, Record<string, unknown>[]> = {}\n\n if (operation === 'update') {\n for (const blockName of rowToInsert.blocksToDelete) {\n const blockTableName = adapter.tableNameMap.get(`${tableName}_blocks_${blockName}`)\n const blockTable = adapter.tables[blockTableName]\n await db.delete(blockTable).where(eq(blockTable._parentID, insertedRow.id))\n }\n }\n\n for (const [blockName, blockRows] of Object.entries(blocksToInsert)) {\n const blockTableName = adapter.tableNameMap.get(`${tableName}_blocks_${blockName}`)\n insertedBlockRows[blockName] = await db\n .insert(adapter.tables[blockTableName])\n .values(blockRows.map(({ row }) => row))\n .returning()\n\n insertedBlockRows[blockName].forEach((row, i) => {\n blockRows[i].row = row\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 db\n .insert(adapter.tables[`${blockTableName}${adapter.localesSuffix}`])\n .values(blockLocaleRowsToInsert)\n .returning()\n }\n\n await insertArrays({\n adapter,\n arrays: blockRows.map(({ arrays }) => arrays),\n db,\n parentRows: insertedBlockRows[blockName],\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 })\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 db.delete(selectTable).where(eq(selectTable.parent, insertedRow.id))\n }\n await db.insert(selectTable).values(tableRows).returning()\n }\n\n // //////////////////////////////////\n // Error Handling\n // //////////////////////////////////\n } catch (error) {\n throw error.code === '23505'\n ? new ValidationError(\n [\n {\n field: adapter.fieldConstraints[tableName][error.constraint],\n message: req.t('error:valueMustBeUnique'),\n },\n ],\n req.t,\n )\n : error\n }\n\n if (ignoreResult) return data as T\n\n // //////////////////////////////////\n // RETRIEVE NEWLY UPDATED ROW\n // //////////////////////////////////\n\n const findManyArgs = buildFindManyArgs({\n adapter,\n depth: 0,\n fields,\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 })\n\n return result\n}\n"],"names":["eq","ValidationError","buildFindManyArgs","transform","transformForWrite","deleteExistingArrayRows","deleteExistingRowsByPath","insertArrays","upsertRow","id","adapter","data","db","fields","ignoreResult","operation","path","req","tableName","upsertTarget","where","rowToInsert","insertedRow","target","tables","row","insert","values","onConflictDoUpdate","set","returning","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","blockName","blockRow","uuid","localeTable","localesSuffix","delete","relationshipsTableName","relationshipsSuffix","localeColumnName","parentColumnName","parentID","pathColumnName","rows","relationshipsToDelete","textsTableName","numbersTableName","insertedBlockRows","blocksToDelete","blockTableName","tableNameMap","get","blockTable","blockRows","map","i","blockLocaleIndexMap","blockLocaleRowsToInsert","reduce","acc","blockLocale","blockLocaleData","arrays","parentRows","arrayTableName","tableRows","selectTable","error","code","field","fieldConstraints","constraint","message","t","findManyArgs","depth","doc","query","findFirst","result","config","payload"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,oCAAoC,GAGpC,SAASA,EAAE,QAAQ,cAAa;AAChC,SAASC,eAAe,QAAQ,iBAAgB;AAKhD,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;AAEhD,OAAO,MAAMC,YAAY,OAA6B,EACpD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F;YACE;gBACEgG,OAAOvF,QAAQwF,gBAAgB,CAAChF,UAAU,CAAC6E,MAAMI,UAAU,CAAC;gBAC5DC,SAASnF,IAAIoF,CAAC,CAAC;YACjB;SACD,EACDpF,IAAIoF,CAAC,IAEPN;IACN;IAEA,IAAIjF,cAAc,OAAOH;IAEzB,qCAAqC;IACrC,6BAA6B;IAC7B,qCAAqC;IAErC,MAAM2F,eAAepG,kBAAkB;QACrCQ;QACA6F,OAAO;QACP1F;QACAK;IACF;IAEAoF,aAAalF,KAAK,GAAGpB,GAAGU,QAAQc,MAAM,CAACN,UAAU,CAACT,EAAE,EAAEa,YAAYb,EAAE;IAEpE,MAAM+F,MAAM,MAAM5F,GAAG6F,KAAK,CAACvF,UAAU,CAACwF,SAAS,CAACJ;IAEhD,qCAAqC;IACrC,iBAAiB;IACjB,qCAAqC;IAErC,MAAMK,SAASxG,UAAa;QAC1BO;QACAkG,QAAQlG,QAAQmG,OAAO,CAACD,MAAM;QAC9BjG,MAAM6F;QACN3F;IACF;IAEA,OAAO8F;AACT,EAAC"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"insertArrays.d.ts","sourceRoot":"","sources":["../../src/upsertRow/insertArrays.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAA;AACnE,OAAO,KAAK,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAE7D,KAAK,IAAI,GAAG;IACV,OAAO,EAAE,eAAe,CAAA;IACxB,MAAM,EAAE;QACN,CAAC,SAAS,EAAE,MAAM,GAAG,gBAAgB,EAAE,CAAA;KACxC,EAAE,CAAA;IACH,EAAE,EAAE,SAAS,CAAA;IACb,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAA;CACtC,CAAA;AAYD,eAAO,MAAM,YAAY,wCAA+C,IAAI,KAAG,QAAQ,IAAI,
|
1
|
+
{"version":3,"file":"insertArrays.d.ts","sourceRoot":"","sources":["../../src/upsertRow/insertArrays.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAA;AACnE,OAAO,KAAK,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAE7D,KAAK,IAAI,GAAG;IACV,OAAO,EAAE,eAAe,CAAA;IACxB,MAAM,EAAE;QACN,CAAC,SAAS,EAAE,MAAM,GAAG,gBAAgB,EAAE,CAAA;KACxC,EAAE,CAAA;IACH,EAAE,EAAE,SAAS,CAAA;IACb,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAA;CACtC,CAAA;AAYD,eAAO,MAAM,YAAY,wCAA+C,IAAI,KAAG,QAAQ,IAAI,CA4E1F,CAAA"}
|
@@ -41,9 +41,9 @@
|
|
41
41
|
insertedRows = await db.insert(adapter.tables[tableName]).values(row.rows).returning();
|
42
42
|
}
|
43
43
|
// Insert locale rows
|
44
|
-
if (adapter.tables[`${tableName}
|
44
|
+
if (adapter.tables[`${tableName}${adapter.localesSuffix}`] && row.locales.length > 0) {
|
45
45
|
if (!row.locales[0]._parentID) {
|
46
|
-
row.locales = row.locales.map((localeRow
|
46
|
+
row.locales = row.locales.map((localeRow)=>{
|
47
47
|
if (typeof localeRow._getParentID === 'function') {
|
48
48
|
localeRow._parentID = localeRow._getParentID(insertedRows);
|
49
49
|
delete localeRow._getParentID;
|
@@ -51,7 +51,7 @@
|
|
51
51
|
return localeRow;
|
52
52
|
});
|
53
53
|
}
|
54
|
-
await db.insert(adapter.tables[`${tableName}
|
54
|
+
await db.insert(adapter.tables[`${tableName}${adapter.localesSuffix}`]).values(row.locales).returning();
|
55
55
|
}
|
56
56
|
// If there are sub arrays, call this function recursively
|
57
57
|
if (row.arrays.length > 0) {
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../src/upsertRow/insertArrays.ts"],"sourcesContent":["/* eslint-disable no-param-reassign */\nimport type { ArrayRowToInsert } from '../transform/write/types.js'\nimport type { DrizzleDB, PostgresAdapter } from '../types.js'\n\ntype Args = {\n adapter: PostgresAdapter\n arrays: {\n [tableName: string]: ArrayRowToInsert[]\n }[]\n db: DrizzleDB\n parentRows: Record<string, unknown>[]\n}\n\ntype RowsByTable = {\n [tableName: string]: {\n arrays: {\n [tableName: string]: ArrayRowToInsert[]\n }[]\n locales: Record<string, unknown>[]\n rows: Record<string, unknown>[]\n }\n}\n\nexport const insertArrays = async ({ adapter, arrays, db, parentRows }: Args): Promise<void> => {\n // Maintain a map of flattened rows by table\n const rowsByTable: RowsByTable = {}\n\n arrays.forEach((arraysByTable, parentRowIndex) => {\n Object.entries(arraysByTable).forEach(([tableName, arrayRows]) => {\n // If the table doesn't exist in map, initialize it\n if (!rowsByTable[tableName]) {\n rowsByTable[tableName] = {\n arrays: [],\n locales: [],\n rows: [],\n }\n }\n\n const parentID = parentRows[parentRowIndex].id\n\n // Add any sub arrays that need to be created\n // We will call this recursively below\n arrayRows.forEach((arrayRow, i) => {\n if (Object.keys(arrayRow.arrays).length > 0) {\n rowsByTable[tableName].arrays.push(arrayRow.arrays)\n }\n\n // Set up parent IDs for both row and locale row\n arrayRow.row._parentID = parentID\n rowsByTable[tableName].rows.push(arrayRow.row)\n\n Object.entries(arrayRow.locales).forEach(([arrayRowLocale, arrayRowLocaleData]) => {\n arrayRowLocaleData._parentID = arrayRow.row.id\n arrayRowLocaleData._locale = arrayRowLocale\n rowsByTable[tableName].locales.push(arrayRowLocaleData)\n if (!arrayRow.row.id) {\n arrayRowLocaleData._getParentID = (rows) => rows[i].id\n }\n })\n })\n })\n })\n\n // Insert all corresponding arrays\n // (one insert per array table)\n for (const [tableName, row] of Object.entries(rowsByTable)) {\n // the nested arrays need the ID for the parentID foreign key\n let insertedRows: Args['parentRows']\n if (row.rows.length > 0) {\n insertedRows = await db.insert(adapter.tables[tableName]).values(row.rows).returning()\n }\n\n // Insert locale rows\n if (adapter.tables[`${tableName}
|
1
|
+
{"version":3,"sources":["../../src/upsertRow/insertArrays.ts"],"sourcesContent":["/* eslint-disable no-param-reassign */\nimport type { ArrayRowToInsert } from '../transform/write/types.js'\nimport type { DrizzleDB, PostgresAdapter } from '../types.js'\n\ntype Args = {\n adapter: PostgresAdapter\n arrays: {\n [tableName: string]: ArrayRowToInsert[]\n }[]\n db: DrizzleDB\n parentRows: Record<string, unknown>[]\n}\n\ntype RowsByTable = {\n [tableName: string]: {\n arrays: {\n [tableName: string]: ArrayRowToInsert[]\n }[]\n locales: Record<string, unknown>[]\n rows: Record<string, unknown>[]\n }\n}\n\nexport const insertArrays = async ({ adapter, arrays, db, parentRows }: Args): Promise<void> => {\n // Maintain a map of flattened rows by table\n const rowsByTable: RowsByTable = {}\n\n arrays.forEach((arraysByTable, parentRowIndex) => {\n Object.entries(arraysByTable).forEach(([tableName, arrayRows]) => {\n // If the table doesn't exist in map, initialize it\n if (!rowsByTable[tableName]) {\n rowsByTable[tableName] = {\n arrays: [],\n locales: [],\n rows: [],\n }\n }\n\n const parentID = parentRows[parentRowIndex].id\n\n // Add any sub arrays that need to be created\n // We will call this recursively below\n arrayRows.forEach((arrayRow, i) => {\n if (Object.keys(arrayRow.arrays).length > 0) {\n rowsByTable[tableName].arrays.push(arrayRow.arrays)\n }\n\n // Set up parent IDs for both row and locale row\n arrayRow.row._parentID = parentID\n rowsByTable[tableName].rows.push(arrayRow.row)\n\n Object.entries(arrayRow.locales).forEach(([arrayRowLocale, arrayRowLocaleData]) => {\n arrayRowLocaleData._parentID = arrayRow.row.id\n arrayRowLocaleData._locale = arrayRowLocale\n rowsByTable[tableName].locales.push(arrayRowLocaleData)\n if (!arrayRow.row.id) {\n arrayRowLocaleData._getParentID = (rows) => rows[i].id\n }\n })\n })\n })\n })\n\n // Insert all corresponding arrays\n // (one insert per array table)\n for (const [tableName, row] of Object.entries(rowsByTable)) {\n // the nested arrays need the ID for the parentID foreign key\n let insertedRows: Args['parentRows']\n if (row.rows.length > 0) {\n insertedRows = await db.insert(adapter.tables[tableName]).values(row.rows).returning()\n }\n\n // Insert locale rows\n if (adapter.tables[`${tableName}${adapter.localesSuffix}`] && row.locales.length > 0) {\n if (!row.locales[0]._parentID) {\n row.locales = row.locales.map((localeRow) => {\n if (typeof localeRow._getParentID === 'function') {\n localeRow._parentID = localeRow._getParentID(insertedRows)\n delete localeRow._getParentID\n }\n return localeRow\n })\n }\n await db\n .insert(adapter.tables[`${tableName}${adapter.localesSuffix}`])\n .values(row.locales)\n .returning()\n }\n\n // If there are sub arrays, call this function recursively\n if (row.arrays.length > 0) {\n await insertArrays({\n adapter,\n arrays: row.arrays,\n db,\n parentRows: insertedRows,\n })\n }\n }\n}\n"],"names":["insertArrays","adapter","arrays","db","parentRows","rowsByTable","forEach","arraysByTable","parentRowIndex","Object","entries","tableName","arrayRows","locales","rows","parentID","id","arrayRow","i","keys","length","push","row","_parentID","arrayRowLocale","arrayRowLocaleData","_locale","_getParentID","insertedRows","insert","tables","values","returning","localesSuffix","map","localeRow"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,oCAAoC,GAuBpC,OAAO,MAAMA,eAAe,OAAO,EAAEC,OAAO,EAAEC,MAAM,EAAEC,EAAE,EAAEC,UAAU,EAAQ;IAC1E,4CAA4C;IAC5C,MAAMC,cAA2B,CAAC;IAElCH,OAAOI,OAAO,CAAC,CAACC,eAAeC;QAC7BC,OAAOC,OAAO,CAACH,eAAeD,OAAO,CAAC,CAAC,CAACK,WAAWC,UAAU;YAC3D,mDAAmD;YACnD,IAAI,CAACP,WAAW,CAACM,UAAU,EAAE;gBAC3BN,WAAW,CAACM,UAAU,GAAG;oBACvBT,QAAQ,EAAE;oBACVW,SAAS,EAAE;oBACXC,MAAM,EAAE;gBACV;YACF;YAEA,MAAMC,WAAWX,UAAU,CAACI,eAAe,CAACQ,EAAE;YAE9C,6CAA6C;YAC7C,sCAA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AAS,EAAE;gBAC7BD,IAAIT,OAAO,GAAGS,IAAIT,OAAO,CAACqB,GAAG,CAAC,CAACC;oBAC7B,IAAI,OAAOA,UAAUR,YAAY,KAAK,YAAY;wBAChDQ,UAAUZ,SAAS,GAAGY,UAAUR,YAAY,CAACC;wBAC7C,OAAOO,UAAUR,YAAY;oBAC/B;oBACA,OAAOQ;gBACT;YACF;YACA,MAAMhC,GACH0B,MAAM,CAAC5B,QAAQ6B,MAAM,CAAC,CAAC,EAAEnB,UAAU,EAAEV,QAAQgC,aAAa,CAAC,CAAC,CAAC,EAC7DF,MAAM,CAACT,IAAIT,OAAO,EAClBmB,SAAS;QACd;QAEA,0DAA0D;QAC1D,IAAIV,IAAIpB,MAAM,CAACkB,MAAM,GAAG,GAAG;YACzB,MAAMpB,aAAa;gBACjBC;gBACAC,QAAQoB,IAAIpB,MAAM;gBAClBC;gBACAC,YAAYwB;YACd;QACF;IACF;AACF,EAAC"}
|
@@ -1,13 +1,18 @@
|
|
1
1
|
import type { SQL } from 'drizzle-orm';
|
2
|
-
import type { Field,
|
2
|
+
import type { Field, PayloadRequestWithData } from 'payload/types';
|
3
3
|
import type { DrizzleDB, GenericColumn, PostgresAdapter } from '../types.js';
|
4
4
|
type BaseArgs = {
|
5
5
|
adapter: PostgresAdapter;
|
6
6
|
data: Record<string, unknown>;
|
7
7
|
db: DrizzleDB;
|
8
8
|
fields: Field[];
|
9
|
+
/**
|
10
|
+
* When true, skips reading the data back from the database and returns the input data
|
11
|
+
* @default false
|
12
|
+
*/
|
13
|
+
ignoreResult?: boolean;
|
9
14
|
path?: string;
|
10
|
-
req:
|
15
|
+
req: PayloadRequestWithData;
|
11
16
|
tableName: string;
|
12
17
|
};
|
13
18
|
type CreateArgs = BaseArgs & {
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/upsertRow/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,aAAa,CAAA;AACtC,OAAO,KAAK,EAAE,KAAK,EAAE,
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/upsertRow/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,aAAa,CAAA;AACtC,OAAO,KAAK,EAAE,KAAK,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAA;AAElE,OAAO,KAAK,EAAE,SAAS,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAE5E,KAAK,QAAQ,GAAG;IACd,OAAO,EAAE,eAAe,CAAA;IACxB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC7B,EAAE,EAAE,SAAS,CAAA;IACb,MAAM,EAAE,KAAK,EAAE,CAAA;IACf;;;OAGG;IACH,YAAY,CAAC,EAAE,OAAO,CAAA;IACtB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,GAAG,EAAE,sBAAsB,CAAA;IAC3B,SAAS,EAAE,MAAM,CAAA;CAClB,CAAA;AAED,KAAK,UAAU,GAAG,QAAQ,GAAG;IAC3B,EAAE,CAAC,EAAE,KAAK,CAAA;IACV,SAAS,EAAE,QAAQ,CAAA;IACnB,YAAY,CAAC,EAAE,KAAK,CAAA;IACpB,KAAK,CAAC,EAAE,KAAK,CAAA;CACd,CAAA;AAED,KAAK,UAAU,GAAG,QAAQ,GAAG;IAC3B,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;IACpB,SAAS,EAAE,QAAQ,CAAA;IACnB,YAAY,CAAC,EAAE,aAAa,CAAA;IAC5B,KAAK,CAAC,EAAE,GAAG,CAAC,OAAO,CAAC,CAAA;CACrB,CAAA;AAED,MAAM,MAAM,IAAI,GAAG,UAAU,GAAG,UAAU,CAAA"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../src/upsertRow/types.ts"],"sourcesContent":["import type { SQL } from 'drizzle-orm'\nimport type { Field,
|
1
|
+
{"version":3,"sources":["../../src/upsertRow/types.ts"],"sourcesContent":["import type { SQL } from 'drizzle-orm'\nimport type { Field, PayloadRequestWithData } from 'payload/types'\n\nimport type { DrizzleDB, GenericColumn, PostgresAdapter } from '../types.js'\n\ntype BaseArgs = {\n adapter: PostgresAdapter\n data: Record<string, unknown>\n db: DrizzleDB\n fields: Field[]\n /**\n * When true, skips reading the data back from the database and returns the input data\n * @default false\n */\n ignoreResult?: boolean\n path?: string\n req: PayloadRequestWithData\n tableName: string\n}\n\ntype CreateArgs = BaseArgs & {\n id?: never\n operation: 'create'\n upsertTarget?: never\n where?: never\n}\n\ntype UpdateArgs = BaseArgs & {\n id?: number | string\n operation: 'update'\n upsertTarget?: GenericColumn\n where?: SQL<unknown>\n}\n\nexport type Args = CreateArgs | UpdateArgs\n"],"names":[],"rangeMappings":"","mappings":"AAkCA,WAA0C"}
|
package/package.json
CHANGED
@@ -1,22 +1,39 @@
|
|
1
1
|
{
|
2
2
|
"name": "@payloadcms/db-postgres",
|
3
|
-
"version": "3.0.0-
|
3
|
+
"version": "3.0.0-canary.220bb7c",
|
4
4
|
"description": "The officially supported Postgres database adapter for Payload",
|
5
|
+
"homepage": "https://payloadcms.com",
|
5
6
|
"repository": {
|
6
7
|
"type": "git",
|
7
8
|
"url": "https://github.com/payloadcms/payload.git",
|
8
9
|
"directory": "packages/db-postgres"
|
9
10
|
},
|
10
11
|
"license": "MIT",
|
11
|
-
"
|
12
|
+
"author": "Payload <dev@payloadcms.com> (https://payloadcms.com)",
|
12
13
|
"type": "module",
|
13
|
-
"
|
14
|
-
"
|
15
|
-
|
16
|
-
|
14
|
+
"exports": {
|
15
|
+
".": {
|
16
|
+
"import": "./dist/index.js",
|
17
|
+
"require": "./dist/index.js",
|
18
|
+
"types": "./dist/index.d.ts"
|
19
|
+
},
|
20
|
+
"./types": {
|
21
|
+
"import": "./dist/types.js",
|
22
|
+
"require": "./dist/types.js",
|
23
|
+
"types": "./dist/types.d.ts"
|
24
|
+
},
|
25
|
+
"./migration-utils": {
|
26
|
+
"import": "./dist/exports/migration-utils.js",
|
27
|
+
"require": "./dist/exports/migration-utils.js",
|
28
|
+
"types": "./dist/exports/migration-utils.d.ts"
|
29
|
+
}
|
17
30
|
},
|
18
31
|
"main": "./dist/index.js",
|
19
32
|
"types": "./dist/index.d.ts",
|
33
|
+
"files": [
|
34
|
+
"dist",
|
35
|
+
"mock.js"
|
36
|
+
],
|
20
37
|
"dependencies": {
|
21
38
|
"@libsql/client": "^0.5.2",
|
22
39
|
"console-table-printer": "2.11.2",
|
@@ -25,37 +42,22 @@
|
|
25
42
|
"pg": "8.11.3",
|
26
43
|
"prompts": "2.4.2",
|
27
44
|
"to-snake-case": "1.0.0",
|
28
|
-
"uuid": "9.0.
|
45
|
+
"uuid": "^9.0.1"
|
29
46
|
},
|
30
47
|
"devDependencies": {
|
31
48
|
"@types/pg": "8.10.2",
|
32
49
|
"@types/to-snake-case": "1.0.0",
|
33
|
-
"payload": "3.0.0-
|
50
|
+
"payload": "3.0.0-canary.220bb7c",
|
34
51
|
"@payloadcms/eslint-config": "1.1.1"
|
35
52
|
},
|
36
53
|
"peerDependencies": {
|
37
|
-
"payload": "3.0.0-
|
54
|
+
"payload": "3.0.0-canary.220bb7c"
|
38
55
|
},
|
39
|
-
"exports": {
|
40
|
-
".": {
|
41
|
-
"import": "./dist/index.js",
|
42
|
-
"require": "./dist/index.js",
|
43
|
-
"types": "./dist/index.d.ts"
|
44
|
-
},
|
45
|
-
"./types": {
|
46
|
-
"import": "./dist/types.js",
|
47
|
-
"require": "./dist/types.js",
|
48
|
-
"types": "./dist/types.d.ts"
|
49
|
-
}
|
50
|
-
},
|
51
|
-
"files": [
|
52
|
-
"dist",
|
53
|
-
"mock.js"
|
54
|
-
],
|
55
56
|
"scripts": {
|
56
|
-
"build": "pnpm build:swc && pnpm build:types",
|
57
|
+
"build": "pnpm build:swc && pnpm build:types && pnpm renamePredefinedMigrations",
|
57
58
|
"build:swc": "swc ./src -d ./dist --config-file .swcrc",
|
58
59
|
"build:types": "tsc --emitDeclarationOnly --outDir dist",
|
59
|
-
"clean": "rimraf {dist,*.tsbuildinfo}"
|
60
|
+
"clean": "rimraf {dist,*.tsbuildinfo}",
|
61
|
+
"renamePredefinedMigrations": "tsx ./scripts/renamePredefinedMigrations.ts"
|
60
62
|
}
|
61
63
|
}
|
@@ -1 +0,0 @@
|
|
1
|
-
{"version":3,"file":"getTableName.d.ts","sourceRoot":"","sources":["../../src/schema/getTableName.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAA;AAKxD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAElD,KAAK,IAAI,GAAG;IACV,OAAO,EAAE,eAAe,CAAA;IACxB,8CAA8C;IAC9C,MAAM,EAAE;QACN,MAAM,CAAC,EAAE,gBAAgB,CAAA;QACzB,QAAQ,CAAC,EAAE,gBAAgB,CAAA;QAC3B,IAAI,CAAC,EAAE,MAAM,CAAA;QACb,IAAI,CAAC,EAAE,MAAM,CAAA;KACd,CAAA;IACD,2DAA2D;IAC3D,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,mGAAmG;IACnG,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,mFAAmF;IACnF,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,oCAAoC;IACpC,aAAa,CAAC,EAAE,OAAO,CAAA;IACvB,uHAAuH;IACvH,MAAM,CAAC,EAAE,QAAQ,GAAG,UAAU,CAAA;IAC9B,oBAAoB,CAAC,EAAE,OAAO,CAAA;IAC9B,kGAAkG;IAClG,QAAQ,CAAC,EAAE,OAAO,CAAA;CACnB,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,YAAY,0IAWtB,IAAI,KAAG,MA4BT,CAAA"}
|
@@ -1,31 +0,0 @@
|
|
1
|
-
import { APIError } from 'payload/errors';
|
2
|
-
import toSnakeCase from 'to-snake-case';
|
3
|
-
/**
|
4
|
-
* Used to name database enums and tables
|
5
|
-
* Returns the table or enum name for a given entity
|
6
|
-
*/ export const getTableName = ({ adapter, config: { name, slug }, config, locales = false, parentTableName, prefix = '', relationships = false, target = 'dbName', throwValidationError = false, versions = false })=>{
|
7
|
-
let result;
|
8
|
-
let custom = config[target];
|
9
|
-
if (!custom && target === 'enumName') {
|
10
|
-
custom = config['dbName'];
|
11
|
-
}
|
12
|
-
if (custom) {
|
13
|
-
result = typeof custom === 'function' ? custom({
|
14
|
-
tableName: parentTableName
|
15
|
-
}) : custom;
|
16
|
-
} else {
|
17
|
-
result = `${prefix}${toSnakeCase(name ?? slug)}`;
|
18
|
-
}
|
19
|
-
if (locales) result = `${result}${adapter.localesSuffix}`;
|
20
|
-
if (versions) result = `_${result}${adapter.versionsSuffix}`;
|
21
|
-
if (relationships) result = `${result}${adapter.relationshipsSuffix}`;
|
22
|
-
if (!throwValidationError) {
|
23
|
-
return result;
|
24
|
-
}
|
25
|
-
if (result.length > 63) {
|
26
|
-
throw new APIError(`Exceeded max identifier length for table or enum name of 63 characters. Invalid name: ${result}`);
|
27
|
-
}
|
28
|
-
return result;
|
29
|
-
};
|
30
|
-
|
31
|
-
//# sourceMappingURL=getTableName.js.map
|
@@ -1 +0,0 @@
|
|
1
|
-
{"version":3,"sources":["../../src/schema/getTableName.ts"],"sourcesContent":["import type { DBIdentifierName } from 'payload/database'\n\nimport { APIError } from 'payload/errors'\nimport toSnakeCase from 'to-snake-case'\n\nimport type { PostgresAdapter } from '../types.js'\n\ntype Args = {\n adapter: PostgresAdapter\n /** The collection, global or field config **/\n config: {\n dbName?: DBIdentifierName\n enumName?: DBIdentifierName\n name?: string\n slug?: string\n }\n /** Localized tables need to be given the locales suffix */\n locales?: boolean\n /** For nested tables passed for the user custom dbName functions to handle their own iterations */\n parentTableName?: string\n /** For sub tables (array for example) this needs to include the parentTableName */\n prefix?: string\n /** Adds the relationships suffix */\n relationships?: boolean\n /** For tables based on fields that could have both enumName and dbName (ie: select with hasMany), default: 'dbName' */\n target?: 'dbName' | 'enumName'\n throwValidationError?: boolean\n /** Adds the versions suffix, should only be used on the base collection to duplicate suffixing */\n versions?: boolean\n}\n\n/**\n * Used to name database enums and tables\n * Returns the table or enum name for a given entity\n */\nexport const getTableName = ({\n adapter,\n config: { name, slug },\n config,\n locales = false,\n parentTableName,\n prefix = '',\n relationships = false,\n target = 'dbName',\n throwValidationError = false,\n versions = false,\n}: Args): string => {\n let result: string\n let custom = config[target]\n\n if (!custom && target === 'enumName') {\n custom = config['dbName']\n }\n\n if (custom) {\n result = typeof custom === 'function' ? custom({ tableName: parentTableName }) : custom\n } else {\n result = `${prefix}${toSnakeCase(name ?? slug)}`\n }\n\n if (locales) result = `${result}${adapter.localesSuffix}`\n if (versions) result = `_${result}${adapter.versionsSuffix}`\n if (relationships) result = `${result}${adapter.relationshipsSuffix}`\n\n if (!throwValidationError) {\n return result\n }\n\n if (result.length > 63) {\n throw new APIError(\n `Exceeded max identifier length for table or enum name of 63 characters. Invalid name: ${result}`,\n )\n }\n return result\n}\n"],"names":["APIError","toSnakeCase","getTableName","adapter","config","name","slug","locales","parentTableName","prefix","relationships","target","throwValidationError","versions","result","custom","tableName","localesSuffix","versionsSuffix","relationshipsSuffix","length"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAEA,SAASA,QAAQ,QAAQ,iBAAgB;AACzC,OAAOC,iBAAiB,gBAAe;AA4BvC;;;CAGC,GACD,OAAO,MAAMC,eAAe,CAAC,EAC3BC,OAAO,EACPC,QAAQ,EAAEC,IAAI,EAAEC,IAAI,EAAE,EACtBF,MAAM,EACNG,UAAU,KAAK,EACfC,eAAe,EACfC,SAAS,EAAE,EACXC,gBAAgB,KAAK,EACrBC,SAAS,QAAQ,EACjBC,uBAAuB,KAAK,EAC5BC,WAAW,KAAK,EACX;IACL,IAAIC;IACJ,IAAIC,SAASX,MAAM,CAACO,OAAO;IAE3B,IAAI,CAACI,UAAUJ,WAAW,YAAY;QACpCI,SAASX,MAAM,CAAC,SAAS;IAC3B;IAEA,IAAIW,QAAQ;QACVD,SAAS,OAAOC,WAAW,aAAaA,OAAO;YAAEC,WAAWR;QAAgB,KAAKO;IACnF,OAAO;QACLD,SAAS,CAAC,EAAEL,OAAO,EAAER,YAAYI,QAAQC,MAAM,CAAC;IAClD;IAEA,IAAIC,SAASO,SAAS,CAAC,EAAEA,OAAO,EAAEX,QAAQc,aAAa,CAAC,CAAC;IACzD,IAAIJ,UAAUC,SAAS,CAAC,CAAC,EAAEA,OAAO,EAAEX,QAAQe,cAAc,CAAC,CAAC;IAC5D,IAAIR,eAAeI,SAAS,CAAC,EAAEA,OAAO,EAAEX,QAAQgB,mBAAmB,CAAC,CAAC;IAErE,IAAI,CAACP,sBAAsB;QACzB,OAAOE;IACT;IAEA,IAAIA,OAAOM,MAAM,GAAG,IAAI;QACtB,MAAM,IAAIpB,SACR,CAAC,sFAAsF,EAAEc,OAAO,CAAC;IAErG;IACA,OAAOA;AACT,EAAC"}
|
package/src/index.ts
DELETED
@@ -1,156 +0,0 @@
|
|
1
|
-
import type { Payload } from 'payload'
|
2
|
-
import type { DatabaseAdapterObj } from 'payload/database'
|
3
|
-
|
4
|
-
import fs from 'fs'
|
5
|
-
import path from 'path'
|
6
|
-
import { createDatabaseAdapter } from 'payload/database'
|
7
|
-
|
8
|
-
import type { Args, PostgresAdapter } from './types.js'
|
9
|
-
|
10
|
-
import { connect } from './connect.js'
|
11
|
-
import { create } from './create.js'
|
12
|
-
import { createGlobal } from './createGlobal.js'
|
13
|
-
import { createGlobalVersion } from './createGlobalVersion.js'
|
14
|
-
import { createMigration } from './createMigration.js'
|
15
|
-
import { createVersion } from './createVersion.js'
|
16
|
-
import { deleteMany } from './deleteMany.js'
|
17
|
-
import { deleteOne } from './deleteOne.js'
|
18
|
-
import { deleteVersions } from './deleteVersions.js'
|
19
|
-
import { destroy } from './destroy.js'
|
20
|
-
import { find } from './find.js'
|
21
|
-
import { findGlobal } from './findGlobal.js'
|
22
|
-
import { findGlobalVersions } from './findGlobalVersions.js'
|
23
|
-
import { findOne } from './findOne.js'
|
24
|
-
import { findVersions } from './findVersions.js'
|
25
|
-
import { init } from './init.js'
|
26
|
-
import { migrate } from './migrate.js'
|
27
|
-
import { migrateDown } from './migrateDown.js'
|
28
|
-
import { migrateFresh } from './migrateFresh.js'
|
29
|
-
import { migrateRefresh } from './migrateRefresh.js'
|
30
|
-
import { migrateReset } from './migrateReset.js'
|
31
|
-
import { migrateStatus } from './migrateStatus.js'
|
32
|
-
import { queryDrafts } from './queryDrafts.js'
|
33
|
-
import { beginTransaction } from './transactions/beginTransaction.js'
|
34
|
-
import { commitTransaction } from './transactions/commitTransaction.js'
|
35
|
-
import { rollbackTransaction } from './transactions/rollbackTransaction.js'
|
36
|
-
import { updateOne } from './update.js'
|
37
|
-
import { updateGlobal } from './updateGlobal.js'
|
38
|
-
import { updateGlobalVersion } from './updateGlobalVersion.js'
|
39
|
-
import { updateVersion } from './updateVersion.js'
|
40
|
-
|
41
|
-
export type { MigrateDownArgs, MigrateUpArgs } from './types.js'
|
42
|
-
|
43
|
-
export { sql } from 'drizzle-orm'
|
44
|
-
|
45
|
-
export function postgresAdapter(args: Args): DatabaseAdapterObj<PostgresAdapter> {
|
46
|
-
function adapter({ payload }: { payload: Payload }) {
|
47
|
-
const migrationDir = findMigrationDir(args.migrationDir)
|
48
|
-
const idType = args.idType || 'serial'
|
49
|
-
|
50
|
-
return createDatabaseAdapter<PostgresAdapter>({
|
51
|
-
name: 'postgres',
|
52
|
-
|
53
|
-
// Postgres-specific
|
54
|
-
blockTableNames: {},
|
55
|
-
drizzle: undefined,
|
56
|
-
enums: {},
|
57
|
-
fieldConstraints: {},
|
58
|
-
idType,
|
59
|
-
localesSuffix: args.localesSuffix || '_locales',
|
60
|
-
logger: args.logger,
|
61
|
-
pgSchema: undefined,
|
62
|
-
pool: undefined,
|
63
|
-
poolOptions: args.pool,
|
64
|
-
push: args.push,
|
65
|
-
relations: {},
|
66
|
-
relationshipsSuffix: args.relationshipsSuffix || '_rels',
|
67
|
-
schema: {},
|
68
|
-
schemaName: args.schemaName,
|
69
|
-
sessions: {},
|
70
|
-
tables: {},
|
71
|
-
versionsSuffix: args.versionsSuffix || '_v',
|
72
|
-
|
73
|
-
// DatabaseAdapter
|
74
|
-
beginTransaction,
|
75
|
-
commitTransaction,
|
76
|
-
connect,
|
77
|
-
create,
|
78
|
-
createGlobal,
|
79
|
-
createGlobalVersion,
|
80
|
-
createMigration,
|
81
|
-
createVersion,
|
82
|
-
/**
|
83
|
-
* This represents how a default ID is treated in Payload as were a field type
|
84
|
-
*/
|
85
|
-
defaultIDType: idType === 'serial' ? 'number' : 'text',
|
86
|
-
deleteMany,
|
87
|
-
deleteOne,
|
88
|
-
deleteVersions,
|
89
|
-
destroy,
|
90
|
-
find,
|
91
|
-
findGlobal,
|
92
|
-
findGlobalVersions,
|
93
|
-
findOne,
|
94
|
-
findVersions,
|
95
|
-
init,
|
96
|
-
migrate,
|
97
|
-
migrateDown,
|
98
|
-
migrateFresh,
|
99
|
-
migrateRefresh,
|
100
|
-
migrateReset,
|
101
|
-
migrateStatus,
|
102
|
-
migrationDir,
|
103
|
-
payload,
|
104
|
-
queryDrafts,
|
105
|
-
rollbackTransaction,
|
106
|
-
updateGlobal,
|
107
|
-
updateGlobalVersion,
|
108
|
-
updateOne,
|
109
|
-
updateVersion,
|
110
|
-
})
|
111
|
-
}
|
112
|
-
|
113
|
-
return {
|
114
|
-
defaultIDType: 'number',
|
115
|
-
init: adapter,
|
116
|
-
}
|
117
|
-
}
|
118
|
-
|
119
|
-
/**
|
120
|
-
* Attempt to find migrations directory.
|
121
|
-
*
|
122
|
-
* Checks for the following directories in order:
|
123
|
-
* - `migrationDir` argument from Payload config
|
124
|
-
* - `src/migrations`
|
125
|
-
* - `dist/migrations`
|
126
|
-
* - `migrations`
|
127
|
-
*
|
128
|
-
* Defaults to `src/migrations`
|
129
|
-
*
|
130
|
-
* @param migrationDir
|
131
|
-
* @returns
|
132
|
-
*/
|
133
|
-
function findMigrationDir(migrationDir?: string): string {
|
134
|
-
const cwd = process.cwd()
|
135
|
-
const srcDir = path.resolve(cwd, 'src/migrations')
|
136
|
-
const distDir = path.resolve(cwd, 'dist/migrations')
|
137
|
-
const relativeMigrations = path.resolve(cwd, 'migrations')
|
138
|
-
|
139
|
-
// Use arg if provided
|
140
|
-
if (migrationDir) return migrationDir
|
141
|
-
|
142
|
-
// Check other common locations
|
143
|
-
if (fs.existsSync(srcDir)) {
|
144
|
-
return srcDir
|
145
|
-
}
|
146
|
-
|
147
|
-
if (fs.existsSync(distDir)) {
|
148
|
-
return distDir
|
149
|
-
}
|
150
|
-
|
151
|
-
if (fs.existsSync(relativeMigrations)) {
|
152
|
-
return relativeMigrations
|
153
|
-
}
|
154
|
-
|
155
|
-
return srcDir
|
156
|
-
}
|