@payloadcms/drizzle 4.0.0-internal.bc5cf8c → 4.0.0-internal.bd1d413
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/LICENSE.md +1 -1
- package/dist/createTableName.d.ts.map +1 -1
- package/dist/createTableName.js +2 -7
- package/dist/createTableName.js.map +1 -1
- package/dist/exports/postgres.d.ts +6 -1
- package/dist/exports/postgres.d.ts.map +1 -1
- package/dist/exports/postgres.js +6 -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.map +1 -1
- package/dist/find/buildPolymorphicJoinQuery.d.ts +39 -0
- package/dist/find/buildPolymorphicJoinQuery.d.ts.map +1 -0
- package/dist/find/buildPolymorphicJoinQuery.js +146 -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.map +1 -1
- package/dist/find/traverseFields.d.ts.map +1 -1
- package/dist/find/traverseFields.js +20 -191
- package/dist/find/traverseFields.js.map +1 -1
- package/dist/index.d.ts +4 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -8
- package/dist/index.js.map +1 -1
- package/dist/migrate.d.ts.map +1 -1
- package/dist/migrate.js +41 -15
- package/dist/migrate.js.map +1 -1
- package/dist/migrateDown.d.ts +2 -1
- package/dist/migrateDown.d.ts.map +1 -1
- package/dist/migrateDown.js +17 -4
- package/dist/migrateDown.js.map +1 -1
- package/dist/migrateFresh.d.ts +4 -2
- package/dist/migrateFresh.d.ts.map +1 -1
- package/dist/migrateFresh.js +26 -9
- package/dist/migrateFresh.js.map +1 -1
- package/dist/migrateRefresh.d.ts +2 -1
- package/dist/migrateRefresh.d.ts.map +1 -1
- package/dist/migrateRefresh.js +20 -5
- package/dist/migrateRefresh.js.map +1 -1
- package/dist/migrateReset.d.ts +2 -1
- package/dist/migrateReset.d.ts.map +1 -1
- package/dist/migrateReset.js +18 -4
- package/dist/migrateReset.js.map +1 -1
- package/dist/migrateStatus.d.ts +2 -1
- package/dist/migrateStatus.d.ts.map +1 -1
- package/dist/migrateStatus.js +11 -6
- package/dist/migrateStatus.js.map +1 -1
- package/dist/postgres/createDatabase.d.ts.map +1 -1
- package/dist/postgres/createExtensions.d.ts.map +1 -1
- package/dist/postgres/createJSONQuery/index.d.ts.map +1 -1
- package/dist/postgres/createJSONQuery/index.js +3 -3
- package/dist/postgres/createJSONQuery/index.js.map +1 -1
- package/dist/postgres/findDocumentLocks.d.ts +4 -0
- package/dist/postgres/findDocumentLocks.d.ts.map +1 -0
- package/dist/postgres/findDocumentLocks.js +22 -0
- package/dist/postgres/findDocumentLocks.js.map +1 -0
- package/dist/postgres/init.d.ts.map +1 -1
- package/dist/postgres/init.js +6 -0
- package/dist/postgres/init.js.map +1 -1
- package/dist/postgres/predefinedMigrations/localize-status/getGeneratedColumnType.d.ts +26 -0
- package/dist/postgres/predefinedMigrations/localize-status/getGeneratedColumnType.d.ts.map +1 -0
- package/dist/postgres/predefinedMigrations/localize-status/getGeneratedColumnType.js +61 -0
- package/dist/postgres/predefinedMigrations/localize-status/getGeneratedColumnType.js.map +1 -0
- package/dist/postgres/predefinedMigrations/localize-status/getMigrationDB.d.ts +13 -0
- package/dist/postgres/predefinedMigrations/localize-status/getMigrationDB.d.ts.map +1 -0
- package/dist/postgres/predefinedMigrations/localize-status/getMigrationDB.js +17 -0
- package/dist/postgres/predefinedMigrations/localize-status/getMigrationDB.js.map +1 -0
- package/dist/postgres/predefinedMigrations/localize-status/index.d.ts.map +1 -1
- package/dist/postgres/predefinedMigrations/localize-status/index.js +73 -10
- package/dist/postgres/predefinedMigrations/localize-status/index.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/fetchAndResave/traverseFields.d.ts.map +1 -1
- package/dist/postgres/predefinedMigrations/v2-v3/groupUpSQLStatements.d.ts.map +1 -1
- package/dist/postgres/predefinedMigrations/v2-v3/index.d.ts.map +1 -1
- package/dist/postgres/predefinedMigrations/v2-v3/index.js +2 -2
- package/dist/postgres/predefinedMigrations/v2-v3/index.js.map +1 -1
- package/dist/postgres/predefinedMigrations/v2-v3/migrateRelationships.d.ts.map +1 -1
- package/dist/postgres/predefinedMigrations/v2-v3/traverseFields.d.ts.map +1 -1
- package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.d.ts +15 -0
- package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.d.ts.map +1 -0
- package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.js +25 -0
- package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.js.map +1 -0
- package/dist/postgres/query/postgresUnaccent.d.ts +13 -0
- package/dist/postgres/query/postgresUnaccent.d.ts.map +1 -0
- package/dist/postgres/query/postgresUnaccent.js +40 -0
- package/dist/postgres/query/postgresUnaccent.js.map +1 -0
- 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/schema/buildDrizzleTable.d.ts.map +1 -1
- package/dist/postgres/schema/geometryColumn.d.ts +2 -2
- package/dist/postgres/schema/geometryColumn.d.ts.map +1 -1
- package/dist/postgres/types.d.ts +13 -2
- package/dist/postgres/types.d.ts.map +1 -1
- package/dist/postgres/types.js.map +1 -1
- package/dist/queries/addJoinTable.d.ts +1 -1
- package/dist/queries/addJoinTable.d.ts.map +1 -1
- package/dist/queries/buildOperatorConstraint.d.ts +22 -0
- package/dist/queries/buildOperatorConstraint.d.ts.map +1 -0
- package/dist/queries/buildOperatorConstraint.js +79 -0
- package/dist/queries/buildOperatorConstraint.js.map +1 -0
- package/dist/queries/buildOrderBy.d.ts +1 -1
- package/dist/queries/buildOrderBy.d.ts.map +1 -1
- package/dist/queries/buildQuery.d.ts.map +1 -1
- package/dist/queries/getTableAlias.d.ts.map +1 -1
- package/dist/queries/getTableColumnFromPath.d.ts +12 -3
- package/dist/queries/getTableColumnFromPath.d.ts.map +1 -1
- package/dist/queries/getTableColumnFromPath.js +65 -28
- package/dist/queries/getTableColumnFromPath.js.map +1 -1
- package/dist/queries/operatorMap.d.ts +7 -3
- package/dist/queries/operatorMap.d.ts.map +1 -1
- package/dist/queries/operatorMap.js.map +1 -1
- package/dist/queries/parseParams.d.ts.map +1 -1
- package/dist/queries/parseParams.js +262 -10
- package/dist/queries/parseParams.js.map +1 -1
- package/dist/queries/resolveRelationshipPath.d.ts +36 -0
- package/dist/queries/resolveRelationshipPath.d.ts.map +1 -0
- package/dist/queries/resolveRelationshipPath.js +66 -0
- package/dist/queries/resolveRelationshipPath.js.map +1 -0
- package/dist/queries/sanitizeQueryValue.d.ts.map +1 -1
- package/dist/queries/sanitizeQueryValue.js +6 -2
- package/dist/queries/sanitizeQueryValue.js.map +1 -1
- package/dist/queries/selectDistinct.d.ts.map +1 -1
- package/dist/queries/validateOperatorHandlers.d.ts +8 -0
- package/dist/queries/validateOperatorHandlers.d.ts.map +1 -0
- package/dist/queries/validateOperatorHandlers.js +30 -0
- package/dist/queries/validateOperatorHandlers.js.map +1 -0
- package/dist/schema/build.d.ts.map +1 -1
- package/dist/schema/build.js +54 -5
- package/dist/schema/build.js.map +1 -1
- package/dist/schema/buildDrizzleRelations.d.ts.map +1 -1
- package/dist/schema/buildRawSchema.d.ts.map +1 -1
- package/dist/schema/idToUUID.d.ts.map +1 -1
- package/dist/schema/traverseFields.d.ts.map +1 -1
- package/dist/schema/traverseFields.js +77 -19
- package/dist/schema/traverseFields.js.map +1 -1
- package/dist/schema/withDefault.d.ts.map +1 -1
- package/dist/sqlite/createJSONQuery/convertPathToJSONTraversal.d.ts.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 +4 -1
- 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/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 +2 -5
- package/dist/transactions/commitTransaction.js.map +1 -1
- package/dist/transform/read/hasManyNumber.d.ts.map +1 -1
- package/dist/transform/read/hasManyText.d.ts.map +1 -1
- package/dist/transform/read/index.d.ts.map +1 -1
- package/dist/transform/read/relationship.d.ts.map +1 -1
- package/dist/transform/read/traverseFields.d.ts.map +1 -1
- package/dist/transform/read/traverseFields.js +11 -3
- 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 +5 -2
- 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 +5 -1
- package/dist/transform/write/index.js.map +1 -1
- package/dist/transform/write/numbers.d.ts.map +1 -1
- package/dist/transform/write/relationships.d.ts.map +1 -1
- package/dist/transform/write/selects.d.ts.map +1 -1
- package/dist/transform/write/texts.d.ts.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 +39 -16
- 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/types.d.ts +52 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/updateJobs.d.ts.map +1 -1
- package/dist/updateJobs.js +37 -0
- package/dist/updateJobs.js.map +1 -1
- package/dist/updateOne.d.ts.map +1 -1
- package/dist/updateOne.js +54 -1
- package/dist/updateOne.js.map +1 -1
- package/dist/upsertRow/deleteExistingArrayRows.d.ts.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/handleUpsertError.d.ts.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 +57 -13
- package/dist/upsertRow/index.js.map +1 -1
- package/dist/upsertRow/insertArrays.d.ts.map +1 -1
- package/dist/upsertRow/insertArrays.js +4 -4
- package/dist/upsertRow/insertArrays.js.map +1 -1
- package/dist/upsertRow/shouldUseOptimizedUpsertRow.d.ts.map +1 -1
- package/dist/utilities/appendPrefixToKeys.d.ts.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.d.ts.map +1 -1
- package/dist/utilities/buildCreateMigration.js +13 -9
- 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/buildForeignKeyName.d.ts.map +1 -1
- package/dist/utilities/buildForeignKeyName.js +3 -2
- package/dist/utilities/buildForeignKeyName.js.map +1 -1
- package/dist/utilities/buildIndexName.d.ts.map +1 -1
- package/dist/utilities/buildIndexName.js +3 -2
- package/dist/utilities/buildIndexName.js.map +1 -1
- package/dist/utilities/checkTruncatedIdentifiers.d.ts +13 -0
- package/dist/utilities/checkTruncatedIdentifiers.d.ts.map +1 -0
- package/dist/utilities/checkTruncatedIdentifiers.js +56 -0
- package/dist/utilities/checkTruncatedIdentifiers.js.map +1 -0
- package/dist/utilities/createBlocksMap.d.ts.map +1 -1
- package/dist/utilities/createRelationshipMap.d.ts.map +1 -1
- package/dist/utilities/createSchemaGenerator.d.ts.map +1 -1
- package/dist/utilities/createSchemaGenerator.js +27 -13
- package/dist/utilities/createSchemaGenerator.js.map +1 -1
- package/dist/utilities/escapeSQLValue.d.ts.map +1 -1
- package/dist/utilities/executeSchemaHooks.d.ts.map +1 -1
- package/dist/utilities/executeSchemaHooks.js +1 -1
- package/dist/utilities/executeSchemaHooks.js.map +1 -1
- package/dist/utilities/extendDrizzleTable.d.ts.map +1 -1
- 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/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/getArrayRelationName.d.ts.map +1 -1
- package/dist/utilities/getCollectionIdType.d.ts.map +1 -1
- package/dist/utilities/getMigrationTemplate.d.ts.map +1 -1
- package/dist/utilities/getNameFromDrizzleTable.d.ts.map +1 -1
- package/dist/utilities/getPrimaryDb.d.ts +1 -1
- package/dist/utilities/getPrimaryDb.d.ts.map +1 -1
- package/dist/utilities/getSizesToVariantsRenames.d.ts +54 -0
- package/dist/utilities/getSizesToVariantsRenames.d.ts.map +1 -0
- package/dist/utilities/getSizesToVariantsRenames.js +252 -0
- package/dist/utilities/getSizesToVariantsRenames.js.map +1 -0
- package/dist/utilities/getTransaction.d.ts +1 -1
- package/dist/utilities/getTransaction.d.ts.map +1 -1
- package/dist/utilities/getTransaction.js.map +1 -1
- package/dist/utilities/hasLocalesTable.d.ts.map +1 -1
- package/dist/utilities/isPolymorphicRelationship.d.ts.map +1 -1
- package/dist/utilities/isUUIDType.d.ts.map +1 -1
- package/dist/utilities/json.d.ts.map +1 -1
- package/dist/utilities/migrationTableExists.d.ts.map +1 -1
- package/dist/utilities/parseError.d.ts.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.d.ts.map +1 -1
- package/dist/utilities/pushDevSchema.js +1 -1
- package/dist/utilities/pushDevSchema.js.map +1 -1
- package/dist/utilities/rawConstraint.d.ts.map +1 -1
- package/dist/utilities/sanitizePathSegment.d.ts.map +1 -1
- package/dist/utilities/validateExistingBlockIsIdentical.d.ts +1 -5
- package/dist/utilities/validateExistingBlockIsIdentical.d.ts.map +1 -1
- package/dist/utilities/validateExistingBlockIsIdentical.js.map +1 -1
- package/dist/utilities/validateIdentifierLength.d.ts +12 -0
- package/dist/utilities/validateIdentifierLength.d.ts.map +1 -0
- package/dist/utilities/validateIdentifierLength.js +18 -0
- package/dist/utilities/validateIdentifierLength.js.map +1 -0
- package/package.json +17 -19
- 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/isValidStringID.spec.js +0 -15
- package/dist/utilities/isValidStringID.spec.js.map +0 -1
|
@@ -5,12 +5,12 @@ import prompts from 'prompts';
|
|
|
5
5
|
import { getMigrationTemplate } from './getMigrationTemplate.js';
|
|
6
6
|
export const buildCreateMigration = ({ executeMethod, filename, sanitizeStatements })=>{
|
|
7
7
|
const dirname = path.dirname(filename);
|
|
8
|
-
return async function createMigration({ file, forceAcceptWarning, migrationName, payload, skipEmpty }) {
|
|
8
|
+
return async function createMigration({ file, forceAcceptWarning, migrationName, payload, shouldPrompt = true, skipEmpty }) {
|
|
9
9
|
const dir = payload.db.migrationDir;
|
|
10
10
|
if (!fs.existsSync(dir)) {
|
|
11
11
|
fs.mkdirSync(dir);
|
|
12
12
|
}
|
|
13
|
-
const { generateDrizzleJson, generateMigration, upSnapshot } = this.requireDrizzleKit();
|
|
13
|
+
const { generateDrizzleJson, generateMigration, upSnapshot } = await this.requireDrizzleKit();
|
|
14
14
|
const drizzleJsonAfter = await generateDrizzleJson(this.schema);
|
|
15
15
|
const [yyymmdd, hhmmss] = new Date().toISOString().split('T');
|
|
16
16
|
const formattedDate = yyymmdd.replace(/\D/g, '');
|
|
@@ -80,21 +80,21 @@ export const buildCreateMigration = ({ executeMethod, filename, sanitizeStatemen
|
|
|
80
80
|
});
|
|
81
81
|
}
|
|
82
82
|
if (!upSQL?.length && !downSQL?.length && !forceAcceptWarning) {
|
|
83
|
-
if (skipEmpty) {
|
|
84
|
-
|
|
83
|
+
if (skipEmpty || !shouldPrompt) {
|
|
84
|
+
return {
|
|
85
|
+
created: false
|
|
86
|
+
};
|
|
85
87
|
}
|
|
86
88
|
const { confirm: shouldCreateBlankMigration } = await prompts({
|
|
87
89
|
name: 'confirm',
|
|
88
90
|
type: 'confirm',
|
|
89
91
|
initial: false,
|
|
90
92
|
message: 'No schema changes detected. Would you like to create a blank migration file?'
|
|
91
|
-
}, {
|
|
92
|
-
onCancel: ()=>{
|
|
93
|
-
process.exit(0);
|
|
94
|
-
}
|
|
95
93
|
});
|
|
96
94
|
if (!shouldCreateBlankMigration) {
|
|
97
|
-
|
|
95
|
+
return {
|
|
96
|
+
created: false
|
|
97
|
+
};
|
|
98
98
|
}
|
|
99
99
|
}
|
|
100
100
|
// write schema
|
|
@@ -115,6 +115,10 @@ export const buildCreateMigration = ({ executeMethod, filename, sanitizeStatemen
|
|
|
115
115
|
payload.logger.info({
|
|
116
116
|
msg: `Migration created at ${fullPath}`
|
|
117
117
|
});
|
|
118
|
+
return {
|
|
119
|
+
created: true,
|
|
120
|
+
path: fullPath
|
|
121
|
+
};
|
|
118
122
|
};
|
|
119
123
|
};
|
|
120
124
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/buildCreateMigration.ts"],"sourcesContent":["import type { DrizzleSnapshotJSON } from 'drizzle-kit/api'\nimport type { CreateMigration
|
|
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;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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,SA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YACA,MAAMC,mBAAmBH,aAAaV,GAAG,CAAC,CAACM,SACzC,OAAOA,WAAW,WAAWA,SAASA,OAAOK,UAAU;YAEzD,MAAMG,SAASxB,QAAQM,IAAI,CACzB,CAACmB,UAAYA,QAAQ1B,OAAO,CAAC2B,IAAI,CAAC,SAASH,iBAAiBG,IAAI,CAAC;YAGnE,IAAI,CAACF,QAAQ;gBACX;YACF;YAEA,IAAIP,QAAQO,OAAOZ,EAAE,IAAIV,MAAMF,OAAO,EAAE,CAACwB,OAAOZ,EAAE,CAAC,EAAE;gBACnD,MAAM,IAAIE,MACR,CAAC,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":"buildForeignKeyName.d.ts","sourceRoot":"","sources":["../../src/utilities/buildForeignKeyName.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;
|
|
1
|
+
{"version":3,"file":"buildForeignKeyName.d.ts","sourceRoot":"","sources":["../../src/utilities/buildForeignKeyName.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAIjD,eAAO,MAAM,mBAAmB,+BAI7B;IACD,OAAO,EAAE,cAAc,CAAA;IACvB,IAAI,EAAE,MAAM,CAAA;IACZ,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB,KAAG,MAkBH,CAAA"}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
+
import { maxGeneratedIdentifierLength } from './validateIdentifierLength.js';
|
|
1
2
|
export const buildForeignKeyName = ({ name, adapter, number = 0 })=>{
|
|
2
3
|
let foreignKeyName = `${name}${number ? `_${number}` : ''}_fk`;
|
|
3
|
-
if (foreignKeyName.length >
|
|
4
|
+
if (foreignKeyName.length > maxGeneratedIdentifierLength) {
|
|
4
5
|
const suffix = `${number ? `_${number}` : ''}_fk`;
|
|
5
|
-
foreignKeyName = `${name.slice(0,
|
|
6
|
+
foreignKeyName = `${name.slice(0, maxGeneratedIdentifierLength - suffix.length)}${suffix}`;
|
|
6
7
|
}
|
|
7
8
|
if (!adapter.foreignKeys.has(foreignKeyName)) {
|
|
8
9
|
adapter.foreignKeys.add(foreignKeyName);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/buildForeignKeyName.ts"],"sourcesContent":["import type { DrizzleAdapter } from '../types.js'\n\nexport const buildForeignKeyName = ({\n name,\n adapter,\n number = 0,\n}: {\n adapter: DrizzleAdapter\n name: string\n number?: number\n}): string => {\n let foreignKeyName = `${name}${number ? `_${number}` : ''}_fk`\n\n if (foreignKeyName.length >
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/buildForeignKeyName.ts"],"sourcesContent":["import type { DrizzleAdapter } from '../types.js'\n\nimport { maxGeneratedIdentifierLength } from './validateIdentifierLength.js'\n\nexport const buildForeignKeyName = ({\n name,\n adapter,\n number = 0,\n}: {\n adapter: DrizzleAdapter\n name: string\n number?: number\n}): string => {\n let foreignKeyName = `${name}${number ? `_${number}` : ''}_fk`\n\n if (foreignKeyName.length > maxGeneratedIdentifierLength) {\n const suffix = `${number ? `_${number}` : ''}_fk`\n foreignKeyName = `${name.slice(0, maxGeneratedIdentifierLength - suffix.length)}${suffix}`\n }\n\n if (!adapter.foreignKeys.has(foreignKeyName)) {\n adapter.foreignKeys.add(foreignKeyName)\n return foreignKeyName\n }\n\n return buildForeignKeyName({\n name,\n adapter,\n number: number + 1,\n })\n}\n"],"names":["maxGeneratedIdentifierLength","buildForeignKeyName","name","adapter","number","foreignKeyName","length","suffix","slice","foreignKeys","has","add"],"mappings":"AAEA,SAASA,4BAA4B,QAAQ,gCAA+B;AAE5E,OAAO,MAAMC,sBAAsB,CAAC,EAClCC,IAAI,EACJC,OAAO,EACPC,SAAS,CAAC,EAKX;IACC,IAAIC,iBAAiB,GAAGH,OAAOE,SAAS,CAAC,CAAC,EAAEA,QAAQ,GAAG,GAAG,GAAG,CAAC;IAE9D,IAAIC,eAAeC,MAAM,GAAGN,8BAA8B;QACxD,MAAMO,SAAS,GAAGH,SAAS,CAAC,CAAC,EAAEA,QAAQ,GAAG,GAAG,GAAG,CAAC;QACjDC,iBAAiB,GAAGH,KAAKM,KAAK,CAAC,GAAGR,+BAA+BO,OAAOD,MAAM,IAAIC,QAAQ;IAC5F;IAEA,IAAI,CAACJ,QAAQM,WAAW,CAACC,GAAG,CAACL,iBAAiB;QAC5CF,QAAQM,WAAW,CAACE,GAAG,CAACN;QACxB,OAAOA;IACT;IAEA,OAAOJ,oBAAoB;QACzBC;QACAC;QACAC,QAAQA,SAAS;IACnB;AACF,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"buildIndexName.d.ts","sourceRoot":"","sources":["../../src/utilities/buildIndexName.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;
|
|
1
|
+
{"version":3,"file":"buildIndexName.d.ts","sourceRoot":"","sources":["../../src/utilities/buildIndexName.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAIjD,eAAO,MAAM,cAAc,6CAKxB;IACD,OAAO,EAAE,cAAc,CAAA;IACvB,YAAY,CAAC,EAAE,OAAO,CAAA;IACtB,IAAI,EAAE,MAAM,CAAA;IACZ,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB,KAAG,MAmBH,CAAA"}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
+
import { maxGeneratedIdentifierLength } from './validateIdentifierLength.js';
|
|
1
2
|
export const buildIndexName = ({ name, adapter, appendSuffix = true, number = 0 })=>{
|
|
2
3
|
let indexName = `${name}${number ? `_${number}` : ''}${appendSuffix ? '_idx' : ''}`;
|
|
3
|
-
if (indexName.length >
|
|
4
|
+
if (indexName.length > maxGeneratedIdentifierLength) {
|
|
4
5
|
const suffix = `${number ? `_${number}` : ''}${appendSuffix ? '_idx' : ''}`;
|
|
5
|
-
indexName = `${name.slice(0,
|
|
6
|
+
indexName = `${name.slice(0, maxGeneratedIdentifierLength - suffix.length)}${suffix}`;
|
|
6
7
|
}
|
|
7
8
|
if (!adapter.indexes.has(indexName) && !(indexName in adapter.rawTables)) {
|
|
8
9
|
adapter.indexes.add(indexName);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/buildIndexName.ts"],"sourcesContent":["import type { DrizzleAdapter } from '../types.js'\n\nexport const buildIndexName = ({\n name,\n adapter,\n appendSuffix = true,\n number = 0,\n}: {\n adapter: DrizzleAdapter\n appendSuffix?: boolean\n name: string\n number?: number\n}): string => {\n let indexName = `${name}${number ? `_${number}` : ''}${appendSuffix ? '_idx' : ''}`\n\n if (indexName.length >
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/buildIndexName.ts"],"sourcesContent":["import type { DrizzleAdapter } from '../types.js'\n\nimport { maxGeneratedIdentifierLength } from './validateIdentifierLength.js'\n\nexport const buildIndexName = ({\n name,\n adapter,\n appendSuffix = true,\n number = 0,\n}: {\n adapter: DrizzleAdapter\n appendSuffix?: boolean\n name: string\n number?: number\n}): string => {\n let indexName = `${name}${number ? `_${number}` : ''}${appendSuffix ? '_idx' : ''}`\n\n if (indexName.length > maxGeneratedIdentifierLength) {\n const suffix = `${number ? `_${number}` : ''}${appendSuffix ? '_idx' : ''}`\n indexName = `${name.slice(0, maxGeneratedIdentifierLength - suffix.length)}${suffix}`\n }\n\n if (!adapter.indexes.has(indexName) && !(indexName in adapter.rawTables)) {\n adapter.indexes.add(indexName)\n return indexName\n }\n\n return buildIndexName({\n name,\n adapter,\n appendSuffix,\n number: number + 1,\n })\n}\n"],"names":["maxGeneratedIdentifierLength","buildIndexName","name","adapter","appendSuffix","number","indexName","length","suffix","slice","indexes","has","rawTables","add"],"mappings":"AAEA,SAASA,4BAA4B,QAAQ,gCAA+B;AAE5E,OAAO,MAAMC,iBAAiB,CAAC,EAC7BC,IAAI,EACJC,OAAO,EACPC,eAAe,IAAI,EACnBC,SAAS,CAAC,EAMX;IACC,IAAIC,YAAY,GAAGJ,OAAOG,SAAS,CAAC,CAAC,EAAEA,QAAQ,GAAG,KAAKD,eAAe,SAAS,IAAI;IAEnF,IAAIE,UAAUC,MAAM,GAAGP,8BAA8B;QACnD,MAAMQ,SAAS,GAAGH,SAAS,CAAC,CAAC,EAAEA,QAAQ,GAAG,KAAKD,eAAe,SAAS,IAAI;QAC3EE,YAAY,GAAGJ,KAAKO,KAAK,CAAC,GAAGT,+BAA+BQ,OAAOD,MAAM,IAAIC,QAAQ;IACvF;IAEA,IAAI,CAACL,QAAQO,OAAO,CAACC,GAAG,CAACL,cAAc,CAAEA,CAAAA,aAAaH,QAAQS,SAAS,AAAD,GAAI;QACxET,QAAQO,OAAO,CAACG,GAAG,CAACP;QACpB,OAAOA;IACT;IAEA,OAAOL,eAAe;QACpBC;QACAC;QACAC;QACAC,QAAQA,SAAS;IACnB;AACF,EAAC"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { DrizzleAdapter } from '../types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Warns about identifiers Postgres will silently truncate past 63 chars, and throws
|
|
4
|
+
* when two of them truncate to the same name (a schema Postgres can't create anyway).
|
|
5
|
+
*
|
|
6
|
+
* Base table/enum names throw during construction, so this only covers concatenated
|
|
7
|
+
* identifiers: companion tables, columns, and inline index/foreign key names.
|
|
8
|
+
*/
|
|
9
|
+
export declare const checkTruncatedIdentifiers: ({ adapter, logWarnings, }: {
|
|
10
|
+
adapter: Pick<DrizzleAdapter, 'payload' | 'rawTables'>;
|
|
11
|
+
logWarnings: boolean;
|
|
12
|
+
}) => void;
|
|
13
|
+
//# sourceMappingURL=checkTruncatedIdentifiers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"checkTruncatedIdentifiers.d.ts","sourceRoot":"","sources":["../../src/utilities/checkTruncatedIdentifiers.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAOjD;;;;;;GAMG;AACH,eAAO,MAAM,yBAAyB,8BAGnC;IACD,OAAO,EAAE,IAAI,CAAC,cAAc,EAAE,SAAS,GAAG,WAAW,CAAC,CAAA;IACtD,WAAW,EAAE,OAAO,CAAA;CACrB,KAAG,IAgEH,CAAA"}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { APIError } from 'payload';
|
|
2
|
+
import { maxIdentifierLength } from './validateIdentifierLength.js';
|
|
3
|
+
const truncate = (name)=>name.length > maxIdentifierLength ? name.slice(0, maxIdentifierLength) : name;
|
|
4
|
+
/**
|
|
5
|
+
* Warns about identifiers Postgres will silently truncate past 63 chars, and throws
|
|
6
|
+
* when two of them truncate to the same name (a schema Postgres can't create anyway).
|
|
7
|
+
*
|
|
8
|
+
* Base table/enum names throw during construction, so this only covers concatenated
|
|
9
|
+
* identifiers: companion tables, columns, and inline index/foreign key names.
|
|
10
|
+
*/ export const checkTruncatedIdentifiers = ({ adapter, logWarnings })=>{
|
|
11
|
+
const truncatedNames = new Set();
|
|
12
|
+
const collisions = new Set();
|
|
13
|
+
// finalName -> originalName, per namespace, to detect post-truncation collisions
|
|
14
|
+
const tableNames = new Map();
|
|
15
|
+
const indexNames = new Map();
|
|
16
|
+
const foreignKeyNames = new Map();
|
|
17
|
+
const check = (original, seen)=>{
|
|
18
|
+
const final = truncate(original);
|
|
19
|
+
const existing = seen.get(final);
|
|
20
|
+
if (existing !== undefined && existing !== original) {
|
|
21
|
+
collisions.add(`"${existing}" and "${original}" both become "${final}"`);
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
seen.set(final, original);
|
|
25
|
+
if (final !== original) {
|
|
26
|
+
truncatedNames.add(original);
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
for(const tableName in adapter.rawTables){
|
|
30
|
+
const table = adapter.rawTables[tableName];
|
|
31
|
+
check(table.name, tableNames);
|
|
32
|
+
// Columns only collide with other columns in the same table.
|
|
33
|
+
const columnNames = new Map();
|
|
34
|
+
for(const columnKey in table.columns){
|
|
35
|
+
check(table.columns[columnKey].name, columnNames);
|
|
36
|
+
}
|
|
37
|
+
if (table.indexes) {
|
|
38
|
+
for(const indexKey in table.indexes){
|
|
39
|
+
check(table.indexes[indexKey].name, indexNames);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
if (table.foreignKeys) {
|
|
43
|
+
for(const foreignKeyKey in table.foreignKeys){
|
|
44
|
+
check(table.foreignKeys[foreignKeyKey].name, foreignKeyNames);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
if (collisions.size > 0) {
|
|
49
|
+
throw new APIError(`Multiple identifiers exceed Postgres's ${maxIdentifierLength}-character limit and truncate to the same name, which Postgres cannot create: ${Array.from(collisions).join('; ')}. Use the dbName property to give them shorter, distinct names.`);
|
|
50
|
+
}
|
|
51
|
+
if (logWarnings && truncatedNames.size > 0) {
|
|
52
|
+
adapter.payload.logger.warn(`The following identifiers exceed Postgres's ${maxIdentifierLength}-character limit and will be silently truncated, which can leave the database out of sync with your Payload schema: ${Array.from(truncatedNames).join(', ')}. Use the dbName property to shorten them.`);
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
//# sourceMappingURL=checkTruncatedIdentifiers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/checkTruncatedIdentifiers.ts"],"sourcesContent":["import { APIError } from 'payload'\n\nimport type { DrizzleAdapter } from '../types.js'\n\nimport { maxIdentifierLength } from './validateIdentifierLength.js'\n\nconst truncate = (name: string): string =>\n name.length > maxIdentifierLength ? name.slice(0, maxIdentifierLength) : name\n\n/**\n * Warns about identifiers Postgres will silently truncate past 63 chars, and throws\n * when two of them truncate to the same name (a schema Postgres can't create anyway).\n *\n * Base table/enum names throw during construction, so this only covers concatenated\n * identifiers: companion tables, columns, and inline index/foreign key names.\n */\nexport const checkTruncatedIdentifiers = ({\n adapter,\n logWarnings,\n}: {\n adapter: Pick<DrizzleAdapter, 'payload' | 'rawTables'>\n logWarnings: boolean\n}): void => {\n const truncatedNames = new Set<string>()\n const collisions = new Set<string>()\n\n // finalName -> originalName, per namespace, to detect post-truncation collisions\n const tableNames = new Map<string, string>()\n const indexNames = new Map<string, string>()\n const foreignKeyNames = new Map<string, string>()\n\n const check = (original: string, seen: Map<string, string>) => {\n const final = truncate(original)\n\n const existing = seen.get(final)\n if (existing !== undefined && existing !== original) {\n collisions.add(`\"${existing}\" and \"${original}\" both become \"${final}\"`)\n return\n }\n\n seen.set(final, original)\n\n if (final !== original) {\n truncatedNames.add(original)\n }\n }\n\n for (const tableName in adapter.rawTables) {\n const table = adapter.rawTables[tableName]\n\n check(table.name, tableNames)\n\n // Columns only collide with other columns in the same table.\n const columnNames = new Map<string, string>()\n for (const columnKey in table.columns) {\n check(table.columns[columnKey].name, columnNames)\n }\n\n if (table.indexes) {\n for (const indexKey in table.indexes) {\n check(table.indexes[indexKey].name, indexNames)\n }\n }\n\n if (table.foreignKeys) {\n for (const foreignKeyKey in table.foreignKeys) {\n check(table.foreignKeys[foreignKeyKey].name, foreignKeyNames)\n }\n }\n }\n\n if (collisions.size > 0) {\n throw new APIError(\n `Multiple identifiers exceed Postgres's ${maxIdentifierLength}-character limit and truncate to the same name, which Postgres cannot create: ${Array.from(\n collisions,\n ).join('; ')}. Use the dbName property to give them shorter, distinct names.`,\n )\n }\n\n if (logWarnings && truncatedNames.size > 0) {\n adapter.payload.logger.warn(\n `The following identifiers exceed Postgres's ${maxIdentifierLength}-character limit and will be silently truncated, which can leave the database out of sync with your Payload schema: ${Array.from(\n truncatedNames,\n ).join(', ')}. Use the dbName property to shorten them.`,\n )\n }\n}\n"],"names":["APIError","maxIdentifierLength","truncate","name","length","slice","checkTruncatedIdentifiers","adapter","logWarnings","truncatedNames","Set","collisions","tableNames","Map","indexNames","foreignKeyNames","check","original","seen","final","existing","get","undefined","add","set","tableName","rawTables","table","columnNames","columnKey","columns","indexes","indexKey","foreignKeys","foreignKeyKey","size","Array","from","join","payload","logger","warn"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,UAAS;AAIlC,SAASC,mBAAmB,QAAQ,gCAA+B;AAEnE,MAAMC,WAAW,CAACC,OAChBA,KAAKC,MAAM,GAAGH,sBAAsBE,KAAKE,KAAK,CAAC,GAAGJ,uBAAuBE;AAE3E;;;;;;CAMC,GACD,OAAO,MAAMG,4BAA4B,CAAC,EACxCC,OAAO,EACPC,WAAW,EAIZ;IACC,MAAMC,iBAAiB,IAAIC;IAC3B,MAAMC,aAAa,IAAID;IAEvB,iFAAiF;IACjF,MAAME,aAAa,IAAIC;IACvB,MAAMC,aAAa,IAAID;IACvB,MAAME,kBAAkB,IAAIF;IAE5B,MAAMG,QAAQ,CAACC,UAAkBC;QAC/B,MAAMC,QAAQjB,SAASe;QAEvB,MAAMG,WAAWF,KAAKG,GAAG,CAACF;QAC1B,IAAIC,aAAaE,aAAaF,aAAaH,UAAU;YACnDN,WAAWY,GAAG,CAAC,CAAC,CAAC,EAAEH,SAAS,OAAO,EAAEH,SAAS,eAAe,EAAEE,MAAM,CAAC,CAAC;YACvE;QACF;QAEAD,KAAKM,GAAG,CAACL,OAAOF;QAEhB,IAAIE,UAAUF,UAAU;YACtBR,eAAec,GAAG,CAACN;QACrB;IACF;IAEA,IAAK,M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;CAC1C,CAAA;AAED,eAAO,MAAM,eAAe,
|
|
1
|
+
{"version":3,"file":"createBlocksMap.d.ts","sourceRoot":"","sources":["../../src/utilities/createBlocksMap.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,SAAS,GAAG;IACtB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAA;CAC1C,CAAA;AAED,eAAO,MAAM,eAAe,SAAU,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAG,SAyC/D,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createRelationshipMap.d.ts","sourceRoot":"","sources":["../../src/utilities/createRelationshipMap.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,aAAa,
|
|
1
|
+
{"version":3,"file":"createRelationshipMap.d.ts","sourceRoot":"","sources":["../../src/utilities/createRelationshipMap.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,aAAa,SAAU,OAAO,KAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAqBrF,CAAA"}
|
|
@@ -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,cAwUH,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
|
|
@@ -75,7 +76,15 @@ export const createSchemaGenerator = ({ columnToCodeConverter, corePackageSuffix
|
|
|
75
76
|
fkGraph[tableName].add(col.reference.table);
|
|
76
77
|
}
|
|
77
78
|
}
|
|
79
|
+
for(const fkKey in table.foreignKeys ?? {}){
|
|
80
|
+
for (const foreignColumn of table.foreignKeys[fkKey].foreignColumns){
|
|
81
|
+
if (foreignColumn.table !== tableName) {
|
|
82
|
+
fkGraph[tableName].add(foreignColumn.table);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
78
86
|
}
|
|
87
|
+
const extraConfigType = corePackageSuffix === 'pg-core' ? 'PgTableExtraConfigValue' : 'SQLiteTableExtraConfigValue';
|
|
79
88
|
const canReach = (from, target, visited)=>{
|
|
80
89
|
if (from === target) {
|
|
81
90
|
return true;
|
|
@@ -102,6 +111,14 @@ export const createSchemaGenerator = ({ columnToCodeConverter, corePackageSuffix
|
|
|
102
111
|
for(const tableName in this.rawTables){
|
|
103
112
|
const table = this.rawTables[tableName];
|
|
104
113
|
const extrasDeclarations = [];
|
|
114
|
+
/**
|
|
115
|
+
* A table-level foreign key to its own table, or to a table that points back at it, makes
|
|
116
|
+
* TypeScript infer the table's type from its own initializer (TS7022). An explicit return
|
|
117
|
+
* type on the extras callback breaks that cycle, like `AnyPgColumn` does for `.references()`.
|
|
118
|
+
*/ const extrasNeedReturnType = Object.values(table.foreignKeys ?? {}).some((foreignKey)=>foreignKey.foreignColumns.some((foreignColumn)=>foreignColumn.table === tableName || circularEdges.has(`${tableName}:${foreignColumn.table}`)));
|
|
119
|
+
if (extrasNeedReturnType) {
|
|
120
|
+
addImport(corePackage, `type ${extraConfigType}`);
|
|
121
|
+
}
|
|
105
122
|
if (table.indexes) {
|
|
106
123
|
for(const key in table.indexes){
|
|
107
124
|
const index = table.indexes[key];
|
|
@@ -139,7 +156,7 @@ ${Object.entries(table.columns).map(([key, column])=>` ${sanitizeObjectKey(key)
|
|
|
139
156
|
locales: this.payload.config.localization ? this.payload.config.localization.localeCodes : undefined,
|
|
140
157
|
tableKey: tableName
|
|
141
158
|
})},`).join('\n')}
|
|
142
|
-
}${extrasDeclarations.length ? `, (columns) => [
|
|
159
|
+
}${extrasDeclarations.length ? `, (columns)${extrasNeedReturnType ? `: ${extraConfigType}[]` : ''} => [
|
|
143
160
|
${extrasDeclarations.join(' ')}
|
|
144
161
|
]` : ''}
|
|
145
162
|
)
|
|
@@ -215,7 +232,7 @@ declare module '${this.packageName}' {
|
|
|
215
232
|
*/
|
|
216
233
|
`;
|
|
217
234
|
const importTypes = `import type {} from '${this.packageName}'`;
|
|
218
|
-
|
|
235
|
+
const code = [
|
|
219
236
|
warning,
|
|
220
237
|
importTypes,
|
|
221
238
|
...importDeclarationsSanitized,
|
|
@@ -235,22 +252,19 @@ declare module '${this.packageName}' {
|
|
|
235
252
|
outputFile = path.resolve(cwd, 'payload-generated-schema.ts');
|
|
236
253
|
}
|
|
237
254
|
}
|
|
255
|
+
await writeFile(outputFile, code, 'utf-8');
|
|
238
256
|
if (prettify) {
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
code = await prettier.format(code, {
|
|
244
|
-
...config,
|
|
245
|
-
parser: 'typescript'
|
|
246
|
-
});
|
|
247
|
-
} catch {
|
|
248
|
-
/* empty */ }
|
|
257
|
+
await formatGeneratedFile({
|
|
258
|
+
filePath: outputFile,
|
|
259
|
+
logger: this.payload.logger
|
|
260
|
+
});
|
|
249
261
|
}
|
|
250
|
-
await writeFile(outputFile, code, 'utf-8');
|
|
251
262
|
if (log) {
|
|
252
263
|
this.payload.logger.info(`Written ${outputFile}`);
|
|
253
264
|
}
|
|
265
|
+
return {
|
|
266
|
+
outputFile
|
|
267
|
+
};
|
|
254
268
|
};
|
|
255
269
|
};
|
|
256
270
|
|