@payloadcms/drizzle 4.0.0-internal.fec2230 → 4.0.0-internal.ff27d6e
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/count.d.ts.map +1 -1
- package/dist/count.js +25 -3
- package/dist/count.js.map +1 -1
- package/dist/countGlobalVersions.js +8 -3
- package/dist/countGlobalVersions.js.map +1 -1
- package/dist/countVersions.d.ts.map +1 -1
- package/dist/countVersions.js +29 -4
- package/dist/countVersions.js.map +1 -1
- package/dist/createGlobalVersion.d.ts.map +1 -1
- package/dist/createGlobalVersion.js +17 -2
- package/dist/createGlobalVersion.js.map +1 -1
- package/dist/createVersion.d.ts.map +1 -1
- package/dist/createVersion.js +12 -1
- package/dist/createVersion.js.map +1 -1
- package/dist/deleteBranchGlobal.d.ts +10 -0
- package/dist/deleteBranchGlobal.d.ts.map +1 -0
- package/dist/deleteBranchGlobal.js +27 -0
- package/dist/deleteBranchGlobal.js.map +1 -0
- package/dist/deleteOne.d.ts.map +1 -1
- package/dist/deleteOne.js +25 -1
- package/dist/deleteOne.js.map +1 -1
- package/dist/exports/postgres.d.ts +2 -1
- package/dist/exports/postgres.d.ts.map +1 -1
- package/dist/exports/postgres.js +2 -1
- package/dist/exports/postgres.js.map +1 -1
- package/dist/exports/sqlite.d.ts +2 -1
- package/dist/exports/sqlite.d.ts.map +1 -1
- package/dist/exports/sqlite.js +2 -1
- package/dist/exports/sqlite.js.map +1 -1
- package/dist/find/buildFindManyArgs.d.ts +3 -2
- package/dist/find/buildFindManyArgs.d.ts.map +1 -1
- package/dist/find/buildFindManyArgs.js +2 -1
- package/dist/find/buildFindManyArgs.js.map +1 -1
- package/dist/find/buildPolymorphicJoinQuery.d.ts +40 -0
- package/dist/find/buildPolymorphicJoinQuery.d.ts.map +1 -0
- package/dist/find/buildPolymorphicJoinQuery.js +163 -0
- package/dist/find/buildPolymorphicJoinQuery.js.map +1 -0
- package/dist/find/buildPolymorphicJoinWhere.d.ts +20 -0
- package/dist/find/buildPolymorphicJoinWhere.d.ts.map +1 -0
- package/dist/find/buildPolymorphicJoinWhere.js +301 -0
- package/dist/find/buildPolymorphicJoinWhere.js.map +1 -0
- package/dist/find/createPolymorphicJoinWherePlan.d.ts +38 -0
- package/dist/find/createPolymorphicJoinWherePlan.d.ts.map +1 -0
- package/dist/find/createPolymorphicJoinWherePlan.js +200 -0
- package/dist/find/createPolymorphicJoinWherePlan.js.map +1 -0
- package/dist/find/findMany.d.ts +6 -1
- package/dist/find/findMany.d.ts.map +1 -1
- package/dist/find/findMany.js +16 -3
- package/dist/find/findMany.js.map +1 -1
- package/dist/find/traverseFields.d.ts +3 -2
- package/dist/find/traverseFields.d.ts.map +1 -1
- package/dist/find/traverseFields.js +82 -198
- package/dist/find/traverseFields.js.map +1 -1
- package/dist/find.d.ts.map +1 -1
- package/dist/find.js +32 -4
- package/dist/find.js.map +1 -1
- package/dist/findDistinct.d.ts.map +1 -1
- package/dist/findDistinct.js +104 -8
- package/dist/findDistinct.js.map +1 -1
- package/dist/findGlobal.d.ts.map +1 -1
- package/dist/findGlobal.js +24 -5
- package/dist/findGlobal.js.map +1 -1
- package/dist/findGlobalVersions.js +8 -3
- package/dist/findGlobalVersions.js.map +1 -1
- package/dist/findOne.d.ts +1 -1
- package/dist/findOne.d.ts.map +1 -1
- package/dist/findOne.js +30 -3
- package/dist/findOne.js.map +1 -1
- package/dist/findVersions.d.ts.map +1 -1
- package/dist/findVersions.js +32 -5
- package/dist/findVersions.js.map +1 -1
- package/dist/index.d.ts +3 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -8
- package/dist/index.js.map +1 -1
- package/dist/migrate.d.ts.map +1 -1
- package/dist/migrate.js +6 -2
- package/dist/migrate.js.map +1 -1
- package/dist/migrateDown.d.ts.map +1 -1
- package/dist/migrateDown.js +5 -2
- package/dist/migrateDown.js.map +1 -1
- package/dist/migrateFresh.d.ts.map +1 -1
- package/dist/migrateFresh.js +5 -2
- package/dist/migrateFresh.js.map +1 -1
- package/dist/migrateRefresh.d.ts.map +1 -1
- package/dist/migrateRefresh.js +6 -2
- package/dist/migrateRefresh.js.map +1 -1
- package/dist/migrateReset.d.ts.map +1 -1
- package/dist/migrateReset.js +6 -2
- package/dist/migrateReset.js.map +1 -1
- package/dist/postgres/createJSONQuery/index.js +3 -3
- package/dist/postgres/createJSONQuery/index.js.map +1 -1
- package/dist/postgres/insert.d.ts.map +1 -1
- package/dist/postgres/insert.js +4 -2
- package/dist/postgres/insert.js.map +1 -1
- package/dist/postgres/predefinedMigrations/sizes-to-variants/index.d.ts +35 -0
- package/dist/postgres/predefinedMigrations/sizes-to-variants/index.d.ts.map +1 -0
- package/dist/postgres/predefinedMigrations/sizes-to-variants/index.js +185 -0
- package/dist/postgres/predefinedMigrations/sizes-to-variants/index.js.map +1 -0
- package/dist/postgres/predefinedMigrations/v2-v3/fetchAndResave/index.d.ts.map +1 -1
- package/dist/postgres/predefinedMigrations/v2-v3/fetchAndResave/index.js +8 -4
- package/dist/postgres/predefinedMigrations/v2-v3/fetchAndResave/index.js.map +1 -1
- package/dist/postgres/predefinedMigrations/v2-v3/index.js +1 -1
- package/dist/postgres/predefinedMigrations/v2-v3/index.js.map +1 -1
- package/dist/postgres/requireDrizzleKit.d.ts +4 -0
- package/dist/postgres/requireDrizzleKit.d.ts.map +1 -1
- package/dist/postgres/requireDrizzleKit.js +16 -10
- package/dist/postgres/requireDrizzleKit.js.map +1 -1
- package/dist/postgres/types.d.ts +4 -0
- package/dist/postgres/types.d.ts.map +1 -1
- package/dist/postgres/types.js.map +1 -1
- package/dist/queries/buildAndOrConditions.d.ts +3 -2
- package/dist/queries/buildAndOrConditions.d.ts.map +1 -1
- package/dist/queries/buildAndOrConditions.js +2 -1
- package/dist/queries/buildAndOrConditions.js.map +1 -1
- package/dist/queries/buildBranchVisibility.d.ts +11 -0
- package/dist/queries/buildBranchVisibility.d.ts.map +1 -0
- package/dist/queries/buildBranchVisibility.js +48 -0
- package/dist/queries/buildBranchVisibility.js.map +1 -0
- package/dist/queries/buildOrderBy.d.ts +3 -2
- package/dist/queries/buildOrderBy.d.ts.map +1 -1
- package/dist/queries/buildOrderBy.js +2 -1
- package/dist/queries/buildOrderBy.js.map +1 -1
- package/dist/queries/buildQuery.d.ts +3 -2
- package/dist/queries/buildQuery.d.ts.map +1 -1
- package/dist/queries/buildQuery.js +4 -2
- package/dist/queries/buildQuery.js.map +1 -1
- package/dist/queries/getTableColumnFromPath.d.ts +3 -2
- package/dist/queries/getTableColumnFromPath.d.ts.map +1 -1
- package/dist/queries/getTableColumnFromPath.js +176 -29
- package/dist/queries/getTableColumnFromPath.js.map +1 -1
- package/dist/queries/parseParams.d.ts +3 -2
- package/dist/queries/parseParams.d.ts.map +1 -1
- package/dist/queries/parseParams.js +63 -3
- package/dist/queries/parseParams.js.map +1 -1
- package/dist/queryDrafts.d.ts.map +1 -1
- package/dist/queryDrafts.js +27 -5
- package/dist/queryDrafts.js.map +1 -1
- package/dist/schema/build.d.ts.map +1 -1
- package/dist/schema/build.js +28 -20
- package/dist/schema/build.js.map +1 -1
- package/dist/sqlite/createJSONQuery/convertPathToJSONTraversal.js +3 -2
- package/dist/sqlite/createJSONQuery/convertPathToJSONTraversal.js.map +1 -1
- package/dist/sqlite/createJSONQuery/index.d.ts.map +1 -1
- package/dist/sqlite/createJSONQuery/index.js +6 -5
- package/dist/sqlite/createJSONQuery/index.js.map +1 -1
- package/dist/sqlite/createRequireDrizzleKit.d.ts +6 -0
- package/dist/sqlite/createRequireDrizzleKit.d.ts.map +1 -0
- package/dist/sqlite/createRequireDrizzleKit.js +15 -0
- package/dist/sqlite/createRequireDrizzleKit.js.map +1 -0
- package/dist/sqlite/execute.js.map +1 -1
- package/dist/sqlite/insert.d.ts.map +1 -1
- package/dist/sqlite/insert.js +9 -4
- package/dist/sqlite/insert.js.map +1 -1
- package/dist/sqlite/predefinedMigrations/sizes-to-variants/index.d.ts +15 -0
- package/dist/sqlite/predefinedMigrations/sizes-to-variants/index.d.ts.map +1 -0
- package/dist/sqlite/predefinedMigrations/sizes-to-variants/index.js +114 -0
- package/dist/sqlite/predefinedMigrations/sizes-to-variants/index.js.map +1 -0
- package/dist/sqlite/types.d.ts +4 -0
- package/dist/sqlite/types.d.ts.map +1 -1
- package/dist/sqlite/types.js.map +1 -1
- package/dist/transactions/beginTransaction.d.ts.map +1 -1
- package/dist/transactions/beginTransaction.js +13 -5
- package/dist/transactions/beginTransaction.js.map +1 -1
- package/dist/transactions/commitTransaction.d.ts.map +1 -1
- package/dist/transactions/commitTransaction.js +1 -5
- package/dist/transactions/commitTransaction.js.map +1 -1
- package/dist/transform/read/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 +48 -21
- package/dist/transform/write/traverseFields.js.map +1 -1
- package/dist/transform/write/types.d.ts +7 -0
- package/dist/transform/write/types.d.ts.map +1 -1
- package/dist/transform/write/types.js.map +1 -1
- package/dist/types.d.ts +3 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/updateGlobal.d.ts +5 -1
- package/dist/updateGlobal.d.ts.map +1 -1
- package/dist/updateGlobal.js +96 -4
- package/dist/updateGlobal.js.map +1 -1
- package/dist/updateOne.d.ts.map +1 -1
- package/dist/updateOne.js +93 -4
- package/dist/updateOne.js.map +1 -1
- package/dist/upsertBranchGlobalChange.d.ts +3 -0
- package/dist/upsertBranchGlobalChange.d.ts.map +1 -0
- package/dist/upsertBranchGlobalChange.js +35 -0
- package/dist/upsertBranchGlobalChange.js.map +1 -0
- package/dist/upsertRow/deleteExistingRowsByPath.d.ts.map +1 -1
- package/dist/upsertRow/deleteExistingRowsByPath.js +17 -12
- package/dist/upsertRow/deleteExistingRowsByPath.js.map +1 -1
- package/dist/upsertRow/index.d.ts +1 -1
- package/dist/upsertRow/index.d.ts.map +1 -1
- package/dist/upsertRow/index.js +156 -46
- package/dist/upsertRow/index.js.map +1 -1
- package/dist/upsertRow/types.d.ts +3 -0
- package/dist/upsertRow/types.d.ts.map +1 -1
- package/dist/upsertRow/types.js.map +1 -1
- package/dist/utilities/blocksToJsonMigrator.d.ts.map +1 -1
- package/dist/utilities/blocksToJsonMigrator.js +7 -18
- package/dist/utilities/blocksToJsonMigrator.js.map +1 -1
- package/dist/utilities/buildCreateMigration.js +1 -1
- package/dist/utilities/buildCreateMigration.js.map +1 -1
- package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.d.ts +15 -0
- package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.d.ts.map +1 -0
- package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.js +110 -0
- package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.js.map +1 -0
- package/dist/utilities/createSchemaGenerator.d.ts.map +1 -1
- package/dist/utilities/createSchemaGenerator.js +7 -12
- package/dist/utilities/createSchemaGenerator.js.map +1 -1
- package/dist/utilities/executeSchemaHooks.js +1 -1
- package/dist/utilities/executeSchemaHooks.js.map +1 -1
- package/dist/utilities/formatGeneratedFile.d.ts +10 -0
- package/dist/utilities/formatGeneratedFile.d.ts.map +1 -0
- package/dist/utilities/formatGeneratedFile.js +58 -0
- package/dist/utilities/formatGeneratedFile.js.map +1 -0
- package/dist/utilities/getSizesToVariantsRenames.d.ts +54 -0
- package/dist/utilities/getSizesToVariantsRenames.d.ts.map +1 -0
- package/dist/utilities/getSizesToVariantsRenames.js +251 -0
- package/dist/utilities/getSizesToVariantsRenames.js.map +1 -0
- package/dist/utilities/getTransaction.js.map +1 -1
- package/dist/utilities/parseJSONPathSegment.d.ts +9 -0
- package/dist/utilities/parseJSONPathSegment.d.ts.map +1 -0
- package/dist/utilities/parseJSONPathSegment.js +17 -0
- package/dist/utilities/parseJSONPathSegment.js.map +1 -0
- package/dist/utilities/pushDevSchema.js +1 -1
- package/dist/utilities/pushDevSchema.js.map +1 -1
- package/package.json +17 -19
- package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.spec.js +0 -91
- package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.spec.js.map +0 -1
- package/dist/postgres/query/postgresUnaccent.spec.js +0 -71
- package/dist/postgres/query/postgresUnaccent.spec.js.map +0 -1
- package/dist/queries/buildOperatorConstraint.spec.js +0 -348
- package/dist/queries/buildOperatorConstraint.spec.js.map +0 -1
- package/dist/queries/validateOperatorHandlers.spec.js +0 -142
- package/dist/queries/validateOperatorHandlers.spec.js.map +0 -1
- package/dist/schema/buildRawSchema.spec.js +0 -290
- package/dist/schema/buildRawSchema.spec.js.map +0 -1
- package/dist/sqlite/requireDrizzleKit.d.ts +0 -3
- package/dist/sqlite/requireDrizzleKit.d.ts.map +0 -1
- package/dist/sqlite/requireDrizzleKit.js +0 -12
- package/dist/sqlite/requireDrizzleKit.js.map +0 -1
- package/dist/upsertRow/handleUpsertError.spec.js +0 -42
- package/dist/upsertRow/handleUpsertError.spec.js.map +0 -1
- package/dist/utilities/checkTruncatedIdentifiers.spec.js +0 -301
- package/dist/utilities/checkTruncatedIdentifiers.spec.js.map +0 -1
- package/dist/utilities/isValidStringID.spec.js +0 -15
- package/dist/utilities/isValidStringID.spec.js.map +0 -1
- package/dist/utilities/validateIdentifierLength.spec.js +0 -19
- package/dist/utilities/validateIdentifierLength.spec.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/buildCreateMigration.ts"],"sourcesContent":["import type { DrizzleSnapshotJSON } from 'drizzle-kit/api'\nimport type { CreateMigration } from 'payload'\n\nimport fs from 'fs'\nimport path from 'path'\nimport { getPredefinedMigration, writeMigrationIndex } from 'payload'\nimport prompts from 'prompts'\n\nimport type { DrizzleAdapter } from '../types.js'\n\nimport { getMigrationTemplate } from './getMigrationTemplate.js'\n\nexport const buildCreateMigration = ({\n executeMethod,\n filename,\n sanitizeStatements,\n}: {\n executeMethod: string\n filename: string\n sanitizeStatements: (args: { sqlExecute: string; statements: string[] }) => string\n}): CreateMigration => {\n const dirname = path.dirname(filename)\n return async function createMigration(\n this: DrizzleAdapter,\n { file, forceAcceptWarning, migrationName, payload, shouldPrompt = true, skipEmpty },\n ) {\n const dir = payload.db.migrationDir\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir)\n }\n\n const { generateDrizzleJson, generateMigration, upSnapshot } = this.requireDrizzleKit()\n\n const drizzleJsonAfter = await generateDrizzleJson(this.schema)\n\n const [yyymmdd, hhmmss] = new Date().toISOString().split('T')\n const formattedDate = yyymmdd.replace(/\\D/g, '')\n const formattedTime = hhmmss.split('.')[0].replace(/\\D/g, '')\n let imports: string = ''\n let downSQL: string\n let upSQL: string\n\n const predefinedMigration = await getPredefinedMigration({\n dirname,\n file,\n migrationName,\n payload,\n })\n\n imports = predefinedMigration.imports\n downSQL = predefinedMigration.downSQL\n upSQL = predefinedMigration.upSQL\n\n const timestamp = `${formattedDate}_${formattedTime}`\n\n const name = migrationName || file?.split('/').slice(2).join('/')\n const fileName = `${timestamp}${name ? `_${name.replace(/\\W/g, '_')}` : ''}`\n\n const filePath = `${dir}/${fileName}`\n\n if (typeof predefinedMigration.dynamic === 'function') {\n const dynamicResult = await predefinedMigration.dynamic({ filePath, payload })\n\n if (dynamicResult.upSQL) {\n upSQL = dynamicResult.upSQL\n }\n\n if (dynamicResult.downSQL) {\n downSQL = dynamicResult.downSQL\n }\n\n if (dynamicResult.imports) {\n imports = dynamicResult.imports\n }\n }\n\n let drizzleJsonBefore = this.defaultDrizzleSnapshot as DrizzleSnapshotJSON\n\n if (this.schemaName) {\n drizzleJsonBefore.schemas = {\n [this.schemaName]: this.schemaName,\n }\n }\n\n if (!upSQL) {\n // Get latest migration snapshot\n const latestSnapshot = fs\n .readdirSync(dir)\n .filter((file) => file.endsWith('.json'))\n .sort()\n .reverse()?.[0]\n\n if (latestSnapshot) {\n drizzleJsonBefore = JSON.parse(fs.readFileSync(`${dir}/${latestSnapshot}`, 'utf8'))\n\n if (upSnapshot && drizzleJsonBefore.version < drizzleJsonAfter.version) {\n drizzleJsonBefore = upSnapshot(drizzleJsonBefore)\n }\n }\n\n payload.logger.info('Starting migration: generating UP statements...')\n const sqlStatementsUp = await generateMigration(drizzleJsonBefore, drizzleJsonAfter)\n\n payload.logger.info('Migration UP complete. Generating DOWN statements...')\n const sqlStatementsDown = await generateMigration(drizzleJsonAfter, drizzleJsonBefore)\n\n payload.logger.info('Migration DOWN statements generation complete.')\n\n const sqlExecute = `await db.${executeMethod}(` + 'sql`'\n\n if (sqlStatementsUp?.length) {\n upSQL = sanitizeStatements({ sqlExecute, statements: sqlStatementsUp })\n }\n if (sqlStatementsDown?.length) {\n downSQL = sanitizeStatements({ sqlExecute, statements: sqlStatementsDown })\n }\n\n if (!upSQL?.length && !downSQL?.length && !forceAcceptWarning) {\n if (skipEmpty || !shouldPrompt) {\n return { created: false }\n }\n\n const { confirm: shouldCreateBlankMigration } = await prompts({\n name: 'confirm',\n type: 'confirm',\n initial: false,\n message: 'No schema changes detected. Would you like to create a blank migration file?',\n })\n\n if (!shouldCreateBlankMigration) {\n return { created: false }\n }\n }\n\n // write schema\n fs.writeFileSync(`${filePath}.json`, JSON.stringify(drizzleJsonAfter, null, 2))\n }\n\n const data = getMigrationTemplate({\n downSQL: downSQL || ` // Migration code`,\n imports,\n packageName: payload.db.packageName,\n upSQL: upSQL || ` // Migration code`,\n })\n\n const fullPath = `${filePath}.ts`\n\n // write migration\n fs.writeFileSync(fullPath, data)\n\n writeMigrationIndex({ migrationsDir: payload.db.migrationDir })\n\n payload.logger.info({ msg: `Migration created at ${fullPath}` })\n\n return { created: true, path: fullPath }\n }\n}\n"],"names":["fs","path","getPredefinedMigration","writeMigrationIndex","prompts","getMigrationTemplate","buildCreateMigration","executeMethod","filename","sanitizeStatements","dirname","createMigration","file","forceAcceptWarning","migrationName","payload","shouldPrompt","skipEmpty","dir","db","migrationDir","existsSync","mkdirSync","generateDrizzleJson","generateMigration","upSnapshot","requireDrizzleKit","drizzleJsonAfter","schema","yyymmdd","hhmmss","Date","toISOString","split","formattedDate","replace","formattedTime","imports","downSQL","upSQL","predefinedMigration","timestamp","name","slice","join","fileName","filePath","dynamic","dynamicResult","drizzleJsonBefore","defaultDrizzleSnapshot","schemaName","schemas","latestSnapshot","readdirSync","filter","endsWith","sort","reverse","JSON","parse","readFileSync","version","logger","info","sqlStatementsUp","sqlStatementsDown","sqlExecute","length","statements","created","confirm","shouldCreateBlankMigration","type","initial","message","writeFileSync","stringify","data","packageName","fullPath","migrationsDir","msg"],"mappings":"AAGA,OAAOA,QAAQ,KAAI;AACnB,OAAOC,UAAU,OAAM;AACvB,SAASC,sBAAsB,EAAEC,mBAAmB,QAAQ,UAAS;AACrE,OAAOC,aAAa,UAAS;AAI7B,SAASC,oBAAoB,QAAQ,4BAA2B;AAEhE,OAAO,MAAMC,uBAAuB,CAAC,EACnCC,aAAa,EACbC,QAAQ,EACRC,kBAAkB,EAKnB;IACC,MAAMC,UAAUT,KAAKS,OAAO,CAACF;IAC7B,OAAO,eAAeG,gBAEpB,EAAEC,IAAI,EAAEC,kBAAkB,EAAEC,aAAa,EAAEC,OAAO,EAAEC,eAAe,IAAI,EAAEC,SAAS,EAAE;QAEpF,MAAMC,MAAMH,QAAQI,EAAE,CAACC,YAAY;QACnC,IAAI,CAACpB,GAAGqB,UAAU,CAACH,MAAM;YACvBlB,GAAGsB,SAAS,CAACJ;QACf;QAEA,MAAM,EAAEK,mBAAmB,EAAEC,iBAAiB,EAAEC,UAAU,EAAE,GAAG,IAAI,CAACC,iBAAiB;
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/buildCreateMigration.ts"],"sourcesContent":["import type { DrizzleSnapshotJSON } from 'drizzle-kit/api'\nimport type { CreateMigration } from 'payload'\n\nimport fs from 'fs'\nimport path from 'path'\nimport { getPredefinedMigration, writeMigrationIndex } from 'payload'\nimport prompts from 'prompts'\n\nimport type { DrizzleAdapter } from '../types.js'\n\nimport { getMigrationTemplate } from './getMigrationTemplate.js'\n\nexport const buildCreateMigration = ({\n executeMethod,\n filename,\n sanitizeStatements,\n}: {\n executeMethod: string\n filename: string\n sanitizeStatements: (args: { sqlExecute: string; statements: string[] }) => string\n}): CreateMigration => {\n const dirname = path.dirname(filename)\n return async function createMigration(\n this: DrizzleAdapter,\n { file, forceAcceptWarning, migrationName, payload, shouldPrompt = true, skipEmpty },\n ) {\n const dir = payload.db.migrationDir\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir)\n }\n\n const { generateDrizzleJson, generateMigration, upSnapshot } = await this.requireDrizzleKit()\n\n const drizzleJsonAfter = await generateDrizzleJson(this.schema)\n\n const [yyymmdd, hhmmss] = new Date().toISOString().split('T')\n const formattedDate = yyymmdd.replace(/\\D/g, '')\n const formattedTime = hhmmss.split('.')[0].replace(/\\D/g, '')\n let imports: string = ''\n let downSQL: string\n let upSQL: string\n\n const predefinedMigration = await getPredefinedMigration({\n dirname,\n file,\n migrationName,\n payload,\n })\n\n imports = predefinedMigration.imports\n downSQL = predefinedMigration.downSQL\n upSQL = predefinedMigration.upSQL\n\n const timestamp = `${formattedDate}_${formattedTime}`\n\n const name = migrationName || file?.split('/').slice(2).join('/')\n const fileName = `${timestamp}${name ? `_${name.replace(/\\W/g, '_')}` : ''}`\n\n const filePath = `${dir}/${fileName}`\n\n if (typeof predefinedMigration.dynamic === 'function') {\n const dynamicResult = await predefinedMigration.dynamic({ filePath, payload })\n\n if (dynamicResult.upSQL) {\n upSQL = dynamicResult.upSQL\n }\n\n if (dynamicResult.downSQL) {\n downSQL = dynamicResult.downSQL\n }\n\n if (dynamicResult.imports) {\n imports = dynamicResult.imports\n }\n }\n\n let drizzleJsonBefore = this.defaultDrizzleSnapshot as DrizzleSnapshotJSON\n\n if (this.schemaName) {\n drizzleJsonBefore.schemas = {\n [this.schemaName]: this.schemaName,\n }\n }\n\n if (!upSQL) {\n // Get latest migration snapshot\n const latestSnapshot = fs\n .readdirSync(dir)\n .filter((file) => file.endsWith('.json'))\n .sort()\n .reverse()?.[0]\n\n if (latestSnapshot) {\n drizzleJsonBefore = JSON.parse(fs.readFileSync(`${dir}/${latestSnapshot}`, 'utf8'))\n\n if (upSnapshot && drizzleJsonBefore.version < drizzleJsonAfter.version) {\n drizzleJsonBefore = upSnapshot(drizzleJsonBefore)\n }\n }\n\n payload.logger.info('Starting migration: generating UP statements...')\n const sqlStatementsUp = await generateMigration(drizzleJsonBefore, drizzleJsonAfter)\n\n payload.logger.info('Migration UP complete. Generating DOWN statements...')\n const sqlStatementsDown = await generateMigration(drizzleJsonAfter, drizzleJsonBefore)\n\n payload.logger.info('Migration DOWN statements generation complete.')\n\n const sqlExecute = `await db.${executeMethod}(` + 'sql`'\n\n if (sqlStatementsUp?.length) {\n upSQL = sanitizeStatements({ sqlExecute, statements: sqlStatementsUp })\n }\n if (sqlStatementsDown?.length) {\n downSQL = sanitizeStatements({ sqlExecute, statements: sqlStatementsDown })\n }\n\n if (!upSQL?.length && !downSQL?.length && !forceAcceptWarning) {\n if (skipEmpty || !shouldPrompt) {\n return { created: false }\n }\n\n const { confirm: shouldCreateBlankMigration } = await prompts({\n name: 'confirm',\n type: 'confirm',\n initial: false,\n message: 'No schema changes detected. Would you like to create a blank migration file?',\n })\n\n if (!shouldCreateBlankMigration) {\n return { created: false }\n }\n }\n\n // write schema\n fs.writeFileSync(`${filePath}.json`, JSON.stringify(drizzleJsonAfter, null, 2))\n }\n\n const data = getMigrationTemplate({\n downSQL: downSQL || ` // Migration code`,\n imports,\n packageName: payload.db.packageName,\n upSQL: upSQL || ` // Migration code`,\n })\n\n const fullPath = `${filePath}.ts`\n\n // write migration\n fs.writeFileSync(fullPath, data)\n\n writeMigrationIndex({ migrationsDir: payload.db.migrationDir })\n\n payload.logger.info({ msg: `Migration created at ${fullPath}` })\n\n return { created: true, path: fullPath }\n }\n}\n"],"names":["fs","path","getPredefinedMigration","writeMigrationIndex","prompts","getMigrationTemplate","buildCreateMigration","executeMethod","filename","sanitizeStatements","dirname","createMigration","file","forceAcceptWarning","migrationName","payload","shouldPrompt","skipEmpty","dir","db","migrationDir","existsSync","mkdirSync","generateDrizzleJson","generateMigration","upSnapshot","requireDrizzleKit","drizzleJsonAfter","schema","yyymmdd","hhmmss","Date","toISOString","split","formattedDate","replace","formattedTime","imports","downSQL","upSQL","predefinedMigration","timestamp","name","slice","join","fileName","filePath","dynamic","dynamicResult","drizzleJsonBefore","defaultDrizzleSnapshot","schemaName","schemas","latestSnapshot","readdirSync","filter","endsWith","sort","reverse","JSON","parse","readFileSync","version","logger","info","sqlStatementsUp","sqlStatementsDown","sqlExecute","length","statements","created","confirm","shouldCreateBlankMigration","type","initial","message","writeFileSync","stringify","data","packageName","fullPath","migrationsDir","msg"],"mappings":"AAGA,OAAOA,QAAQ,KAAI;AACnB,OAAOC,UAAU,OAAM;AACvB,SAASC,sBAAsB,EAAEC,mBAAmB,QAAQ,UAAS;AACrE,OAAOC,aAAa,UAAS;AAI7B,SAASC,oBAAoB,QAAQ,4BAA2B;AAEhE,OAAO,MAAMC,uBAAuB,CAAC,EACnCC,aAAa,EACbC,QAAQ,EACRC,kBAAkB,EAKnB;IACC,MAAMC,UAAUT,KAAKS,OAAO,CAACF;IAC7B,OAAO,eAAeG,gBAEpB,EAAEC,IAAI,EAAEC,kBAAkB,EAAEC,aAAa,EAAEC,OAAO,EAAEC,eAAe,IAAI,EAAEC,SAAS,EAAE;QAEpF,MAAMC,MAAMH,QAAQI,EAAE,CAACC,YAAY;QACnC,IAAI,CAACpB,GA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AAEsD,SAAS;oBAAM;gBAC1B;gBAEA,MAAM,EAAEC,SAASC,0BAA0B,EAAE,GAAG,MAAMpE,QAAQ;oBAC5DsC,MAAM;oBACN+B,MAAM;oBACNC,SAAS;oBACTC,SAAS;gBACX;gBAEA,IAAI,CAACH,4BAA4B;oBAC/B,OAAO;wBAAEF,SAAS;oBAAM;gBAC1B;YACF;YAEA,eAAe;YACftE,GAAG4E,aAAa,CAAC,GAAG9B,SAAS,KAAK,CAAC,EAAEa,KAAKkB,SAAS,CAAClD,kBAAkB,MAAM;QAC9E;QAEA,MAAMmD,OAAOzE,qBAAqB;YAChCiC,SAASA,WAAW,CAAC,mBAAmB,CAAC;YACzCD;YACA0C,aAAahE,QAAQI,EAAE,CAAC4D,WAAW;YACnCxC,OAAOA,SAAS,CAAC,mBAAmB,CAAC;QACvC;QAEA,MAAMyC,WAAW,GAAGlC,SAAS,GAAG,CAAC;QAEjC,kBAAkB;QAClB9C,GAAG4E,aAAa,CAACI,UAAUF;QAE3B3E,oBAAoB;YAAE8E,eAAelE,QAAQI,EAAE,CAACC,YAAY;QAAC;QAE7DL,QAAQgD,MAAM,CAACC,IAAI,CAAC;YAAEkB,KAAK,CAAC,qBAAqB,EAAEF,UAAU;QAAC;QAE9D,OAAO;YAAEV,SAAS;YAAMrE,MAAM+E;QAAS;IACzC;AACF,EAAC"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { DynamicMigrationTemplate } from 'payload';
|
|
2
|
+
/**
|
|
3
|
+
* Builds the `sizes-to-variants` predefined migration for a SQL adapter. The migration renames
|
|
4
|
+
* columns rather than letting drizzle-kit diff the schema (which would drop and re-add them,
|
|
5
|
+
* losing every stored image size).
|
|
6
|
+
*
|
|
7
|
+
* It also writes a schema snapshot: the project's previous snapshot with only these renames
|
|
8
|
+
* applied. The next generated migration then diffs from the renamed columns instead of dropping
|
|
9
|
+
* them, and still picks up every other schema change the upgrade brings. Without a previous
|
|
10
|
+
* snapshot (a project that has only ever used `push`) there's nothing to update, so none is written.
|
|
11
|
+
*/
|
|
12
|
+
export declare const buildDynamicPredefinedSizesToVariantsMigration: ({ packageName, }: {
|
|
13
|
+
packageName: string;
|
|
14
|
+
}) => DynamicMigrationTemplate;
|
|
15
|
+
//# sourceMappingURL=buildDynamicPredefinedSizesToVariantsMigration.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"buildDynamicPredefinedSizesToVariantsMigration.d.ts","sourceRoot":"","sources":["../../src/utilities/buildDynamicPredefinedSizesToVariantsMigration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,SAAS,CAAA;AA+BvD;;;;;;;;;GASG;AACH,eAAO,MAAM,8CAA8C,qBAExD;IACD,WAAW,EAAE,MAAM,CAAA;CACpB,KAAG,wBAoBH,CAAA"}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { randomUUID } from 'crypto';
|
|
2
|
+
import { readdirSync, readFileSync, writeFileSync } from 'fs';
|
|
3
|
+
import { findSizesToVariantsFieldCollision, getSizesToVariantsRenames } from './getSizesToVariantsRenames.js';
|
|
4
|
+
/**
|
|
5
|
+
* Builds the `sizes-to-variants` predefined migration for a SQL adapter. The migration renames
|
|
6
|
+
* columns rather than letting drizzle-kit diff the schema (which would drop and re-add them,
|
|
7
|
+
* losing every stored image size).
|
|
8
|
+
*
|
|
9
|
+
* It also writes a schema snapshot: the project's previous snapshot with only these renames
|
|
10
|
+
* applied. The next generated migration then diffs from the renamed columns instead of dropping
|
|
11
|
+
* them, and still picks up every other schema change the upgrade brings. Without a previous
|
|
12
|
+
* snapshot (a project that has only ever used `push`) there's nothing to update, so none is written.
|
|
13
|
+
*/ export const buildDynamicPredefinedSizesToVariantsMigration = ({ packageName })=>{
|
|
14
|
+
return async ({ filePath, payload })=>{
|
|
15
|
+
const adapter = payload.db;
|
|
16
|
+
const previousSnapshot = await readLatestSnapshot({
|
|
17
|
+
adapter
|
|
18
|
+
});
|
|
19
|
+
if (previousSnapshot) {
|
|
20
|
+
const renamedSnapshot = applySizesToVariantsRenames({
|
|
21
|
+
plan: getSizesToVariantsRenames({
|
|
22
|
+
adapter,
|
|
23
|
+
direction: 'up'
|
|
24
|
+
}),
|
|
25
|
+
snapshot: previousSnapshot
|
|
26
|
+
});
|
|
27
|
+
writeFileSync(`${filePath}.json`, JSON.stringify(renamedSnapshot, null, 2));
|
|
28
|
+
}
|
|
29
|
+
return {
|
|
30
|
+
downSQL: ` await migrateSizesToVariants({ db, direction: 'down', payload })`,
|
|
31
|
+
imports: `import { migrateSizesToVariants } from '${packageName}/migration-utils'`,
|
|
32
|
+
upSQL: ` await migrateSizesToVariants({ db, payload })`
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
/** The latest snapshot in the migrations directory, upgraded to drizzle-kit's current format. */ async function readLatestSnapshot({ adapter }) {
|
|
37
|
+
const dir = adapter.migrationDir;
|
|
38
|
+
const latestSnapshotFile = readdirSync(dir).filter((file)=>file.endsWith('.json')).sort().reverse()[0];
|
|
39
|
+
if (!latestSnapshotFile) {
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
const { generateDrizzleJson, upSnapshot } = await adapter.requireDrizzleKit();
|
|
43
|
+
const currentVersion = (await generateDrizzleJson(adapter.schema)).version;
|
|
44
|
+
const snapshot = JSON.parse(readFileSync(`${dir}/${latestSnapshotFile}`, 'utf8'));
|
|
45
|
+
return upSnapshot && snapshot.version < currentVersion ? upSnapshot(snapshot) : snapshot;
|
|
46
|
+
}
|
|
47
|
+
function applySizesToVariantsRenames({ plan, snapshot }) {
|
|
48
|
+
const renamed = structuredClone(snapshot);
|
|
49
|
+
for (const { columns, indexes, tableName } of plan){
|
|
50
|
+
const table = Object.values(renamed.tables).find(({ name })=>name === tableName);
|
|
51
|
+
if (!table) {
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
const existingColumns = new Set(Object.values(table.columns).map(({ name })=>name));
|
|
55
|
+
for (const { from, to } of columns){
|
|
56
|
+
if (existingColumns.has(from) && existingColumns.has(to)) {
|
|
57
|
+
throw new Error(`Cannot create the sizes-to-variants migration because snapshot table "${tableName}" contains both "${from}" and "${to}". Move or rename the existing destination data before creating this migration.`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const fieldCollision = findSizesToVariantsFieldCollision({
|
|
61
|
+
columns,
|
|
62
|
+
existingColumns
|
|
63
|
+
});
|
|
64
|
+
if (fieldCollision) {
|
|
65
|
+
throw new Error(`Cannot create the sizes-to-variants migration because snapshot table "${tableName}" contains both the "${fieldCollision.from}" and "${fieldCollision.to}" fields. Move or rename the existing destination data before creating this migration.`);
|
|
66
|
+
}
|
|
67
|
+
for (const { from, to } of columns){
|
|
68
|
+
const column = table.columns[from];
|
|
69
|
+
if (column) {
|
|
70
|
+
if (table.columns[to]) {
|
|
71
|
+
throw new Error(`Cannot create the sizes-to-variants migration because snapshot table "${tableName}" contains both "${from}" and "${to}". Move or rename the existing destination data before creating this migration.`);
|
|
72
|
+
}
|
|
73
|
+
delete table.columns[from];
|
|
74
|
+
table.columns[to] = {
|
|
75
|
+
...column,
|
|
76
|
+
name: to
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
for (const [key, index] of Object.entries(table.indexes ?? {})){
|
|
81
|
+
const indexColumns = index.columns.map((column)=>{
|
|
82
|
+
const name = typeof column === 'string' ? column : column.expression;
|
|
83
|
+
const renamedName = columns.find(({ from })=>from === name)?.to ?? name;
|
|
84
|
+
return typeof column === 'string' ? renamedName : {
|
|
85
|
+
...column,
|
|
86
|
+
expression: renamedName
|
|
87
|
+
};
|
|
88
|
+
});
|
|
89
|
+
const indexColumnNames = indexColumns.map((column)=>typeof column === 'string' ? column : column.expression);
|
|
90
|
+
const target = indexes.find((planned)=>planned.columns.join(',') === indexColumnNames.join(','));
|
|
91
|
+
if (!target) {
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
if (key !== target.to && table.indexes?.[target.to]) {
|
|
95
|
+
throw new Error(`Cannot create the sizes-to-variants migration because snapshot table "${tableName}" contains both indexes "${key}" and "${target.to}". Move or rename the existing destination index before creating this migration.`);
|
|
96
|
+
}
|
|
97
|
+
delete table.indexes[key];
|
|
98
|
+
table.indexes[target.to] = {
|
|
99
|
+
...index,
|
|
100
|
+
name: target.to,
|
|
101
|
+
columns: indexColumns
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
renamed.prevId = snapshot.id;
|
|
106
|
+
renamed.id = randomUUID();
|
|
107
|
+
return renamed;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
//# sourceMappingURL=buildDynamicPredefinedSizesToVariantsMigration.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/buildDynamicPredefinedSizesToVariantsMigration.ts"],"sourcesContent":["import type { DynamicMigrationTemplate } from 'payload'\n\nimport { randomUUID } from 'crypto'\nimport { readdirSync, readFileSync, writeFileSync } from 'fs'\n\nimport type { DrizzleAdapter } from '../types.js'\nimport type { SizesToVariantsTableRenames } from './getSizesToVariantsRenames.js'\n\nimport {\n findSizesToVariantsFieldCollision,\n getSizesToVariantsRenames,\n} from './getSizesToVariantsRenames.js'\n\ntype SnapshotIndex = {\n columns: ({ expression: string } | string)[]\n name: string\n}\n\ntype SnapshotTable = {\n columns: Record<string, { name: string }>\n indexes?: Record<string, SnapshotIndex>\n name: string\n}\n\ntype Snapshot = {\n id?: string\n prevId?: string\n tables: Record<string, SnapshotTable>\n version: string\n}\n\n/**\n * Builds the `sizes-to-variants` predefined migration for a SQL adapter. The migration renames\n * columns rather than letting drizzle-kit diff the schema (which would drop and re-add them,\n * losing every stored image size).\n *\n * It also writes a schema snapshot: the project's previous snapshot with only these renames\n * applied. The next generated migration then diffs from the renamed columns instead of dropping\n * them, and still picks up every other schema change the upgrade brings. Without a previous\n * snapshot (a project that has only ever used `push`) there's nothing to update, so none is written.\n */\nexport const buildDynamicPredefinedSizesToVariantsMigration = ({\n packageName,\n}: {\n packageName: string\n}): DynamicMigrationTemplate => {\n return async ({ filePath, payload }) => {\n const adapter = payload.db as unknown as DrizzleAdapter\n const previousSnapshot = await readLatestSnapshot({ adapter })\n\n if (previousSnapshot) {\n const renamedSnapshot = applySizesToVariantsRenames({\n plan: getSizesToVariantsRenames({ adapter, direction: 'up' }),\n snapshot: previousSnapshot,\n })\n\n writeFileSync(`${filePath}.json`, JSON.stringify(renamedSnapshot, null, 2))\n }\n\n return {\n downSQL: ` await migrateSizesToVariants({ db, direction: 'down', payload })`,\n imports: `import { migrateSizesToVariants } from '${packageName}/migration-utils'`,\n upSQL: ` await migrateSizesToVariants({ db, payload })`,\n }\n }\n}\n\n/** The latest snapshot in the migrations directory, upgraded to drizzle-kit's current format. */\nasync function readLatestSnapshot({\n adapter,\n}: {\n adapter: DrizzleAdapter\n}): Promise<Snapshot | undefined> {\n const dir = adapter.migrationDir\n const latestSnapshotFile = readdirSync(dir)\n .filter((file) => file.endsWith('.json'))\n .sort()\n .reverse()[0]\n\n if (!latestSnapshotFile) {\n return undefined\n }\n\n const { generateDrizzleJson, upSnapshot } = await adapter.requireDrizzleKit()\n const currentVersion = (await generateDrizzleJson(adapter.schema)).version\n const snapshot = JSON.parse(readFileSync(`${dir}/${latestSnapshotFile}`, 'utf8')) as Snapshot\n\n return upSnapshot && snapshot.version < currentVersion ? upSnapshot(snapshot) : snapshot\n}\n\nfunction applySizesToVariantsRenames({\n plan,\n snapshot,\n}: {\n plan: SizesToVariantsTableRenames[]\n snapshot: Snapshot\n}): Snapshot {\n const renamed: Snapshot = structuredClone(snapshot)\n\n for (const { columns, indexes, tableName } of plan) {\n const table = Object.values(renamed.tables).find(({ name }) => name === tableName)\n\n if (!table) {\n continue\n }\n\n const existingColumns = new Set(Object.values(table.columns).map(({ name }) => name))\n\n for (const { from, to } of columns) {\n if (existingColumns.has(from) && existingColumns.has(to)) {\n throw new Error(\n `Cannot create the sizes-to-variants migration because snapshot table \"${tableName}\" contains both \"${from}\" and \"${to}\". Move or rename the existing destination data before creating this migration.`,\n )\n }\n }\n\n const fieldCollision = findSizesToVariantsFieldCollision({ columns, existingColumns })\n\n if (fieldCollision) {\n throw new Error(\n `Cannot create the sizes-to-variants migration because snapshot table \"${tableName}\" contains both the \"${fieldCollision.from}\" and \"${fieldCollision.to}\" fields. Move or rename the existing destination data before creating this migration.`,\n )\n }\n\n for (const { from, to } of columns) {\n const column = table.columns[from]\n\n if (column) {\n if (table.columns[to]) {\n throw new Error(\n `Cannot create the sizes-to-variants migration because snapshot table \"${tableName}\" contains both \"${from}\" and \"${to}\". Move or rename the existing destination data before creating this migration.`,\n )\n }\n\n delete table.columns[from]\n table.columns[to] = { ...column, name: to }\n }\n }\n\n for (const [key, index] of Object.entries(table.indexes ?? {})) {\n const indexColumns = index.columns.map((column) => {\n const name = typeof column === 'string' ? column : column.expression\n const renamedName = columns.find(({ from }) => from === name)?.to ?? name\n\n return typeof column === 'string' ? renamedName : { ...column, expression: renamedName }\n })\n const indexColumnNames = indexColumns.map((column) =>\n typeof column === 'string' ? column : column.expression,\n )\n const target = indexes.find(\n (planned) => planned.columns.join(',') === indexColumnNames.join(','),\n )\n\n if (!target) {\n continue\n }\n\n if (key !== target.to && table.indexes?.[target.to]) {\n throw new Error(\n `Cannot create the sizes-to-variants migration because snapshot table \"${tableName}\" contains both indexes \"${key}\" and \"${target.to}\". Move or rename the existing destination index before creating this migration.`,\n )\n }\n\n delete table.indexes[key]\n table.indexes[target.to] = { ...index, name: target.to, columns: indexColumns }\n }\n }\n\n renamed.prevId = snapshot.id\n renamed.id = randomUUID()\n\n return renamed\n}\n"],"names":["randomUUID","readdirSync","readFileSync","writeFileSync","findSizesToVariantsFieldCollision","getSizesToVariantsRenames","buildDynamicPredefinedSizesToVariantsMigration","packageName","filePath","payload","adapter","db","previousSnapshot","readLatestSnapshot","renamedSnapshot","applySizesToVariantsRenames","plan","direction","snapshot","JSON","stringify","downSQL","imports","upSQL","dir","migrationDir","latestSnapshotFile","filter","file","endsWith","sort","reverse","undefined","generateDrizzleJson","upSnapshot","requireDrizzleKit","currentVersion","schema","version","parse","renamed","structuredClone","columns","indexes","tableName","table","Object","values","tables","find","name","existingColumns","Set","map","from","to","has","Error","fieldCollision","column","key","index","entries","indexColumns","expression","renamedName","indexColumnNames","target","planned","join","prevId","id"],"mappings":"AAEA,SAASA,UAAU,QAAQ,SAAQ;AACnC,SAASC,WAAW,EAAEC,YAAY,EAAEC,aAAa,QAAQ,KAAI;AAK7D,SACEC,iCAAiC,EACjCC,yBAAyB,QACpB,iCAAgC;AAoBvC;;;;;;;;;CASC,GACD,OAAO,MAAMC,iDAAiD,CAAC,EAC7DC,WAAW,EAGZ;IACC,OAAO,OAAO,EAAEC,QAAQ,EAAEC,OAAO,EAAE;QACjC,MAAMC,UAAUD,QAAQE,EAAE;QAC1B,MAAMC,mBAAmB,MAAMC,mBAAmB;YAAEH;QAAQ;QAE5D,IAAIE,kBAAkB;YACpB,MAAME,kBAAkBC,4BAA4B;gBAClDC,MAAMX,0BAA0B;oBAAEK;oBAASO,WAAW;gBAAK;gBAC3DC,UAAUN;YACZ;YAEAT,cAAc,GAAGK,SAAS,KAAK,CAAC,EAAEW,KAAKC,SAAS,CAACN,iBAAiB,MAAM;QAC1E;QAEA,OAAO;YACLO,SAAS,CAAC,kEAAkE,CAAC;YAC7EC,SAAS,CAAC,wCAAwC,EAAEf,YAAY,iBAAiB,CAAC;YAClFgB,OAAO,CAAC,+CAA+C,CAAC;QAC1D;IACF;AACF,EAAC;AAED,+FAA+F,GAC/F,eAAeV,mBAAmB,EAChCH,OAAO,EAGR;IACC,MAAMc,MAAMd,QAAQe,YAAY;IAChC,MAAMC,qBAAqBzB,YAAYuB,KACpCG,MAAM,CAAC,CAACC,OAASA,KAAKC,QAAQ,CAAC,UAC/BC,IAAI,GACJC,OAAO,EAAE,CAAC,EAAE;IAEf,IAAI,CAACL,oB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sEAAsE,EAAEb,UAAU,yBAAyB,EAAEgB,IAAI,OAAO,EAAEO,OAAOZ,EAAE,CAAC,gFAAgF,CAAC;YAE1N;YAEA,OAAOV,MAAMF,OAAO,CAACiB,IAAI;YACzBf,MAAMF,OAAO,CAACwB,OAAOZ,EAAE,CAAC,GAAG;gBAAE,GAAGM,KAAK;gBAAEX,MAAMiB,OAAOZ,EAAE;gBAAEb,SAASqB;YAAa;QAChF;IACF;IAEAvB,QAAQ8B,MAAM,GAAGpD,SAASqD,EAAE;IAC5B/B,QAAQ+B,EAAE,GAAGvE;IAEb,OAAOwC;AACT"}
|
|
@@ -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;
|
|
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;AAoCxE,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,cA4SH,CAAA"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { existsSync } from 'fs';
|
|
2
2
|
import { writeFile } from 'fs/promises';
|
|
3
3
|
import path from 'path';
|
|
4
|
+
import { formatGeneratedFile } from './formatGeneratedFile.js';
|
|
4
5
|
/**
|
|
5
6
|
* @example
|
|
6
7
|
* console.log(sanitizeObjectKey("oneTwo")); // oneTwo
|
|
@@ -215,7 +216,7 @@ declare module '${this.packageName}' {
|
|
|
215
216
|
*/
|
|
216
217
|
`;
|
|
217
218
|
const importTypes = `import type {} from '${this.packageName}'`;
|
|
218
|
-
|
|
219
|
+
const code = [
|
|
219
220
|
warning,
|
|
220
221
|
importTypes,
|
|
221
222
|
...importDeclarationsSanitized,
|
|
@@ -235,19 +236,13 @@ declare module '${this.packageName}' {
|
|
|
235
236
|
outputFile = path.resolve(cwd, 'payload-generated-schema.ts');
|
|
236
237
|
}
|
|
237
238
|
}
|
|
239
|
+
await writeFile(outputFile, code, 'utf-8');
|
|
238
240
|
if (prettify) {
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
code = await prettier.format(code, {
|
|
244
|
-
...config,
|
|
245
|
-
parser: 'typescript'
|
|
246
|
-
});
|
|
247
|
-
} catch {
|
|
248
|
-
/* empty */ }
|
|
241
|
+
await formatGeneratedFile({
|
|
242
|
+
filePath: outputFile,
|
|
243
|
+
logger: this.payload.logger
|
|
244
|
+
});
|
|
249
245
|
}
|
|
250
|
-
await writeFile(outputFile, code, 'utf-8');
|
|
251
246
|
if (log) {
|
|
252
247
|
this.payload.logger.info(`Written ${outputFile}`);
|
|
253
248
|
}
|
|
@@ -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 return { outputFile }\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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AAc,CAAC,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;QAEA,OAAO;YAAEA;QAAW;IACtB;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\nimport { formatGeneratedFile } from './formatGeneratedFile.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 const 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 await writeFile(outputFile, code, 'utf-8')\n\n if (prettify) {\n await formatGeneratedFile({ filePath: outputFile, logger: this.payload.logger })\n }\n\n if (log) {\n this.payload.logger.info(`Written ${outputFile}`)\n }\n\n return { outputFile }\n }\n}\n"],"names":["existsSync","writeFile","path","formatGeneratedFile","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","filePath","logger","info"],"mappings":"AAEA,SAASA,UAAU,QAAQ,KAAI;AAC/B,SAASC,SAAS,QAAQ,cAAa;AACvC,OAAOC,UAAU,OAAM;AAIvB,SAASC,mBAAmB,QAAQ,2BAA0B;AAE9D;;;;;;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;IAC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AE,IAAI,CAAChF,WAAW,CAAC,CAAC,CAAC;QAE/D,MAAMiF,OAAO;YACXF;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,SAASnH,KAAKoH,OAAO,CAACH,KAAK;YAEjC,IAAInH,WAAWqH,SAAS;gBACtBhG,aAAanB,KAAKoH,OAAO,CAACD,QAAQ;YACpC,OAAO;gBACLhG,aAAanB,KAAKoH,OAAO,CAACH,KAAK;YACjC;QACF;QAEA,MAAMlH,UAAUoB,YAAY6F,MAAM;QAElC,IAAI5F,UAAU;YACZ,MAAMnB,oBAAoB;gBAAEoH,UAAUlG;gBAAYmG,QAAQ,IAAI,CAAC1E,OAAO,CAAC0E,MAAM;YAAC;QAChF;QAEA,IAAIpG,KAAK;YACP,IAAI,CAAC0B,OAAO,CAAC0E,MAAM,CAACC,IAAI,CAAC,CAAC,QAAQ,EAAEpG,YAAY;QAClD;QAEA,OAAO;YAAEA;QAAW;IACtB;AACF,EAAC"}
|
|
@@ -2,7 +2,7 @@ import { extendDrizzleTable } from './extendDrizzleTable.js';
|
|
|
2
2
|
export const executeSchemaHooks = async ({ type, adapter })=>{
|
|
3
3
|
for (const hook of adapter[type]){
|
|
4
4
|
const result = await hook({
|
|
5
|
-
adapter
|
|
5
|
+
adapter,
|
|
6
6
|
extendTable: extendDrizzleTable,
|
|
7
7
|
schema: {
|
|
8
8
|
enums: adapter.enums,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/executeSchemaHooks.ts"],"sourcesContent":["import type { DrizzleAdapter } from '../types.js'\n\nimport { extendDrizzleTable } from './extendDrizzleTable.js'\n\ntype DatabaseSchema = {\n enums?: DrizzleAdapter['enums']\n relations: Record<string, any>\n tables: DrizzleAdapter['tables']\n}\n\ntype Adapter = {\n afterSchemaInit: DatabaseSchemaHook[]\n beforeSchemaInit: DatabaseSchemaHook[]\n} & DatabaseSchema\n\ntype DatabaseSchemaHookArgs = {\n adapter: Record<string, unknown>\n extendTable: typeof extendDrizzleTable\n schema: DatabaseSchema\n}\n\ntype DatabaseSchemaHook = (args: DatabaseSchemaHookArgs) => DatabaseSchema | Promise<DatabaseSchema>\n\ntype Args = {\n adapter: Adapter\n type: 'afterSchemaInit' | 'beforeSchemaInit'\n}\n\nexport const executeSchemaHooks = async ({ type, adapter }: Args): Promise<void> => {\n for (const hook of
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/executeSchemaHooks.ts"],"sourcesContent":["import type { DrizzleAdapter } from '../types.js'\n\nimport { extendDrizzleTable } from './extendDrizzleTable.js'\n\ntype DatabaseSchema = {\n enums?: DrizzleAdapter['enums']\n relations: Record<string, any>\n tables: DrizzleAdapter['tables']\n}\n\ntype Adapter = {\n afterSchemaInit: DatabaseSchemaHook[]\n beforeSchemaInit: DatabaseSchemaHook[]\n} & DatabaseSchema\n\ntype DatabaseSchemaHookArgs = {\n adapter: Record<string, unknown>\n extendTable: typeof extendDrizzleTable\n schema: DatabaseSchema\n}\n\ntype DatabaseSchemaHook = (args: DatabaseSchemaHookArgs) => DatabaseSchema | Promise<DatabaseSchema>\n\ntype Args = {\n adapter: Adapter\n type: 'afterSchemaInit' | 'beforeSchemaInit'\n}\n\nexport const executeSchemaHooks = async ({ type, adapter }: Args): Promise<void> => {\n for (const hook of adapter[type]) {\n const result = await hook({\n adapter,\n extendTable: extendDrizzleTable,\n schema: {\n enums: adapter.enums,\n relations: adapter.relations,\n tables: adapter.tables,\n },\n })\n if (result.enums) {\n adapter.enums = result.enums\n }\n\n adapter.tables = result.tables\n adapter.relations = result.relations\n }\n}\n"],"names":["extendDrizzleTable","executeSchemaHooks","type","adapter","hook","result","extendTable","schema","enums","relations","tables"],"mappings":"AAEA,SAASA,kBAAkB,QAAQ,0BAAyB;AA0B5D,OAAO,MAAMC,qBAAqB,OAAO,EAAEC,IAAI,EAAEC,OAAO,EAAQ;IAC9D,KAAK,MAAMC,QAAQD,OAAO,CAACD,KAAK,CAAE;QAChC,MAAMG,SAAS,MAAMD,KAAK;YACxBD;YACAG,aAAaN;YACbO,QAAQ;gBACNC,OAAOL,QAAQK,KAAK;gBACpBC,WAAWN,QAAQM,SAAS;gBAC5BC,QAAQP,QAAQO,MAAM;YACxB;QACF;QACA,IAAIL,OAAOG,KAAK,EAAE;YAChBL,QAAQK,KAAK,GAAGH,OAAOG,KAAK;QAC9B;QAEAL,QAAQO,MAAM,GAAGL,OAAOK,MAAM;QAC9BP,QAAQM,SAAS,GAAGJ,OAAOI,SAAS;IACtC;AACF,EAAC"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Payload } from 'payload';
|
|
2
|
+
/**
|
|
3
|
+
* Formats a generated file in place with the project's formatter and formatter config: oxfmt if
|
|
4
|
+
* it's installed, otherwise Prettier. Logs an error if neither can format the file.
|
|
5
|
+
*/
|
|
6
|
+
export declare function formatGeneratedFile({ filePath, logger, }: {
|
|
7
|
+
filePath: string;
|
|
8
|
+
logger: Payload['logger'];
|
|
9
|
+
}): Promise<void>;
|
|
10
|
+
//# sourceMappingURL=formatGeneratedFile.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"formatGeneratedFile.d.ts","sourceRoot":"","sources":["../../src/utilities/formatGeneratedFile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AAoBtC;;;GAGG;AACH,wBAAsB,mBAAmB,CAAC,EACxC,QAAQ,EACR,MAAM,GACP,EAAE;IACD,QAAQ,EAAE,MAAM,CAAA;IAChB,MAAM,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAA;CAC1B,GAAG,OAAO,CAAC,IAAI,CAAC,CAwChB"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { execFile } from 'child_process';
|
|
2
|
+
import { readFile, writeFile } from 'fs/promises';
|
|
3
|
+
import { createRequire } from 'module';
|
|
4
|
+
import path from 'path';
|
|
5
|
+
import { dynamicImport } from 'payload';
|
|
6
|
+
import { promisify } from 'util';
|
|
7
|
+
const execFileAsync = promisify(execFile);
|
|
8
|
+
/**
|
|
9
|
+
* Formats a generated file in place with the project's formatter and formatter config: oxfmt if
|
|
10
|
+
* it's installed, otherwise Prettier. Logs an error if neither can format the file.
|
|
11
|
+
*/ export async function formatGeneratedFile({ filePath, logger }) {
|
|
12
|
+
let formatError;
|
|
13
|
+
// oxfmt's `format()` API doesn't discover config files, so run the project's oxfmt CLI instead
|
|
14
|
+
let oxfmtBinPath;
|
|
15
|
+
try {
|
|
16
|
+
const projectRequire = createRequire(path.join(process.cwd(), 'package.json'));
|
|
17
|
+
const packageJSONPath = projectRequire.resolve('oxfmt/package.json');
|
|
18
|
+
const { bin } = projectRequire(packageJSONPath);
|
|
19
|
+
oxfmtBinPath = path.join(path.dirname(packageJSONPath), bin.oxfmt);
|
|
20
|
+
} catch {
|
|
21
|
+
// oxfmt isn't installed
|
|
22
|
+
}
|
|
23
|
+
if (oxfmtBinPath) {
|
|
24
|
+
try {
|
|
25
|
+
await execFileAsync(process.execPath, // Loading `oxfmt.config.ts` relies on Node's type stripping, which `NODE_OPTIONS` may disable
|
|
26
|
+
[
|
|
27
|
+
'--experimental-strip-types',
|
|
28
|
+
oxfmtBinPath,
|
|
29
|
+
'--no-error-on-unmatched-pattern',
|
|
30
|
+
filePath
|
|
31
|
+
], {
|
|
32
|
+
cwd: process.cwd()
|
|
33
|
+
});
|
|
34
|
+
return;
|
|
35
|
+
} catch (err) {
|
|
36
|
+
formatError = err;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
try {
|
|
40
|
+
const prettier = await dynamicImport('prettier');
|
|
41
|
+
const configPath = await prettier.resolveConfigFile();
|
|
42
|
+
const config = configPath ? await prettier.resolveConfig(configPath) : {};
|
|
43
|
+
const code = await readFile(filePath, 'utf-8');
|
|
44
|
+
await writeFile(filePath, await prettier.format(code, {
|
|
45
|
+
...config,
|
|
46
|
+
parser: 'typescript'
|
|
47
|
+
}));
|
|
48
|
+
return;
|
|
49
|
+
} catch (err) {
|
|
50
|
+
formatError ??= err;
|
|
51
|
+
}
|
|
52
|
+
logger.error({
|
|
53
|
+
err: formatError,
|
|
54
|
+
msg: `Could not format ${filePath} with oxfmt or Prettier`
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
//# sourceMappingURL=formatGeneratedFile.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/formatGeneratedFile.ts"],"sourcesContent":["import type { Payload } from 'payload'\n\nimport { execFile } from 'child_process'\nimport { readFile, writeFile } from 'fs/promises'\nimport { createRequire } from 'module'\nimport path from 'path'\nimport { dynamicImport } from 'payload'\nimport { promisify } from 'util'\n\n/**\n * The subset of Prettier's API used here. Prettier isn't a dependency, so its types aren't available.\n */\ntype Prettier = {\n format: (source: string, options: Record<string, unknown>) => Promise<string>\n resolveConfig: (filePath: string) => Promise<null | Record<string, unknown>>\n resolveConfigFile: () => Promise<null | string>\n}\n\nconst execFileAsync = promisify(execFile)\n\n/**\n * Formats a generated file in place with the project's formatter and formatter config: oxfmt if\n * it's installed, otherwise Prettier. Logs an error if neither can format the file.\n */\nexport async function formatGeneratedFile({\n filePath,\n logger,\n}: {\n filePath: string\n logger: Payload['logger']\n}): Promise<void> {\n let formatError: unknown\n\n // oxfmt's `format()` API doesn't discover config files, so run the project's oxfmt CLI instead\n let oxfmtBinPath: string | undefined\n try {\n const projectRequire = createRequire(path.join(process.cwd(), 'package.json'))\n const packageJSONPath = projectRequire.resolve('oxfmt/package.json')\n const { bin } = projectRequire(packageJSONPath) as { bin: { oxfmt: string } }\n oxfmtBinPath = path.join(path.dirname(packageJSONPath), bin.oxfmt)\n } catch {\n // oxfmt isn't installed\n }\n\n if (oxfmtBinPath) {\n try {\n await execFileAsync(\n process.execPath,\n // Loading `oxfmt.config.ts` relies on Node's type stripping, which `NODE_OPTIONS` may disable\n ['--experimental-strip-types', oxfmtBinPath, '--no-error-on-unmatched-pattern', filePath],\n { cwd: process.cwd() },\n )\n return\n } catch (err) {\n formatError = err\n }\n }\n\n try {\n const prettier = await dynamicImport<Prettier>('prettier')\n const configPath = await prettier.resolveConfigFile()\n const config = configPath ? await prettier.resolveConfig(configPath) : {}\n const code = await readFile(filePath, 'utf-8')\n await writeFile(filePath, await prettier.format(code, { ...config, parser: 'typescript' }))\n return\n } catch (err) {\n formatError ??= err\n }\n\n logger.error({ err: formatError, msg: `Could not format ${filePath} with oxfmt or Prettier` })\n}\n"],"names":["execFile","readFile","writeFile","createRequire","path","dynamicImport","promisify","execFileAsync","formatGeneratedFile","filePath","logger","formatError","oxfmtBinPath","projectRequire","join","process","cwd","packageJSONPath","resolve","bin","dirname","oxfmt","execPath","err","prettier","configPath","resolveConfigFile","config","resolveConfig","code","format","parser","error","msg"],"mappings":"AAEA,SAASA,QAAQ,QAAQ,gBAAe;AACxC,SAASC,QAAQ,EAAEC,SAAS,QAAQ,cAAa;AACjD,SAASC,aAAa,QAAQ,SAAQ;AACtC,OAAOC,UAAU,OAAM;AACvB,SAASC,aAAa,QAAQ,UAAS;AACvC,SAASC,SAAS,QAAQ,OAAM;AAWhC,MAAMC,gBAAgBD,UAAUN;AAEhC;;;CAGC,GACD,OAAO,eAAeQ,oBAAoB,EACxCC,QAAQ,EACRC,MAAM,EAIP;IACC,IAAIC;IAEJ,+FAA+F;IAC/F,IAAIC;IACJ,IAAI;QACF,MAAMC,iBAAiBV,cAAcC,KAAKU,IAAI,CAACC,QAAQC,GAAG,IAAI;QAC9D,MAAMC,kBAAkBJ,eAAeK,OAAO,CAAC;QAC/C,MAAM,EAAEC,GAAG,EAAE,GAAGN,eAAeI;QAC/BL,eAAeR,KAAKU,IAAI,CAACV,KAAKgB,OAAO,CAACH,kBAAkBE,IAAIE,KAAK;IACnE,EAAE,OAAM;IACN,wBAAwB;IAC1B;IAEA,IAAIT,cAAc;QAChB,IAAI;YACF,MAAML,cACJQ,QAAQO,QAAQ,EAChB,8FAA8F;YAC9F;gBAAC;gBAA8BV;gBAAc;gBAAmCH;aAAS,EACzF;gBAAEO,KAAKD,QAAQC,GAAG;YAAG;YAEvB;QACF,EAAE,OAAOO,KAAK;YACZZ,cAAcY;QAChB;IACF;IAEA,IAAI;QACF,MAAMC,WAAW,MAAMnB,cAAwB;QAC/C,MAAMoB,aAAa,MAAMD,SAASE,iBAAiB;QACnD,MAAMC,SAASF,aAAa,MAAMD,SAASI,aAAa,CAACH,cAAc,CAAC;QACxE,MAAMI,OAAO,MAAM5B,SAASQ,UAAU;QACtC,MAAMP,UAAUO,UAAU,MAAMe,SAASM,MAAM,CAACD,MAAM;YAAE,GAAGF,MAAM;YAAEI,QAAQ;QAAa;QACxF;IACF,EAAE,OAAOR,KAAK;QACZZ,gBAAgBY;IAClB;IAEAb,OAAOsB,KAAK,CAAC;QAAET,KAAKZ;QAAasB,KAAK,CAAC,iBAAiB,EAAExB,SAAS,uBAAuB,CAAC;IAAC;AAC9F"}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { DrizzleAdapter } from '../types.js';
|
|
2
|
+
export type SizesToVariantsDirection = 'down' | 'up';
|
|
3
|
+
export type SizesToVariantsColumnRename = {
|
|
4
|
+
from: string;
|
|
5
|
+
to: string;
|
|
6
|
+
};
|
|
7
|
+
export type SizesToVariantsIndexRename = {
|
|
8
|
+
/** Columns the index covers, named as they are after the column renames. */
|
|
9
|
+
columns: string[];
|
|
10
|
+
/** The index name to rename from on `down`. The generated legacy name is resolved on `up`. */
|
|
11
|
+
from?: string;
|
|
12
|
+
/** Base used to verify a generated legacy index name, including a possible numeric suffix. */
|
|
13
|
+
legacyNameBase?: string;
|
|
14
|
+
to: string;
|
|
15
|
+
unique: boolean;
|
|
16
|
+
};
|
|
17
|
+
export type SizesToVariantsTableRenames = {
|
|
18
|
+
columns: SizesToVariantsColumnRename[];
|
|
19
|
+
indexes: SizesToVariantsIndexRename[];
|
|
20
|
+
tableName: string;
|
|
21
|
+
};
|
|
22
|
+
export declare function findSizesToVariantsFieldCollision({ columns, existingColumns, }: {
|
|
23
|
+
columns: SizesToVariantsColumnRename[];
|
|
24
|
+
existingColumns: Set<string>;
|
|
25
|
+
}): {
|
|
26
|
+
from: string;
|
|
27
|
+
to: string;
|
|
28
|
+
} | undefined;
|
|
29
|
+
export declare function assertNoSizesToVariantsColumnCollisions({ columns, existingColumns, tableName, }: {
|
|
30
|
+
columns: SizesToVariantsColumnRename[];
|
|
31
|
+
existingColumns: Set<string>;
|
|
32
|
+
tableName: string;
|
|
33
|
+
}): void;
|
|
34
|
+
/**
|
|
35
|
+
* Plans the column and index renames that move every upload collection's stored image sizes
|
|
36
|
+
* between the legacy `sizes` group and `variants`. Reads the current (`variants`) schema the
|
|
37
|
+
* adapter built from the config, so it covers each collection's main and versions tables without
|
|
38
|
+
* re-deriving Payload's column naming.
|
|
39
|
+
*
|
|
40
|
+
* Index names come from the schema on `up`, and on `down` are rebuilt the way `buildIndexName`
|
|
41
|
+
* named them before the rename. The runner still has to locate the verified generated legacy name
|
|
42
|
+
* on `up`, since it may have a numeric suffix that keeps the name unique.
|
|
43
|
+
*/
|
|
44
|
+
export declare function getSizesToVariantsRenames({ adapter, direction, }: {
|
|
45
|
+
adapter: DrizzleAdapter;
|
|
46
|
+
direction: SizesToVariantsDirection;
|
|
47
|
+
}): SizesToVariantsTableRenames[];
|
|
48
|
+
/** Mirrors `buildIndexName` for an index that didn't collide, without registering the name. */
|
|
49
|
+
export declare function isGeneratedLegacyIndexName({ indexName, legacyNameBase, }: {
|
|
50
|
+
indexName: string;
|
|
51
|
+
legacyNameBase: string;
|
|
52
|
+
}): boolean;
|
|
53
|
+
export declare function buildGeneratedLegacyIndexName(name: string, number?: number): string;
|
|
54
|
+
//# sourceMappingURL=getSizesToVariantsRenames.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"getSizesToVariantsRenames.d.ts","sourceRoot":"","sources":["../../src/utilities/getSizesToVariantsRenames.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAsB,MAAM,aAAa,CAAA;AAIrE,MAAM,MAAM,wBAAwB,GAAG,MAAM,GAAG,IAAI,CAAA;AAEpD,MAAM,MAAM,2BAA2B,GAAG;IACxC,IAAI,EAAE,MAAM,CAAA;IACZ,EAAE,EAAE,MAAM,CAAA;CACX,CAAA;AAED,MAAM,MAAM,0BAA0B,GAAG;IACvC,4EAA4E;IAC5E,OAAO,EAAE,MAAM,EAAE,CAAA;IACjB,8FAA8F;IAC9F,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,8FAA8F;IAC9F,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,EAAE,EAAE,MAAM,CAAA;IACV,MAAM,EAAE,OAAO,CAAA;CAChB,CAAA;AAED,MAAM,MAAM,2BAA2B,GAAG;IACxC,OAAO,EAAE,2BAA2B,EAAE,CAAA;IACtC,OAAO,EAAE,0BAA0B,EAAE,CAAA;IACrC,SAAS,EAAE,MAAM,CAAA;CAClB,CAAA;AAED,wBAAgB,iCAAiC,CAAC,EAChD,OAAO,EACP,eAAe,GAChB,EAAE;IACD,OAAO,EAAE,2BAA2B,EAAE,CAAA;IACtC,eAAe,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;CAC7B,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CA2B3C;AAED,wBAAgB,uCAAuC,CAAC,EACtD,OAAO,EACP,eAAe,EACf,SAAS,GACV,EAAE;IACD,OAAO,EAAE,2BAA2B,EAAE,CAAA;IACtC,eAAe,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;IAC5B,SAAS,EAAE,MAAM,CAAA;CAClB,GAAG,IAAI,CAgBP;AAiBD;;;;;;;;;GASG;AACH,wBAAgB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