@payloadcms/drizzle 3.94.0 → 3.94.1
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.
- package/dist/schema/build.d.ts.map +1 -1
- package/dist/schema/build.js +51 -2
- package/dist/schema/build.js.map +1 -1
- package/dist/schema/buildRawSchema.spec.js +245 -10
- package/dist/schema/buildRawSchema.spec.js.map +1 -1
- package/dist/schema/traverseFields.d.ts.map +1 -1
- package/dist/schema/traverseFields.js +71 -14
- package/dist/schema/traverseFields.js.map +1 -1
- package/dist/transform/write/array.d.ts +3 -2
- package/dist/transform/write/array.d.ts.map +1 -1
- package/dist/transform/write/array.js +2 -1
- package/dist/transform/write/array.js.map +1 -1
- package/dist/transform/write/blocks.d.ts +3 -2
- package/dist/transform/write/blocks.d.ts.map +1 -1
- package/dist/transform/write/blocks.js +2 -1
- package/dist/transform/write/blocks.js.map +1 -1
- package/dist/transform/write/index.d.ts.map +1 -1
- package/dist/transform/write/index.js +2 -0
- package/dist/transform/write/index.js.map +1 -1
- package/dist/transform/write/traverseFields.d.ts +2 -1
- package/dist/transform/write/traverseFields.d.ts.map +1 -1
- package/dist/transform/write/traverseFields.js +27 -1
- package/dist/transform/write/traverseFields.js.map +1 -1
- package/dist/transform/write/types.d.ts +10 -0
- package/dist/transform/write/types.d.ts.map +1 -1
- package/dist/transform/write/types.js.map +1 -1
- package/dist/upsertRow/deleteExistingRowsByPath.d.ts +6 -1
- package/dist/upsertRow/deleteExistingRowsByPath.d.ts.map +1 -1
- package/dist/upsertRow/deleteExistingRowsByPath.js +21 -3
- package/dist/upsertRow/deleteExistingRowsByPath.js.map +1 -1
- package/dist/upsertRow/index.d.ts.map +1 -1
- package/dist/upsertRow/index.js +3 -0
- package/dist/upsertRow/index.js.map +1 -1
- package/dist/utilities/createSchemaGenerator.d.ts.map +1 -1
- package/dist/utilities/createSchemaGenerator.js +17 -1
- package/dist/utilities/createSchemaGenerator.js.map +1 -1
- package/dist/utilities/createSchemaGenerator.spec.js +172 -0
- package/dist/utilities/createSchemaGenerator.spec.js.map +1 -0
- package/dist/utilities/fitIdentifierLength.d.ts +25 -0
- package/dist/utilities/fitIdentifierLength.d.ts.map +1 -0
- package/dist/utilities/fitIdentifierLength.js +35 -0
- package/dist/utilities/fitIdentifierLength.js.map +1 -0
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/upsertRow/index.ts"],"sourcesContent":["import type { SQL, Table } from 'drizzle-orm'\nimport type { LibSQLDatabase } from 'drizzle-orm/libsql'\nimport type { SelectedFields } from 'drizzle-orm/sqlite-core'\nimport type { TypeWithID } from 'payload'\n\nimport { and, desc, eq, getTableColumns, 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<null | 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 const updateWhere = where\n ? and(eq(adapter.tables[tableName].id, id), where)\n : eq(adapter.tables[tableName].id, id)\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.update(adapter.tables[tableName]).set(row).where(updateWhere)\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 = updateWhere\n\n const doc = await db.query[tableName].findFirst(findManyArgs)\n\n if (!doc) {\n return null\n }\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 returningFields = buildReturningFields({\n findManyArgs,\n table: adapter.tables[tableName],\n })\n\n const docs = await drizzle\n .update(adapter.tables[tableName])\n .set(row)\n .where(updateWhere)\n .returning(returningFields)\n\n if (!docs[0]) {\n return null\n }\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 const docs = await drizzle\n .update(adapter.tables[tableName])\n .set(row)\n .where(updateWhere)\n .returning({\n id: adapter.tables[tableName].id,\n })\n\n if (!docs[0]) {\n return null\n }\n\n insertedRow = docs[0]\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: where\n ? { set: rowToInsert.row, target, where }\n : { 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\n if (!insertedRow) {\n return null\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\n/**\n * Builds the `RETURNING` selection for the single-query update path so it yields the same shape as\n * `findFirst(findManyArgs)`: columns excluded by `findManyArgs.columns` are skipped and\n * `findManyArgs.extras` are included. Point columns rely on this - they are excluded as raw\n * columns and selected through an `ST_AsGeoJSON` extra instead.\n */\nfunction buildReturningFields({\n findManyArgs,\n table,\n}: {\n findManyArgs: ReturnType<typeof buildFindManyArgs>\n table: Table\n}): SelectedFields {\n const columns = findManyArgs.columns ?? {}\n const extras = (findManyArgs.extras ?? {}) as Record<string, SQL.Aliased>\n const hasIncludedColumns = Object.values(columns).some(Boolean)\n const returningFields: SelectedFields = {}\n\n if (hasIncludedColumns) {\n for (const [columnName, isIncluded] of Object.entries(columns)) {\n if (isIncluded) {\n returningFields[columnName] = table[columnName]\n }\n }\n } else {\n for (const [columnName, column] of Object.entries(getTableColumns(table))) {\n if (columns[columnName] !== false) {\n returningFields[columnName] = column\n }\n }\n }\n\n return Object.assign(returningFields, extras)\n}\n"],"names":["and","desc","eq","getTableColumns","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","updateWhere","tables","Object","keys","length","arrays","parentRows","uuidMap","updatedAt","hasDataToUpdate","update","set","findManyArgs","depth","findManyKeysLength","hasOnlyColumns","columns","doc","query","findFirst","config","payload","returningFields","buildReturningFields","table","docs","returning","error","rowToInsert","target","rowKeys","hasMainRowData","every","key","insert","onConflictDoUpdate","values","allowIDOnCreate","localesToInsert","relationsToInsert","textsToInsert","numbersToInsert","blocksToInsert","selectsToInsert","locales","entries","forEach","locale","localeRow","_parentID","_locale","push","relationships","relation","parent","texts","textRow","numbers","numberRow","selects","selectTableName","selectRows","blocks","blockRow","uuid","localeTableName","localesSuffix","localeTable","deleteWhere","relationshipsTableName","relationshipsSuffix","generalRelationshipDeletes","relationshipsToDelete","filter","rel","localeColumnName","parentColumnName","parentID","pathColumnName","rows","relationshipsToAppend","relationshipsToInsert","map","parentId","relationshipTable","rawTables","relationTo","value","conditions","parts","undefined","endsWith","column","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","extras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,GAAG/B,GAAGe,QAAQ2B,MAAM,CAACb,UAAU,CAACf,EAAE,EAAEqB,YAAYrB,EAAE;IAEpE,MAAM4C,MAAM,MAAMxC,GAAGyC,KAAK,CAAC9B,UAAU,CAAC+B,SAAS,CAACP;IAEhD,qCAAqC;IACrC,iBAAiB;IACjB,qCAAqC;IAErC,MAAMsH,SAAStK,UAAa;QAC1BU;QACA8C,QAAQ9C,QAAQ+C,OAAO,CAACD,MAAM;QAC9B5C,MAAMyC;QACNvC;QACAI,WAAW;QACXM;IACF;IAEA,OAAO8I;AACT,EAAC;AAED;;;;;CAKC,GACD,SAAS3G,qBAAqB,EAC5BX,YAAY,EACZY,KAAK,EAIN;IACC,MAAMR,UAAUJ,aAAaI,OAAO,IAAI,CAAC;IACzC,MAAMmH,SAAUvH,aAAauH,MAAM,IAAI,CAAC;IACxC,MAAMC,qBAAqBlI,OAAOkC,MAAM,CAACpB,SAASuF,IAAI,CAAC8B;IACvD,MAAM/G,kBAAkC,CAAC;IAEzC,IAAI8G,oBAAoB;QACtB,KAAK,MAAM,CAACE,YAAYC,WAAW,IAAIrI,OAAO2C,OAAO,CAAC7B,SAAU;YAC9D,IAAIuH,YAAY;gBACdjH,eAAe,CAACgH,WAAW,GAAG9G,KAAK,CAAC8G,WAAW;YACjD;QACF;IACF,OAAO;QACL,KAAK,MAAM,CAACA,YAAY1C,OAAO,IAAI1F,OAAO2C,OAAO,CAACrF,gBAAgBgE,QAAS;YACzE,IAAIR,OAAO,CAACsH,WAAW,KAAK,OAAO;gBACjChH,eAAe,CAACgH,WAAW,GAAG1C;YAChC;QACF;IACF;IAEA,OAAO1F,OAAOsI,MAAM,CAAClH,iBAAiB6G;AACxC"}
|
|
1
|
+
{"version":3,"sources":["../../src/upsertRow/index.ts"],"sourcesContent":["import type { SQL, Table } from 'drizzle-orm'\nimport type { LibSQLDatabase } from 'drizzle-orm/libsql'\nimport type { SelectedFields } from 'drizzle-orm/sqlite-core'\nimport type { TypeWithID } from 'payload'\n\nimport { and, desc, eq, getTableColumns, 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<null | 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 const updateWhere = where\n ? and(eq(adapter.tables[tableName].id, id), where)\n : eq(adapter.tables[tableName].id, id)\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.update(adapter.tables[tableName]).set(row).where(updateWhere)\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 = updateWhere\n\n const doc = await db.query[tableName].findFirst(findManyArgs)\n\n if (!doc) {\n return null\n }\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 returningFields = buildReturningFields({\n findManyArgs,\n table: adapter.tables[tableName],\n })\n\n const docs = await drizzle\n .update(adapter.tables[tableName])\n .set(row)\n .where(updateWhere)\n .returning(returningFields)\n\n if (!docs[0]) {\n return null\n }\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 const docs = await drizzle\n .update(adapter.tables[tableName])\n .set(row)\n .where(updateWhere)\n .returning({\n id: adapter.tables[tableName].id,\n })\n\n if (!docs[0]) {\n return null\n }\n\n insertedRow = docs[0]\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: where\n ? { set: rowToInsert.row, target, where }\n : { 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\n if (!insertedRow) {\n return null\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 pathPrefixesToDelete: rowToInsert.pathPrefixesToDelete,\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 pathPrefixesToDelete: rowToInsert.pathPrefixesToDelete,\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 pathPrefixesToDelete: rowToInsert.pathPrefixesToDelete,\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\n/**\n * Builds the `RETURNING` selection for the single-query update path so it yields the same shape as\n * `findFirst(findManyArgs)`: columns excluded by `findManyArgs.columns` are skipped and\n * `findManyArgs.extras` are included. Point columns rely on this - they are excluded as raw\n * columns and selected through an `ST_AsGeoJSON` extra instead.\n */\nfunction buildReturningFields({\n findManyArgs,\n table,\n}: {\n findManyArgs: ReturnType<typeof buildFindManyArgs>\n table: Table\n}): SelectedFields {\n const columns = findManyArgs.columns ?? {}\n const extras = (findManyArgs.extras ?? {}) as Record<string, SQL.Aliased>\n const hasIncludedColumns = Object.values(columns).some(Boolean)\n const returningFields: SelectedFields = {}\n\n if (hasIncludedColumns) {\n for (const [columnName, isIncluded] of Object.entries(columns)) {\n if (isIncluded) {\n returningFields[columnName] = table[columnName]\n }\n }\n } else {\n for (const [columnName, column] of Object.entries(getTableColumns(table))) {\n if (columns[columnName] !== false) {\n returningFields[columnName] = column\n }\n }\n }\n\n return Object.assign(returningFields, extras)\n}\n"],"names":["and","desc","eq","getTableColumns","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","updateWhere","tables","Object","keys","length","arrays","parentRows","uuidMap","updatedAt","hasDataToUpdate","update","set","findManyArgs","depth","findManyKeysLength","hasOnlyColumns","columns","doc","query","findFirst","config","payload","returningFields","buildReturningFields","table","docs","returning","error","rowToInsert","target","rowKeys","hasMainRowData","every","key","insert","onConflictDoUpdate","values","allowIDOnCreate","localesToInsert","relationsToInsert","textsToInsert","numbersToInsert","blocksToInsert","selectsToInsert","locales","entries","forEach","locale","localeRow","_parentID","_locale","push","relationships","relation","parent","texts","textRow","numbers","numberRow","selects","selectTableName","selectRows","blocks","blockRow","uuid","localeTableName","localesSuffix","localeTable","deleteWhere","relationshipsTableName","relationshipsSuffix","generalRelationshipDeletes","relationshipsToDelete","filter","rel","localeColumnName","parentColumnName","parentID","pathColumnName","pathPrefixesToDelete","rows","relationshipsToAppend","relationshipsToInsert","map","parentId","relationshipTable","rawTables","relationTo","value","conditions","parts","undefined","endsWith","column","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","extras","hasIncludedColumns","Boolean","columnName","isIncluded","assign"],"mappings":"AAKA,SAASA,GAAG,EAAEC,IAAI,EAAEC,EAAE,EAAEC,eAAe,EAAEC,MAAM,EAAEC,EAAE,QAAQ,cAAa;AAcxE,SAASC,iBAAiB,QAAQ,+BAA8B;AAChE,SAASC,SAAS,QAAQ,6BAA4B;AACtD,SAASC,iBAAiB,QAAQ,8BAA6B;AAC/D,SAASC,SAAS,QAAQ,iCAAgC;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,iBAAiB;IACjB,qCAAqC;IAErC,MAAMuH,SAASvK,UAAa;QAC1BU;QACA8C,QAAQ9C,QAAQ+C,OAAO,CAACD,MAAM;QAC9B5C,MAAMyC;QACNvC;QACAI,WAAW;QACXM;IACF;IAEA,OAAO+I;AACT,EAAC;AAED;;;;;CAKC,GACD,SAAS5G,qBAAqB,EAC5BX,YAAY,EACZY,KAAK,EAIN;IACC,MAAMR,UAAUJ,aAAaI,OAAO,IAAI,CAAC;IACzC,MAAMoH,SAAUxH,aAAawH,MAAM,IAAI,CAAC;IACxC,MAAMC,qBAAqBnI,OAAOkC,MAAM,CAACpB,SAASwF,IAAI,CAAC8B;IACvD,MAAMhH,kBAAkC,CAAC;IAEzC,IAAI+G,oBAAoB;QACtB,KAAK,MAAM,CAACE,YAAYC,WAAW,IAAItI,OAAO2C,OAAO,CAAC7B,SAAU;YAC9D,IAAIwH,YAAY;gBACdlH,eAAe,CAACiH,WAAW,GAAG/G,KAAK,CAAC+G,WAAW;YACjD;QACF;IACF,OAAO;QACL,KAAK,MAAM,CAACA,YAAY1C,OAAO,IAAI3F,OAAO2C,OAAO,CAACrF,gBAAgBgE,QAAS;YACzE,IAAIR,OAAO,CAACuH,WAAW,KAAK,OAAO;gBACjCjH,eAAe,CAACiH,WAAW,GAAG1C;YAChC;QACF;IACF;IAEA,OAAO3F,OAAOuI,MAAM,CAACnH,iBAAiB8G;AACxC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createSchemaGenerator.d.ts","sourceRoot":"","sources":["../../src/utilities/createSchemaGenerator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAM7C,OAAO,KAAK,EAAE,qBAAqB,EAAkB,MAAM,aAAa,CAAA;AAkCxE,eAAO,MAAM,qBAAqB,4GAO/B;IACD,qBAAqB,EAAE,qBAAqB,CAAA;IAC5C,iBAAiB,EAAE,MAAM,CAAA;IACzB,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,WAAW,EAAE,MAAM,CAAA;CACpB,KAAG,
|
|
1
|
+
{"version":3,"file":"createSchemaGenerator.d.ts","sourceRoot":"","sources":["../../src/utilities/createSchemaGenerator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAM7C,OAAO,KAAK,EAAE,qBAAqB,EAAkB,MAAM,aAAa,CAAA;AAkCxE,eAAO,MAAM,qBAAqB,4GAO/B;IACD,qBAAqB,EAAE,qBAAqB,CAAA;IAC5C,iBAAiB,EAAE,MAAM,CAAA;IACzB,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,WAAW,EAAE,MAAM,CAAA;CACpB,KAAG,cA6UH,CAAA"}
|
|
@@ -75,7 +75,15 @@ export const createSchemaGenerator = ({ columnToCodeConverter, corePackageSuffix
|
|
|
75
75
|
fkGraph[tableName].add(col.reference.table);
|
|
76
76
|
}
|
|
77
77
|
}
|
|
78
|
+
for(const fkKey in table.foreignKeys ?? {}){
|
|
79
|
+
for (const foreignColumn of table.foreignKeys[fkKey].foreignColumns){
|
|
80
|
+
if (foreignColumn.table !== tableName) {
|
|
81
|
+
fkGraph[tableName].add(foreignColumn.table);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
78
85
|
}
|
|
86
|
+
const extraConfigType = corePackageSuffix === 'pg-core' ? 'PgTableExtraConfigValue' : 'SQLiteTableExtraConfigValue';
|
|
79
87
|
const canReach = (from, target, visited)=>{
|
|
80
88
|
if (from === target) {
|
|
81
89
|
return true;
|
|
@@ -102,6 +110,14 @@ export const createSchemaGenerator = ({ columnToCodeConverter, corePackageSuffix
|
|
|
102
110
|
for(const tableName in this.rawTables){
|
|
103
111
|
const table = this.rawTables[tableName];
|
|
104
112
|
const extrasDeclarations = [];
|
|
113
|
+
/**
|
|
114
|
+
* A table-level foreign key to its own table, or to a table that points back at it, makes
|
|
115
|
+
* TypeScript infer the table's type from its own initializer (TS7022). An explicit return
|
|
116
|
+
* type on the extras callback breaks that cycle, like `AnyPgColumn` does for `.references()`.
|
|
117
|
+
*/ const extrasNeedReturnType = Object.values(table.foreignKeys ?? {}).some((foreignKey)=>foreignKey.foreignColumns.some((foreignColumn)=>foreignColumn.table === tableName || circularEdges.has(`${tableName}:${foreignColumn.table}`)));
|
|
118
|
+
if (extrasNeedReturnType) {
|
|
119
|
+
addImport(corePackage, `type ${extraConfigType}`);
|
|
120
|
+
}
|
|
105
121
|
if (table.indexes) {
|
|
106
122
|
for(const key in table.indexes){
|
|
107
123
|
const index = table.indexes[key];
|
|
@@ -139,7 +155,7 @@ ${Object.entries(table.columns).map(([key, column])=>` ${sanitizeObjectKey(key)
|
|
|
139
155
|
locales: this.payload.config.localization ? this.payload.config.localization.localeCodes : undefined,
|
|
140
156
|
tableKey: tableName
|
|
141
157
|
})},`).join('\n')}
|
|
142
|
-
}${extrasDeclarations.length ? `, (columns) => [
|
|
158
|
+
}${extrasDeclarations.length ? `, (columns)${extrasNeedReturnType ? `: ${extraConfigType}[]` : ''} => [
|
|
143
159
|
${extrasDeclarations.join(' ')}
|
|
144
160
|
]` : ''}
|
|
145
161
|
)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/createSchemaGenerator.ts"],"sourcesContent":["import type { GenerateSchema } from 'payload'\n\nimport { existsSync } from 'fs'\nimport { writeFile } from 'fs/promises'\nimport path from 'path'\n\nimport type { ColumnToCodeConverter, DrizzleAdapter } from '../types.js'\n\n/**\n * @example\n * console.log(sanitizeObjectKey(\"oneTwo\")); // oneTwo\n * console.log(sanitizeObjectKey(\"one-two\")); // 'one-two'\n * console.log(sanitizeObjectKey(\"_one$Two3\")); // _one$Two3\n * console.log(sanitizeObjectKey(\"3invalid\")); // '3invalid'\n */\nconst sanitizeObjectKey = (key: string) => {\n // Regular expression for a valid identifier\n const identifierRegex = /^[a-z_$][\\w$]*$/i\n if (identifierRegex.test(key)) {\n return key\n }\n\n return `'${key}'`\n}\n\n/**\n * @example\n * (columns default-valuesID) -> columns['default-valuesID']\n * (columns defaultValues) -> columns.defaultValues\n */\nconst accessProperty = (objName: string, key: string) => {\n const sanitized = sanitizeObjectKey(key)\n\n if (sanitized.startsWith(\"'\")) {\n return `${objName}[${sanitized}]`\n }\n\n return `${objName}.${key}`\n}\n\nexport const createSchemaGenerator = ({\n columnToCodeConverter,\n corePackageSuffix,\n defaultOutputFile,\n enumImport,\n schemaImport,\n tableImport,\n}: {\n columnToCodeConverter: ColumnToCodeConverter\n corePackageSuffix: string\n defaultOutputFile?: string\n enumImport?: string\n schemaImport?: string\n tableImport: string\n}): GenerateSchema => {\n return async function generateSchema(\n this: DrizzleAdapter,\n { log = true, outputFile = defaultOutputFile, prettify = true } = {},\n ) {\n const importDeclarations: Record<string, Set<string>> = {}\n\n const tableDeclarations: string[] = []\n const enumDeclarations: string[] = []\n const relationsDeclarations: string[] = []\n\n const addImport = (from: string, name: string) => {\n if (!importDeclarations[from]) {\n importDeclarations[from] = new Set()\n }\n\n importDeclarations[from].add(name)\n }\n\n const corePackage = `${this.packageName}/drizzle/${corePackageSuffix}`\n\n let schemaDeclaration: null | string = null\n\n if (this.schemaName) {\n addImport(corePackage, schemaImport)\n schemaDeclaration = `export const db_schema = ${schemaImport}('${this.schemaName}')`\n }\n\n const enumFn = this.schemaName ? `db_schema.enum` : enumImport\n\n const enumsList: string[] = []\n const addEnum = (name: string, options: string[]) => {\n if (enumsList.some((each) => each === name)) {\n return\n }\n enumsList.push(name)\n enumDeclarations.push(\n `export const ${name} = ${enumFn}('${name}', [${options.map((option) => `'${option}'`).join(', ')}])`,\n )\n }\n\n if (this.payload.config.localization && enumImport) {\n addEnum('enum__locales', this.payload.config.localization.localeCodes)\n }\n\n const tableFn = this.schemaName ? `db_schema.table` : tableImport\n\n if (!this.schemaName) {\n addImport(corePackage, tableImport)\n }\n\n addImport(corePackage, 'index')\n addImport(corePackage, 'uniqueIndex')\n addImport(corePackage, 'foreignKey')\n\n addImport(`${this.packageName}/drizzle`, 'sql')\n addImport(`${this.packageName}/drizzle`, 'relations')\n\n const fkGraph: Record<string, Set<string>> = {}\n\n for (const tableName in this.rawTables) {\n fkGraph[tableName] = new Set()\n const table = this.rawTables[tableName]\n\n for (const colKey in table.columns) {\n const col = table.columns[colKey]\n\n if (col.reference && col.reference.table !== tableName) {\n fkGraph[tableName].add(col.reference.table)\n }\n }\n }\n\n const canReach = (from: string, target: string, visited: Set<string>): boolean => {\n if (from === target) {\n return true\n }\n\n if (visited.has(from)) {\n return false\n }\n\n visited.add(from)\n\n for (const neighbor of fkGraph[from] ?? []) {\n if (canReach(neighbor, target, visited)) {\n return true\n }\n }\n\n return false\n }\n\n const circularEdges = new Set<string>()\n\n for (const tableA in fkGraph) {\n for (const tableB of fkGraph[tableA]) {\n if (canReach(tableB, tableA, new Set())) {\n circularEdges.add(`${tableA}:${tableB}`)\n }\n }\n }\n\n for (const tableName in this.rawTables) {\n const table = this.rawTables[tableName]\n\n const extrasDeclarations: string[] = []\n\n if (table.indexes) {\n for (const key in table.indexes) {\n const index = table.indexes[key]\n let indexDeclaration = `${index.unique ? 'uniqueIndex' : 'index'}('${index.name}')`\n indexDeclaration += `.on(${typeof index.on === 'string' ? `${accessProperty('columns', index.on)}` : `${index.on.map((on) => `${accessProperty('columns', on)}`).join(', ')}`}),`\n extrasDeclarations.push(indexDeclaration)\n }\n }\n\n if (table.foreignKeys) {\n for (const key in table.foreignKeys) {\n const foreignKey = table.foreignKeys[key]\n\n let foreignKeyDeclaration = `foreignKey({\n columns: [${foreignKey.columns.map((col) => `columns['${col}']`).join(', ')}],\n foreignColumns: [${foreignKey.foreignColumns.map((col) => `${accessProperty(col.table, col.name)}`).join(', ')}],\n name: '${foreignKey.name}'\n })`\n\n if (foreignKey.onDelete) {\n foreignKeyDeclaration += `.onDelete('${foreignKey.onDelete}')`\n }\n if (foreignKey.onUpdate) {\n foreignKeyDeclaration += `.onUpdate('${foreignKey.onDelete}')`\n }\n\n foreignKeyDeclaration += ','\n\n extrasDeclarations.push(foreignKeyDeclaration)\n }\n }\n\n const tableCode = `\nexport const ${tableName} = ${tableFn}('${tableName}', {\n${Object.entries(table.columns)\n .map(\n ([key, column]) =>\n ` ${sanitizeObjectKey(key)}: ${columnToCodeConverter({\n adapter: this,\n addEnum,\n addImport,\n circularEdges,\n column,\n locales: this.payload.config.localization\n ? this.payload.config.localization.localeCodes\n : undefined,\n tableKey: tableName,\n })},`,\n )\n .join('\\n')}\n}${\n extrasDeclarations.length\n ? `, (columns) => [\n ${extrasDeclarations.join(' ')}\n]`\n : ''\n }\n)\n`\n\n tableDeclarations.push(tableCode)\n }\n\n for (const tableName in this.rawRelations) {\n const relations = this.rawRelations[tableName]\n const properties: string[] = []\n\n for (const key in relations) {\n const relation = relations[key]\n let declaration: string\n\n if (relation.type === 'one') {\n declaration = `${sanitizeObjectKey(key)}: one(${relation.to}, {\n ${relation.fields.some((field) => field.table !== tableName) ? '// @ts-expect-error Drizzle TypeScript bug for ONE relationships with a field in different table' : ''}\n fields: [${relation.fields.map((field) => `${accessProperty(field.table, field.name)}`).join(', ')}],\n references: [${relation.references.map((col) => `${accessProperty(relation.to, col)}`).join(', ')}],\n ${relation.relationName ? `relationName: '${relation.relationName}',` : ''}\n }),`\n } else {\n declaration = `${sanitizeObjectKey(key)}: many(${relation.to}, {\n ${relation.relationName ? `relationName: '${relation.relationName}',` : ''}\n }),`\n }\n\n properties.push(declaration)\n }\n\n // beautify / lintify relations callback output, when no many for example, don't add it\n const args = []\n\n if (Object.values(relations).some((rel) => rel.type === 'one')) {\n args.push('one')\n }\n\n if (Object.values(relations).some((rel) => rel.type === 'many')) {\n args.push('many')\n }\n\n const arg = args.length ? `{ ${args.join(', ')} }` : ''\n\n const declaration = `export const relations_${tableName} = relations(${tableName}, (${arg}) => ({\n ${properties.join('\\n ')}\n }))`\n\n relationsDeclarations.push(declaration)\n }\n\n if (enumDeclarations.length && !this.schemaName) {\n addImport(corePackage, enumImport)\n }\n\n const importDeclarationsSanitized: string[] = []\n\n for (const moduleName in importDeclarations) {\n const moduleImports = importDeclarations[moduleName]\n\n importDeclarationsSanitized.push(\n `import { ${Array.from(moduleImports).join(', ')} } from '${moduleName}'`,\n )\n }\n\n const schemaType = `\ntype DatabaseSchema = {\n ${[\n this.schemaName ? 'db_schema' : null,\n ...enumsList,\n ...Object.keys(this.rawTables),\n ...Object.keys(this.rawRelations).map((table) => `relations_${table}`),\n ]\n .filter(Boolean)\n .map((name) => `${name}: typeof ${name}`)\n .join('\\n ')}\n}\n `\n\n const finalDeclaration = `\ndeclare module '${this.packageName}' {\n export interface GeneratedDatabaseSchema {\n schema: DatabaseSchema\n }\n}\n `\n\n const warning = `\n/* tslint:disable */\n/* eslint-disable */\n/**\n * This file was automatically generated by Payload.\n * DO NOT MODIFY IT BY HAND. Instead, modify your source Payload config,\n * and re-run \\`payload generate:db-schema\\` to regenerate this file.\n */\n`\n\n const importTypes = `import type {} from '${this.packageName}'`\n\n let code = [\n warning,\n importTypes,\n ...importDeclarationsSanitized,\n schemaDeclaration,\n ...enumDeclarations,\n ...tableDeclarations,\n ...relationsDeclarations,\n schemaType,\n finalDeclaration,\n ]\n .filter(Boolean)\n .join('\\n')\n\n if (!outputFile) {\n const cwd = process.cwd()\n const srcDir = path.resolve(cwd, 'src')\n\n if (existsSync(srcDir)) {\n outputFile = path.resolve(srcDir, 'payload-generated-schema.ts')\n } else {\n outputFile = path.resolve(cwd, 'payload-generated-schema.ts')\n }\n }\n\n if (prettify) {\n try {\n const prettier = await eval('import(\"prettier\")')\n const configPath = await prettier.resolveConfigFile()\n const config = configPath ? await prettier.resolveConfig(configPath) : {}\n code = await prettier.format(code, { ...config, parser: 'typescript' })\n } catch {\n /* empty */\n }\n }\n\n await writeFile(outputFile, code, 'utf-8')\n\n if (log) {\n this.payload.logger.info(`Written ${outputFile}`)\n }\n }\n}\n"],"names":["existsSync","writeFile","path","sanitizeObjectKey","key","identifierRegex","test","accessProperty","objName","sanitized","startsWith","createSchemaGenerator","columnToCodeConverter","corePackageSuffix","defaultOutputFile","enumImport","schemaImport","tableImport","generateSchema","log","outputFile","prettify","importDeclarations","tableDeclarations","enumDeclarations","relationsDeclarations","addImport","from","name","Set","add","corePackage","packageName","schemaDeclaration","schemaName","enumFn","enumsList","addEnum","options","some","each","push","map","option","join","payload","config","localization","localeCodes","tableFn","fkGraph","tableName","rawTables","table","colKey","columns","col","reference","canReach","target","visited","has","neighbor","circularEdges","tableA","tableB","extrasDeclarations","indexes","index","indexDeclaration","unique","on","foreignKeys","foreignKey","foreignKeyDeclaration","foreignColumns","onDelete","onUpdate","tableCode","Object","entries","column","adapter","locales","undefined","tableKey","length","rawRelations","relations","properties","relation","declaration","type","to","fields","field","references","relationName","args","values","rel","arg","importDeclarationsSanitized","moduleName","moduleImports","Array","schemaType","keys","filter","Boolean","finalDeclaration","warning","importTypes","code","cwd","process","srcDir","resolve","prettier","eval","configPath","resolveConfigFile","resolveConfig","format","parser","logger","info"],"mappings":"AAEA,SAASA,UAAU,QAAQ,KAAI;AAC/B,SAASC,SAAS,QAAQ,cAAa;AACvC,OAAOC,UAAU,OAAM;AAIvB;;;;;;CAMC,GACD,MAAMC,oBAAoB,CAACC;IACzB,4CAA4C;IAC5C,MAAMC,kBAAkB;IACxB,IAAIA,gBAAgBC,IAAI,CAACF,MAAM;QAC7B,OAAOA;IACT;IAEA,OAAO,CAAC,CAAC,EAAEA,IAAI,CAAC,CAAC;AACnB;AAEA;;;;CAIC,GACD,MAAMG,iBAAiB,CAACC,SAAiBJ;IACvC,MAAMK,YAAYN,kBAAkBC;IAEpC,IAAIK,UAAUC,UAAU,CAAC,MAAM;QAC7B,OAAO,GAAGF,QAAQ,CAAC,EAAEC,UAAU,CAA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qBAAqB,EAAE,IAAI,CAAChF,WAAW,CAAC,CAAC,CAAC;QAE/D,IAAIiF,OAAO;YACTF;YACAC;eACGV;YACHrE;eACGT;eACAD;eACAE;YACHiF;YACAI;SACD,CACEF,MAAM,CAACC,SACPjE,IAAI,CAAC;QAER,IAAI,CAACxB,YAAY;YACf,MAAM8F,MAAMC,QAAQD,GAAG;YACvB,MAAME,SAASlH,KAAKmH,OAAO,CAACH,KAAK;YAEjC,IAAIlH,WAAWoH,SAAS;gBACtBhG,aAAalB,KAAKmH,OAAO,CAACD,QAAQ;YACpC,OAAO;gBACLhG,aAAalB,KAAKmH,OAAO,CAACH,KAAK;YACjC;QACF;QAEA,IAAI7F,UAAU;YACZ,IAAI;gBACF,MAAMiG,WAAW,MAAMC,KAAK;gBAC5B,MAAMC,aAAa,MAAMF,SAASG,iBAAiB;gBACnD,MAAM3E,SAAS0E,aAAa,MAAMF,SAASI,aAAa,CAACF,cAAc,CAAC;gBACxEP,OAAO,MAAMK,SAASK,MAAM,CAACV,MAAM;oBAAE,GAAGnE,MAAM;oBAAE8E,QAAQ;gBAAa;YACvE,EAAE,OAAM;YACN,SAAS,GACX;QACF;QAEA,MAAM3H,UAAUmB,YAAY6F,MAAM;QAElC,IAAI9F,KAAK;YACP,IAAI,CAAC0B,OAAO,CAACgF,MAAM,CAACC,IAAI,CAAC,CAAC,QAAQ,EAAE1G,YAAY;QAClD;IACF;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/createSchemaGenerator.ts"],"sourcesContent":["import type { GenerateSchema } from 'payload'\n\nimport { existsSync } from 'fs'\nimport { writeFile } from 'fs/promises'\nimport path from 'path'\n\nimport type { ColumnToCodeConverter, DrizzleAdapter } from '../types.js'\n\n/**\n * @example\n * console.log(sanitizeObjectKey(\"oneTwo\")); // oneTwo\n * console.log(sanitizeObjectKey(\"one-two\")); // 'one-two'\n * console.log(sanitizeObjectKey(\"_one$Two3\")); // _one$Two3\n * console.log(sanitizeObjectKey(\"3invalid\")); // '3invalid'\n */\nconst sanitizeObjectKey = (key: string) => {\n // Regular expression for a valid identifier\n const identifierRegex = /^[a-z_$][\\w$]*$/i\n if (identifierRegex.test(key)) {\n return key\n }\n\n return `'${key}'`\n}\n\n/**\n * @example\n * (columns default-valuesID) -> columns['default-valuesID']\n * (columns defaultValues) -> columns.defaultValues\n */\nconst accessProperty = (objName: string, key: string) => {\n const sanitized = sanitizeObjectKey(key)\n\n if (sanitized.startsWith(\"'\")) {\n return `${objName}[${sanitized}]`\n }\n\n return `${objName}.${key}`\n}\n\nexport const createSchemaGenerator = ({\n columnToCodeConverter,\n corePackageSuffix,\n defaultOutputFile,\n enumImport,\n schemaImport,\n tableImport,\n}: {\n columnToCodeConverter: ColumnToCodeConverter\n corePackageSuffix: string\n defaultOutputFile?: string\n enumImport?: string\n schemaImport?: string\n tableImport: string\n}): GenerateSchema => {\n return async function generateSchema(\n this: DrizzleAdapter,\n { log = true, outputFile = defaultOutputFile, prettify = true } = {},\n ) {\n const importDeclarations: Record<string, Set<string>> = {}\n\n const tableDeclarations: string[] = []\n const enumDeclarations: string[] = []\n const relationsDeclarations: string[] = []\n\n const addImport = (from: string, name: string) => {\n if (!importDeclarations[from]) {\n importDeclarations[from] = new Set()\n }\n\n importDeclarations[from].add(name)\n }\n\n const corePackage = `${this.packageName}/drizzle/${corePackageSuffix}`\n\n let schemaDeclaration: null | string = null\n\n if (this.schemaName) {\n addImport(corePackage, schemaImport)\n schemaDeclaration = `export const db_schema = ${schemaImport}('${this.schemaName}')`\n }\n\n const enumFn = this.schemaName ? `db_schema.enum` : enumImport\n\n const enumsList: string[] = []\n const addEnum = (name: string, options: string[]) => {\n if (enumsList.some((each) => each === name)) {\n return\n }\n enumsList.push(name)\n enumDeclarations.push(\n `export const ${name} = ${enumFn}('${name}', [${options.map((option) => `'${option}'`).join(', ')}])`,\n )\n }\n\n if (this.payload.config.localization && enumImport) {\n addEnum('enum__locales', this.payload.config.localization.localeCodes)\n }\n\n const tableFn = this.schemaName ? `db_schema.table` : tableImport\n\n if (!this.schemaName) {\n addImport(corePackage, tableImport)\n }\n\n addImport(corePackage, 'index')\n addImport(corePackage, 'uniqueIndex')\n addImport(corePackage, 'foreignKey')\n\n addImport(`${this.packageName}/drizzle`, 'sql')\n addImport(`${this.packageName}/drizzle`, 'relations')\n\n const fkGraph: Record<string, Set<string>> = {}\n\n for (const tableName in this.rawTables) {\n fkGraph[tableName] = new Set()\n const table = this.rawTables[tableName]\n\n for (const colKey in table.columns) {\n const col = table.columns[colKey]\n\n if (col.reference && col.reference.table !== tableName) {\n fkGraph[tableName].add(col.reference.table)\n }\n }\n\n for (const fkKey in table.foreignKeys ?? {}) {\n for (const foreignColumn of table.foreignKeys[fkKey].foreignColumns) {\n if (foreignColumn.table !== tableName) {\n fkGraph[tableName].add(foreignColumn.table)\n }\n }\n }\n }\n\n const extraConfigType =\n corePackageSuffix === 'pg-core' ? 'PgTableExtraConfigValue' : 'SQLiteTableExtraConfigValue'\n\n const canReach = (from: string, target: string, visited: Set<string>): boolean => {\n if (from === target) {\n return true\n }\n\n if (visited.has(from)) {\n return false\n }\n\n visited.add(from)\n\n for (const neighbor of fkGraph[from] ?? []) {\n if (canReach(neighbor, target, visited)) {\n return true\n }\n }\n\n return false\n }\n\n const circularEdges = new Set<string>()\n\n for (const tableA in fkGraph) {\n for (const tableB of fkGraph[tableA]) {\n if (canReach(tableB, tableA, new Set())) {\n circularEdges.add(`${tableA}:${tableB}`)\n }\n }\n }\n\n for (const tableName in this.rawTables) {\n const table = this.rawTables[tableName]\n\n const extrasDeclarations: string[] = []\n\n /**\n * A table-level foreign key to its own table, or to a table that points back at it, makes\n * TypeScript infer the table's type from its own initializer (TS7022). An explicit return\n * type on the extras callback breaks that cycle, like `AnyPgColumn` does for `.references()`.\n */\n const extrasNeedReturnType = Object.values(table.foreignKeys ?? {}).some((foreignKey) =>\n foreignKey.foreignColumns.some(\n (foreignColumn) =>\n foreignColumn.table === tableName ||\n circularEdges.has(`${tableName}:${foreignColumn.table}`),\n ),\n )\n\n if (extrasNeedReturnType) {\n addImport(corePackage, `type ${extraConfigType}`)\n }\n\n if (table.indexes) {\n for (const key in table.indexes) {\n const index = table.indexes[key]\n let indexDeclaration = `${index.unique ? 'uniqueIndex' : 'index'}('${index.name}')`\n indexDeclaration += `.on(${typeof index.on === 'string' ? `${accessProperty('columns', index.on)}` : `${index.on.map((on) => `${accessProperty('columns', on)}`).join(', ')}`}),`\n extrasDeclarations.push(indexDeclaration)\n }\n }\n\n if (table.foreignKeys) {\n for (const key in table.foreignKeys) {\n const foreignKey = table.foreignKeys[key]\n\n let foreignKeyDeclaration = `foreignKey({\n columns: [${foreignKey.columns.map((col) => `columns['${col}']`).join(', ')}],\n foreignColumns: [${foreignKey.foreignColumns.map((col) => `${accessProperty(col.table, col.name)}`).join(', ')}],\n name: '${foreignKey.name}'\n })`\n\n if (foreignKey.onDelete) {\n foreignKeyDeclaration += `.onDelete('${foreignKey.onDelete}')`\n }\n if (foreignKey.onUpdate) {\n foreignKeyDeclaration += `.onUpdate('${foreignKey.onDelete}')`\n }\n\n foreignKeyDeclaration += ','\n\n extrasDeclarations.push(foreignKeyDeclaration)\n }\n }\n\n const tableCode = `\nexport const ${tableName} = ${tableFn}('${tableName}', {\n${Object.entries(table.columns)\n .map(\n ([key, column]) =>\n ` ${sanitizeObjectKey(key)}: ${columnToCodeConverter({\n adapter: this,\n addEnum,\n addImport,\n circularEdges,\n column,\n locales: this.payload.config.localization\n ? this.payload.config.localization.localeCodes\n : undefined,\n tableKey: tableName,\n })},`,\n )\n .join('\\n')}\n}${\n extrasDeclarations.length\n ? `, (columns)${extrasNeedReturnType ? `: ${extraConfigType}[]` : ''} => [\n ${extrasDeclarations.join(' ')}\n]`\n : ''\n }\n)\n`\n\n tableDeclarations.push(tableCode)\n }\n\n for (const tableName in this.rawRelations) {\n const relations = this.rawRelations[tableName]\n const properties: string[] = []\n\n for (const key in relations) {\n const relation = relations[key]\n let declaration: string\n\n if (relation.type === 'one') {\n declaration = `${sanitizeObjectKey(key)}: one(${relation.to}, {\n ${relation.fields.some((field) => field.table !== tableName) ? '// @ts-expect-error Drizzle TypeScript bug for ONE relationships with a field in different table' : ''}\n fields: [${relation.fields.map((field) => `${accessProperty(field.table, field.name)}`).join(', ')}],\n references: [${relation.references.map((col) => `${accessProperty(relation.to, col)}`).join(', ')}],\n ${relation.relationName ? `relationName: '${relation.relationName}',` : ''}\n }),`\n } else {\n declaration = `${sanitizeObjectKey(key)}: many(${relation.to}, {\n ${relation.relationName ? `relationName: '${relation.relationName}',` : ''}\n }),`\n }\n\n properties.push(declaration)\n }\n\n // beautify / lintify relations callback output, when no many for example, don't add it\n const args = []\n\n if (Object.values(relations).some((rel) => rel.type === 'one')) {\n args.push('one')\n }\n\n if (Object.values(relations).some((rel) => rel.type === 'many')) {\n args.push('many')\n }\n\n const arg = args.length ? `{ ${args.join(', ')} }` : ''\n\n const declaration = `export const relations_${tableName} = relations(${tableName}, (${arg}) => ({\n ${properties.join('\\n ')}\n }))`\n\n relationsDeclarations.push(declaration)\n }\n\n if (enumDeclarations.length && !this.schemaName) {\n addImport(corePackage, enumImport)\n }\n\n const importDeclarationsSanitized: string[] = []\n\n for (const moduleName in importDeclarations) {\n const moduleImports = importDeclarations[moduleName]\n\n importDeclarationsSanitized.push(\n `import { ${Array.from(moduleImports).join(', ')} } from '${moduleName}'`,\n )\n }\n\n const schemaType = `\ntype DatabaseSchema = {\n ${[\n this.schemaName ? 'db_schema' : null,\n ...enumsList,\n ...Object.keys(this.rawTables),\n ...Object.keys(this.rawRelations).map((table) => `relations_${table}`),\n ]\n .filter(Boolean)\n .map((name) => `${name}: typeof ${name}`)\n .join('\\n ')}\n}\n `\n\n const finalDeclaration = `\ndeclare module '${this.packageName}' {\n export interface GeneratedDatabaseSchema {\n schema: DatabaseSchema\n }\n}\n `\n\n const warning = `\n/* tslint:disable */\n/* eslint-disable */\n/**\n * This file was automatically generated by Payload.\n * DO NOT MODIFY IT BY HAND. Instead, modify your source Payload config,\n * and re-run \\`payload generate:db-schema\\` to regenerate this file.\n */\n`\n\n const importTypes = `import type {} from '${this.packageName}'`\n\n let code = [\n warning,\n importTypes,\n ...importDeclarationsSanitized,\n schemaDeclaration,\n ...enumDeclarations,\n ...tableDeclarations,\n ...relationsDeclarations,\n schemaType,\n finalDeclaration,\n ]\n .filter(Boolean)\n .join('\\n')\n\n if (!outputFile) {\n const cwd = process.cwd()\n const srcDir = path.resolve(cwd, 'src')\n\n if (existsSync(srcDir)) {\n outputFile = path.resolve(srcDir, 'payload-generated-schema.ts')\n } else {\n outputFile = path.resolve(cwd, 'payload-generated-schema.ts')\n }\n }\n\n if (prettify) {\n try {\n const prettier = await eval('import(\"prettier\")')\n const configPath = await prettier.resolveConfigFile()\n const config = configPath ? await prettier.resolveConfig(configPath) : {}\n code = await prettier.format(code, { ...config, parser: 'typescript' })\n } catch {\n /* empty */\n }\n }\n\n await writeFile(outputFile, code, 'utf-8')\n\n if (log) {\n this.payload.logger.info(`Written ${outputFile}`)\n }\n }\n}\n"],"names":["existsSync","writeFile","path","sanitizeObjectKey","key","identifierRegex","test","accessProperty","objName","sanitized","startsWith","createSchemaGenerator","columnToCodeConverter","corePackageSuffix","defaultOutputFile","enumImport","schemaImport","tableImport","generateSchema","log","outputFile","prettify","importDeclarations","tableDeclarations","enumDeclarations","relationsDeclarations","addImport","from","name","Set","add","corePackage","packageName","schemaDeclaration","schemaName","enumFn","enumsList","addEnum","options","some","each","push","map","option","join","payload","config","localization","localeCodes","tableFn","fkGraph","tableName","rawTables","table","colKey","columns","col","reference","fkKey","foreignKeys","foreignColumn","foreignColumns","extraConfigType","canReach","target","visited","has","neighbor","circularEdges","tableA","tableB","extrasDeclarations","extrasNeedReturnType","Object","values","foreignKey","indexes","index","indexDeclaration","unique","on","foreignKeyDeclaration","onDelete","onUpdate","tableCode","entries","column","adapter","locales","undefined","tableKey","length","rawRelations","relations","properties","relation","declaration","type","to","fields","field","references","relationName","args","rel","arg","importDeclarationsSanitized","moduleName","moduleImports","Array","schemaType","keys","filter","Boolean","finalDeclaration","warning","importTypes","code","cwd","process","srcDir","resolve","prettier","eval","configPath","resolveConfigFile","resolveConfig","format","parser","logger","info"],"mappings":"AAEA,SAASA,UAAU,QAAQ,KAAI;AAC/B,SAASC,SAAS,QAAQ,cAAa;AACvC,OAAOC,UAAU,OAAM;AAIvB;;;;;;CAMC,GACD,MAAMC,oBAAoB,CAACC;IACzB,4CAA4C;IAC5C,MAAMC,kBAAkB;IACxB,IAAIA,gBAAgBC,IAAI,CAACF,MAAM;QAC7B,OAAOA;IACT;IAEA,OAAO,CAAC,CAAC,EAAEA,IAAI,CAAC,CAAC;AACnB;AAEA;;;;CAIC,GACD,MAAMG,iBAAiB,CAACC,SAAiBJ;IACvC,MAAMK,YAAYN,kBAAkBC;IAEpC,IAAIK,UAAUC,UAAU,CAAC,MAAM;QAC7B,OAAO,GAAGF,QAAQ,CAAC,EAAEC,UAAU,CAAC,CAAC;IACnC;IAEA,OAAO,GAAGD,QAAQ,CAAC,EAAEJ,KAAK;AAC5B;AAEA,OAAO,MAAMO,wBAAwB,CAAC,EACpCC,qBAAqB,EACrBC,iBAAiB,EACjBC,iBAAiB,EACjBC,UAAU,EACVC,YAAY,EACZC,WAAW,EAQZ;IACC,OAAO,eAAeC,eAEpB,EAAEC,MAAM,IAAI,EAAEC,aAAaN,iBAAiB,EAAEO,WAAW,IAAI,EAAE,GAAG,CAAC,CAAC;QAEpE,MAAMC,qBAAkD,CAAC;QAEzD,MAAMC,oBAA8B,EAAE;QACtC,MAAMC,mBAA6B,EAAE;QACrC,MAAMC,wBAAkC,EAAE;QAE1C,MAAMC,YAAY,CAACC,MAAcC;YAC/B,IAAI,CAACN,kBAAkB,CAACK,KAAK,EAAE;gBAC7BL,kBAAkB,CAACK,KAAK,GAAG,IAAIE;YACjC;YAEAP,kBAAkB,CAACK,KAAK,CAACG,GAAG,CAACF;QAC/B;QAEA,MAAMG,cAAc,GAAG,IA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AAC;;;;;IAK/B,CAAC;QAED,MAAMmF,UAAU,CAAC;;;;;;;;AAQrB,CAAC;QAEG,MAAMC,cAAc,CAAC,qBAAqB,EAAE,IAAI,CAACpF,WAAW,CAAC,CAAC,CAAC;QAE/D,IAAIqF,OAAO;YACTF;YACAC;eACGV;YACHzE;eACGT;eACAD;eACAE;YACHqF;YACAI;SACD,CACEF,MAAM,CAACC,SACPrE,IAAI,CAAC;QAER,IAAI,CAACxB,YAAY;YACf,MAAMkG,MAAMC,QAAQD,GAAG;YACvB,MAAME,SAAStH,KAAKuH,OAAO,CAACH,KAAK;YAEjC,IAAItH,WAAWwH,SAAS;gBACtBpG,aAAalB,KAAKuH,OAAO,CAACD,QAAQ;YACpC,OAAO;gBACLpG,aAAalB,KAAKuH,OAAO,CAACH,KAAK;YACjC;QACF;QAEA,IAAIjG,UAAU;YACZ,IAAI;gBACF,MAAMqG,WAAW,MAAMC,KAAK;gBAC5B,MAAMC,aAAa,MAAMF,SAASG,iBAAiB;gBACnD,MAAM/E,SAAS8E,aAAa,MAAMF,SAASI,aAAa,CAACF,cAAc,CAAC;gBACxEP,OAAO,MAAMK,SAASK,MAAM,CAACV,MAAM;oBAAE,GAAGvE,MAAM;oBAAEkF,QAAQ;gBAAa;YACvE,EAAE,OAAM;YACN,SAAS,GACX;QACF;QAEA,MAAM/H,UAAUmB,YAAYiG,MAAM;QAElC,IAAIlG,KAAK;YACP,IAAI,CAAC0B,OAAO,CAACoF,MAAM,CAACC,IAAI,CAAC,CAAC,QAAQ,EAAE9G,YAAY;QAClD;IACF;AACF,EAAC"}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { mkdtemp, readFile, rm } from 'fs/promises';
|
|
2
|
+
import { tmpdir } from 'os';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import { sanitizeConfig } from 'payload';
|
|
5
|
+
import { afterEach, describe, expect, it } from 'vitest';
|
|
6
|
+
import { columnToCodeConverter } from '../postgres/columnToCodeConverter.js';
|
|
7
|
+
import { setColumnID } from '../postgres/schema/setColumnID.js';
|
|
8
|
+
import { buildRawSchema } from '../schema/buildRawSchema.js';
|
|
9
|
+
import { createSchemaGenerator } from './createSchemaGenerator.js';
|
|
10
|
+
const generateSchema = createSchemaGenerator({
|
|
11
|
+
columnToCodeConverter,
|
|
12
|
+
corePackageSuffix: 'pg-core',
|
|
13
|
+
defaultOutputFile: undefined,
|
|
14
|
+
enumImport: 'pgEnum',
|
|
15
|
+
schemaImport: 'pgSchema',
|
|
16
|
+
tableImport: 'pgTable'
|
|
17
|
+
});
|
|
18
|
+
const createAdapter = async (config)=>{
|
|
19
|
+
const sanitized = await sanitizeConfig(config);
|
|
20
|
+
return {
|
|
21
|
+
name: 'postgres',
|
|
22
|
+
blocksAsJSON: false,
|
|
23
|
+
fieldConstraints: {},
|
|
24
|
+
idType: 'serial',
|
|
25
|
+
localesSuffix: '_locales',
|
|
26
|
+
packageName: '@payloadcms/db-postgres',
|
|
27
|
+
payload: {
|
|
28
|
+
blocks: {},
|
|
29
|
+
collections: Object.fromEntries(sanitized.collections.map((collection)=>[
|
|
30
|
+
collection.slug,
|
|
31
|
+
{
|
|
32
|
+
config: collection,
|
|
33
|
+
customIDType: undefined
|
|
34
|
+
}
|
|
35
|
+
])),
|
|
36
|
+
config: sanitized,
|
|
37
|
+
logger: {
|
|
38
|
+
warn: ()=>{}
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
rawRelations: {},
|
|
42
|
+
rawTables: {},
|
|
43
|
+
tableNameMap: new Map(),
|
|
44
|
+
versionsSuffix: '_versions'
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
let outputDir;
|
|
48
|
+
afterEach(async ()=>{
|
|
49
|
+
if (outputDir) {
|
|
50
|
+
await rm(outputDir, {
|
|
51
|
+
force: true,
|
|
52
|
+
recursive: true
|
|
53
|
+
});
|
|
54
|
+
outputDir = undefined;
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
const generate = async (adapter)=>{
|
|
58
|
+
buildRawSchema({
|
|
59
|
+
adapter,
|
|
60
|
+
setColumnID
|
|
61
|
+
});
|
|
62
|
+
outputDir = await mkdtemp(path.join(tmpdir(), 'payload-schema-'));
|
|
63
|
+
const outputFile = path.join(outputDir, 'schema.ts');
|
|
64
|
+
await generateSchema.call(adapter, {
|
|
65
|
+
log: false,
|
|
66
|
+
outputFile,
|
|
67
|
+
prettify: false
|
|
68
|
+
});
|
|
69
|
+
return readFile(outputFile, 'utf8');
|
|
70
|
+
};
|
|
71
|
+
const longGroupName = 'some_long_group_name_that_pushes_the_fk_over_the_limit';
|
|
72
|
+
describe('createSchemaGenerator', ()=>{
|
|
73
|
+
it('should type the extras callback when a promoted foreign key references its own table', async ()=>{
|
|
74
|
+
const adapter = await createAdapter({
|
|
75
|
+
collections: [
|
|
76
|
+
{
|
|
77
|
+
slug: 'pages',
|
|
78
|
+
fields: [
|
|
79
|
+
{
|
|
80
|
+
name: longGroupName,
|
|
81
|
+
type: 'group',
|
|
82
|
+
fields: [
|
|
83
|
+
{
|
|
84
|
+
name: 'parent',
|
|
85
|
+
type: 'relationship',
|
|
86
|
+
relationTo: 'pages'
|
|
87
|
+
}
|
|
88
|
+
]
|
|
89
|
+
}
|
|
90
|
+
],
|
|
91
|
+
timestamps: false,
|
|
92
|
+
versions: false
|
|
93
|
+
}
|
|
94
|
+
]
|
|
95
|
+
});
|
|
96
|
+
const schema = await generate(adapter);
|
|
97
|
+
expect(adapter.rawTables.pages.foreignKeys).toBeDefined();
|
|
98
|
+
expect(schema).toContain('type PgTableExtraConfigValue');
|
|
99
|
+
expect(schema).toMatch(/\(columns\): PgTableExtraConfigValue\[\] => \[/);
|
|
100
|
+
});
|
|
101
|
+
it('should treat promoted foreign keys as edges when detecting circular references', async ()=>{
|
|
102
|
+
const adapter = await createAdapter({
|
|
103
|
+
collections: [
|
|
104
|
+
{
|
|
105
|
+
slug: 'members',
|
|
106
|
+
fields: [
|
|
107
|
+
{
|
|
108
|
+
name: longGroupName,
|
|
109
|
+
type: 'group',
|
|
110
|
+
fields: [
|
|
111
|
+
{
|
|
112
|
+
name: 'avatar',
|
|
113
|
+
type: 'upload',
|
|
114
|
+
relationTo: 'media'
|
|
115
|
+
}
|
|
116
|
+
]
|
|
117
|
+
}
|
|
118
|
+
],
|
|
119
|
+
timestamps: false,
|
|
120
|
+
versions: false
|
|
121
|
+
},
|
|
122
|
+
{
|
|
123
|
+
slug: 'media',
|
|
124
|
+
fields: [
|
|
125
|
+
{
|
|
126
|
+
name: 'owner',
|
|
127
|
+
type: 'relationship',
|
|
128
|
+
relationTo: 'members'
|
|
129
|
+
}
|
|
130
|
+
],
|
|
131
|
+
timestamps: false,
|
|
132
|
+
versions: false,
|
|
133
|
+
upload: true
|
|
134
|
+
}
|
|
135
|
+
]
|
|
136
|
+
});
|
|
137
|
+
const schema = await generate(adapter);
|
|
138
|
+
// `members` -> `media` is promoted to a table-level foreign key, `media` -> `members` stays
|
|
139
|
+
// inline. Both sides of the cycle need an explicit type.
|
|
140
|
+
expect(adapter.rawTables.members.columns[`${longGroupName}_avatar`].reference).toBeUndefined();
|
|
141
|
+
expect(schema).toMatch(/\(\): AnyPgColumn => members\.id/);
|
|
142
|
+
expect(schema).toMatch(/\(columns\): PgTableExtraConfigValue\[\] => \[/);
|
|
143
|
+
});
|
|
144
|
+
it('should leave the extras callback untyped when no foreign key points back at the table', async ()=>{
|
|
145
|
+
const adapter = await createAdapter({
|
|
146
|
+
collections: [
|
|
147
|
+
{
|
|
148
|
+
slug: 'posts',
|
|
149
|
+
fields: [
|
|
150
|
+
{
|
|
151
|
+
name: 'tags',
|
|
152
|
+
type: 'array',
|
|
153
|
+
fields: [
|
|
154
|
+
{
|
|
155
|
+
name: 'tag',
|
|
156
|
+
type: 'text'
|
|
157
|
+
}
|
|
158
|
+
]
|
|
159
|
+
}
|
|
160
|
+
],
|
|
161
|
+
timestamps: false,
|
|
162
|
+
versions: false
|
|
163
|
+
}
|
|
164
|
+
]
|
|
165
|
+
});
|
|
166
|
+
const schema = await generate(adapter);
|
|
167
|
+
expect(schema).not.toContain('PgTableExtraConfigValue');
|
|
168
|
+
expect(schema).toContain('(columns) => [');
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
//# sourceMappingURL=createSchemaGenerator.spec.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/createSchemaGenerator.spec.ts"],"sourcesContent":["import type { Config } from 'payload'\n\nimport { mkdtemp, readFile, rm } from 'fs/promises'\nimport { tmpdir } from 'os'\nimport path from 'path'\nimport { sanitizeConfig } from 'payload'\nimport { afterEach, describe, expect, it } from 'vitest'\n\nimport type { DrizzleAdapter } from '../types.js'\n\nimport { columnToCodeConverter } from '../postgres/columnToCodeConverter.js'\nimport { setColumnID } from '../postgres/schema/setColumnID.js'\nimport { buildRawSchema } from '../schema/buildRawSchema.js'\nimport { createSchemaGenerator } from './createSchemaGenerator.js'\n\nconst generateSchema = createSchemaGenerator({\n columnToCodeConverter,\n corePackageSuffix: 'pg-core',\n defaultOutputFile: undefined,\n enumImport: 'pgEnum',\n schemaImport: 'pgSchema',\n tableImport: 'pgTable',\n})\n\nconst createAdapter = async (config: Config): Promise<DrizzleAdapter> => {\n const sanitized = await sanitizeConfig(config)\n\n return {\n name: 'postgres',\n blocksAsJSON: false,\n fieldConstraints: {},\n idType: 'serial',\n localesSuffix: '_locales',\n packageName: '@payloadcms/db-postgres',\n payload: {\n blocks: {},\n collections: Object.fromEntries(\n sanitized.collections.map((collection) => [\n collection.slug,\n { config: collection, customIDType: undefined },\n ]),\n ),\n config: sanitized,\n logger: { warn: () => {} },\n },\n rawRelations: {},\n rawTables: {},\n tableNameMap: new Map(),\n versionsSuffix: '_versions',\n } as unknown as DrizzleAdapter\n}\n\nlet outputDir: string | undefined\n\nafterEach(async () => {\n if (outputDir) {\n await rm(outputDir, { force: true, recursive: true })\n outputDir = undefined\n }\n})\n\nconst generate = async (adapter: DrizzleAdapter): Promise<string> => {\n buildRawSchema({ adapter, setColumnID })\n\n outputDir = await mkdtemp(path.join(tmpdir(), 'payload-schema-'))\n const outputFile = path.join(outputDir, 'schema.ts')\n\n await generateSchema.call(adapter, { log: false, outputFile, prettify: false })\n\n return readFile(outputFile, 'utf8')\n}\n\nconst longGroupName = 'some_long_group_name_that_pushes_the_fk_over_the_limit'\n\ndescribe('createSchemaGenerator', () => {\n it('should type the extras callback when a promoted foreign key references its own table', async () => {\n const adapter = await createAdapter({\n collections: [\n {\n slug: 'pages',\n fields: [\n {\n name: longGroupName,\n type: 'group',\n fields: [{ name: 'parent', type: 'relationship', relationTo: 'pages' }],\n },\n ],\n timestamps: false,\n versions: false,\n },\n ],\n } as Config)\n\n const schema = await generate(adapter)\n\n expect(adapter.rawTables.pages.foreignKeys).toBeDefined()\n expect(schema).toContain('type PgTableExtraConfigValue')\n expect(schema).toMatch(/\\(columns\\): PgTableExtraConfigValue\\[\\] => \\[/)\n })\n\n it('should treat promoted foreign keys as edges when detecting circular references', async () => {\n const adapter = await createAdapter({\n collections: [\n {\n slug: 'members',\n fields: [\n {\n name: longGroupName,\n type: 'group',\n fields: [{ name: 'avatar', type: 'upload', relationTo: 'media' }],\n },\n ],\n timestamps: false,\n versions: false,\n },\n {\n slug: 'media',\n fields: [{ name: 'owner', type: 'relationship', relationTo: 'members' }],\n timestamps: false,\n versions: false,\n upload: true,\n },\n ],\n } as Config)\n\n const schema = await generate(adapter)\n\n // `members` -> `media` is promoted to a table-level foreign key, `media` -> `members` stays\n // inline. Both sides of the cycle need an explicit type.\n expect(adapter.rawTables.members.columns[`${longGroupName}_avatar`].reference).toBeUndefined()\n expect(schema).toMatch(/\\(\\): AnyPgColumn => members\\.id/)\n expect(schema).toMatch(/\\(columns\\): PgTableExtraConfigValue\\[\\] => \\[/)\n })\n\n it('should leave the extras callback untyped when no foreign key points back at the table', async () => {\n const adapter = await createAdapter({\n collections: [\n {\n slug: 'posts',\n fields: [{ name: 'tags', type: 'array', fields: [{ name: 'tag', type: 'text' }] }],\n timestamps: false,\n versions: false,\n },\n ],\n } as Config)\n\n const schema = await generate(adapter)\n\n expect(schema).not.toContain('PgTableExtraConfigValue')\n expect(schema).toContain('(columns) => [')\n })\n})\n"],"names":["mkdtemp","readFile","rm","tmpdir","path","sanitizeConfig","afterEach","describe","expect","it","columnToCodeConverter","setColumnID","buildRawSchema","createSchemaGenerator","generateSchema","corePackageSuffix","defaultOutputFile","undefined","enumImport","schemaImport","tableImport","createAdapter","config","sanitized","name","blocksAsJSON","fieldConstraints","idType","localesSuffix","packageName","payload","blocks","collections","Object","fromEntries","map","collection","slug","customIDType","logger","warn","rawRelations","rawTables","tableNameMap","Map","versionsSuffix","outputDir","force","recursive","generate","adapter","join","outputFile","call","log","prettify","longGroupName","fields","type","relationTo","timestamps","versions","schema","pages","foreignKeys","toBeDefined","toContain","toMatch","upload","members","columns","reference","toBeUndefined","not"],"mappings":"AAEA,SAASA,OAAO,EAAEC,QAAQ,EAAEC,EAAE,QAAQ,cAAa;AACnD,SAASC,MAAM,QAAQ,KAAI;AAC3B,OAAOC,UAAU,OAAM;AACvB,SAASC,cAAc,QAAQ,UAAS;AACxC,SAASC,SAAS,EAAEC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAQ;AAIxD,SAASC,qBAAqB,QAAQ,uCAAsC;AAC5E,SAASC,WAAW,QAAQ,oCAAmC;AAC/D,SAASC,cAAc,QAAQ,8BAA6B;AAC5D,SAASC,qBAAqB,QAAQ,6BAA4B;AAElE,MAAMC,iBAAiBD,sBAAsB;IAC3CH;IACAK,mBAAmB;IACnBC,mBAAmBC;IACnBC,YAAY;IACZC,cAAc;IACdC,aAAa;AACf;AAEA,MAAMC,gBAAgB,OAAOC;IAC3B,MAAMC,YAAY,MAAMlB,eAAeiB;IAEvC,OAAO;QACLE,MAAM;QACNC,cAAc;QACdC,kBAAkB,CAAC;QACnBC,QAAQ;QACRC,eAAe;QACfC,aAAa;QACbC,SAAS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