0
# Migration Utilities
1
2
Migration helper functions for upgrading PostgreSQL database schemas from older versions of Payload CMS. These utilities handle schema transformation and data migration between major versions.
3
4
## Capabilities
5
6
### Postgres V2 to V3 Migration
7
8
Migrates PostgreSQL database schemas from Payload CMS v2 format to v3 format, handling schema changes, relationship structures, and data transformations.
9
10
```typescript { .api }
11
/**
12
* Migrates PostgreSQL database from Payload v2 to v3 format
13
* @param args - Migration arguments containing database and payload instances
14
* @returns Promise that resolves when migration is complete
15
*/
16
function migratePostgresV2toV3(args: MigrateUpArgs): Promise<void>;
17
```
18
19
**Usage Examples:**
20
21
```typescript
22
import { migratePostgresV2toV3 } from '@payloadcms/db-postgres/migration-utils';
23
24
// In a custom migration file
25
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
26
// Run the v2 to v3 migration
27
await migratePostgresV2toV3({ db, payload, req });
28
29
// Additional custom migration logic
30
console.log('Migration from v2 to v3 completed');
31
}
32
```
33
34
```typescript
35
// Using in production migrations configuration
36
import { postgresAdapter } from '@payloadcms/db-postgres';
37
import { migratePostgresV2toV3 } from '@payloadcms/db-postgres/migration-utils';
38
39
export default buildConfig({
40
db: postgresAdapter({
41
pool: { connectionString: process.env.DATABASE_URI },
42
prodMigrations: [
43
{
44
name: 'v2-to-v3-migration',
45
up: migratePostgresV2toV3,
46
down: async ({ db, payload, req }) => {
47
throw new Error('Downgrade from v3 to v2 not supported');
48
},
49
},
50
],
51
}),
52
});
53
```
54
55
## Migration Process
56
57
The v2 to v3 migration handles several key transformations:
58
59
### Schema Changes
60
- Updates table structures to match v3 requirements
61
- Modifies column types and constraints
62
- Adjusts index definitions
63
- Updates foreign key relationships
64
65
### Relationship Updates
66
- Converts v2 relationship format to v3 structure
67
- Updates join tables and reference columns
68
- Preserves relationship data integrity
69
70
### Data Transformation
71
- Converts field formats between versions
72
- Updates JSON structures in database
73
- Handles locale and version data migration
74
- Preserves all existing content
75
76
### Version Control
77
- Maintains version history during migration
78
- Updates version metadata format
79
- Ensures draft/published status consistency
80
81
## Migration Arguments
82
83
```typescript { .api }
84
interface MigrateUpArgs {
85
/** The Postgres Drizzle instance for executing SQL directly within the current transaction */
86
db: PostgresDB;
87
88
/** Payload CMS instance for Local API methods */
89
payload: Payload;
90
91
/** PayloadRequest object containing the current transaction */
92
req: PayloadRequest;
93
}
94
95
interface MigrateDownArgs {
96
/** The Postgres Drizzle instance for executing SQL directly within the current transaction */
97
db: PostgresDB;
98
99
/** Payload CMS instance for Local API methods */
100
payload: Payload;
101
102
/** PayloadRequest object containing the current transaction */
103
req: PayloadRequest;
104
}
105
```
106
107
## Error Handling
108
109
The migration utility includes comprehensive error handling:
110
111
- **Schema Validation**: Verifies v2 schema structure before migration
112
- **Data Integrity**: Ensures no data loss during transformation
113
- **Rollback Support**: Provides transaction-based rollback on failure
114
- **Progress Logging**: Detailed logging of migration progress
115
- **Conflict Resolution**: Handles naming conflicts and duplicate data
116
117
## Best Practices
118
119
### Pre-Migration Steps
120
1. **Backup Database**: Always create a full database backup before migration
121
2. **Test Environment**: Run migration in staging environment first
122
3. **Schema Analysis**: Review current schema for custom modifications
123
4. **Downtime Planning**: Plan for application downtime during migration
124
125
### During Migration
126
1. **Monitor Progress**: Watch migration logs for any warnings or errors
127
2. **Resource Monitoring**: Ensure adequate database resources
128
3. **Connection Management**: Verify stable database connections
129
4. **Data Validation**: Spot-check critical data during migration
130
131
### Post-Migration Steps
132
1. **Schema Verification**: Confirm v3 schema structure is correct
133
2. **Data Integrity**: Validate that all data migrated successfully
134
3. **Application Testing**: Test application functionality with new schema
135
4. **Performance Check**: Monitor query performance after migration
136
137
```typescript
138
// Example comprehensive migration setup
139
import { postgresAdapter } from '@payloadcms/db-postgres';
140
import { migratePostgresV2toV3 } from '@payloadcms/db-postgres/migration-utils';
141
142
export default buildConfig({
143
db: postgresAdapter({
144
pool: {
145
connectionString: process.env.DATABASE_URI,
146
max: 20, // Ensure adequate connections for migration
147
},
148
logger: console, // Enable logging for migration monitoring
149
prodMigrations: [
150
{
151
name: 'payload-v2-to-v3',
152
up: async ({ db, payload, req }) => {
153
console.log('Starting Payload v2 to v3 migration...');
154
155
try {
156
await migratePostgresV2toV3({ db, payload, req });
157
console.log('Migration completed successfully');
158
} catch (error) {
159
console.error('Migration failed:', error);
160
throw error; // This will trigger rollback
161
}
162
},
163
down: async ({ db, payload, req }) => {
164
throw new Error('Downgrade from v3 to v2 is not supported');
165
},
166
},
167
],
168
}),
169
});
170
```