0
# Migration Management
1
2
Declarative data modeling and migration system with development and production workflows, providing version control for database schema changes.
3
4
## Capabilities
5
6
### Migration Development
7
8
Create and apply migrations during development with automatic migration generation and database synchronization.
9
10
```bash { .api }
11
/**
12
* Create and apply development migrations
13
* Generates migration files and applies them to development database
14
*/
15
prisma migrate dev [options]
16
17
Options:
18
--name <name> Migration name (required for first migration)
19
--schema <path> Custom schema file path
20
--create-only Create migration file without applying
21
--skip-generate Skip automatic Prisma Client generation
22
--skip-seed Skip automatic seeding after migration
23
--help/-h Show migrate dev command help
24
```
25
26
**Usage Examples:**
27
28
```bash
29
# Create and apply initial migration
30
prisma migrate dev --name init
31
32
# Create and apply named migration
33
prisma migrate dev --name add-user-profile
34
35
# Create migration file only (review before applying)
36
prisma migrate dev --create-only --name add-indexes
37
38
# Apply pending migrations without generating new ones
39
prisma migrate dev
40
41
# Skip client generation after migration
42
prisma migrate dev --skip-generate
43
```
44
45
### Migration Deployment
46
47
Deploy pending migrations to production environments with safety checks and rollback capabilities.
48
49
```bash { .api }
50
/**
51
* Deploy pending migrations to production
52
* Applies only unapplied migrations with safety checks
53
*/
54
prisma migrate deploy [options]
55
56
Options:
57
--schema <path> Custom schema file path
58
--help/-h Show migrate deploy command help
59
```
60
61
**Usage Examples:**
62
63
```bash
64
# Deploy all pending migrations
65
prisma migrate deploy
66
67
# Deploy with custom schema location
68
prisma migrate deploy --schema ./custom/schema.prisma
69
```
70
71
### Migration Status
72
73
Check migration status and view pending, applied, and failed migrations.
74
75
```bash { .api }
76
/**
77
* Check migration status and history
78
* Shows applied, pending, and failed migrations
79
*/
80
prisma migrate status [options]
81
82
Options:
83
--schema <path> Custom schema file path
84
--help/-h Show migrate status command help
85
```
86
87
**Usage Examples:**
88
89
```bash
90
# Check migration status
91
prisma migrate status
92
93
# Check status with custom schema
94
prisma migrate status --schema ./custom/schema.prisma
95
```
96
97
**Status Output Example:**
98
99
```
100
Database schema is up to date!
101
102
The following migrations have been applied:
103
✓ 20240101120000_init
104
✓ 20240102130000_add_user_profile
105
✓ 20240103140000_add_indexes
106
107
No pending migrations found.
108
```
109
110
### Migration Reset
111
112
Reset database by dropping all data and reapplying all migrations from the beginning.
113
114
```bash { .api }
115
/**
116
* Reset database and reapply all migrations
117
* Drops all data and recreates database from migrations
118
*/
119
prisma migrate reset [options]
120
121
Options:
122
--schema <path> Custom schema file path
123
--force Skip confirmation prompt
124
--skip-generate Skip automatic Prisma Client generation
125
--skip-seed Skip automatic seeding after reset
126
--help/-h Show migrate reset command help
127
```
128
129
**Usage Examples:**
130
131
```bash
132
# Reset database (with confirmation)
133
prisma migrate reset
134
135
# Reset without confirmation prompt
136
prisma migrate reset --force
137
138
# Reset without regenerating client or seeding
139
prisma migrate reset --force --skip-generate --skip-seed
140
```
141
142
### Migration Resolution
143
144
Resolve failed migrations by marking them as applied without executing them.
145
146
```bash { .api }
147
/**
148
* Mark failed migrations as resolved
149
* Useful for fixing migration history after manual intervention
150
*/
151
prisma migrate resolve [options]
152
153
Options:
154
--applied <migration> Mark specific migration as applied
155
--rolled-back <migration> Mark specific migration as rolled back
156
--schema <path> Custom schema file path
157
--help/-h Show migrate resolve command help
158
```
159
160
**Usage Examples:**
161
162
```bash
163
# Mark migration as applied
164
prisma migrate resolve --applied 20240101120000_failed_migration
165
166
# Mark migration as rolled back
167
prisma migrate resolve --rolled-back 20240101120000_problematic_migration
168
```
169
170
### Migration Diff
171
172
Generate migration diffs between different schema states for preview and review.
173
174
```bash { .api }
175
/**
176
* Generate migration diffs between schema states
177
* Compare schemas and show required database changes
178
*/
179
prisma migrate diff [options]
180
181
Options:
182
--from-empty Compare from empty schema
183
--from-schema-datamodel <path> Compare from schema file
184
--from-schema-datasource <path> Compare from schema datasource
185
--from-url <url> Compare from database URL
186
--from-migrations <path> Compare from migrations directory
187
--to-schema-datamodel <path> Compare to schema file
188
--to-schema-datasource <path> Compare to schema datasource
189
--to-url <url> Compare to database URL
190
--to-migrations <path> Compare to migrations directory
191
--script Output executable SQL script
192
--exit-code Return non-zero exit code if differences found
193
--help/-h Show migrate diff command help
194
```
195
196
**Usage Examples:**
197
198
```bash
199
# Compare current schema to database
200
prisma migrate diff \
201
--from-url $DATABASE_URL \
202
--to-schema-datamodel ./prisma/schema.prisma
203
204
# Generate SQL script for differences
205
prisma migrate diff \
206
--from-url $DATABASE_URL \
207
--to-schema-datamodel ./prisma/schema.prisma \
208
--script
209
210
# Compare two database states
211
prisma migrate diff \
212
--from-url $STAGING_DATABASE_URL \
213
--to-url $PRODUCTION_DATABASE_URL
214
215
# Compare schema to empty state
216
prisma migrate diff \
217
--from-empty \
218
--to-schema-datamodel ./prisma/schema.prisma \
219
--script
220
```
221
222
## Migration Files
223
224
### Migration File Structure
225
226
```
227
prisma/
228
├── schema.prisma
229
└── migrations/
230
├── 20240101120000_init/
231
│ └── migration.sql
232
├── 20240102130000_add_user_profile/
233
│ └── migration.sql
234
└── migration_lock.toml
235
```
236
237
### Migration SQL Example
238
239
```sql
240
-- CreateTable
241
CREATE TABLE "User" (
242
"id" SERIAL NOT NULL,
243
"email" TEXT NOT NULL,
244
"name" TEXT,
245
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
246
"updatedAt" TIMESTAMP(3) NOT NULL,
247
248
CONSTRAINT "User_pkey" PRIMARY KEY ("id")
249
);
250
251
-- CreateIndex
252
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
253
```
254
255
### Migration Lock File
256
257
```toml
258
# migration_lock.toml
259
provider = "postgresql"
260
```
261
262
## Development Workflows
263
264
### Feature Development
265
266
```bash
267
# 1. Modify schema
268
# 2. Create migration
269
prisma migrate dev --name add-feature-x
270
271
# 3. Review generated migration
272
cat prisma/migrations/*/migration.sql
273
274
# 4. Test migration
275
npm run test
276
```
277
278
### Collaborative Development
279
280
```bash
281
# Pull latest migrations from team
282
git pull origin main
283
284
# Apply new migrations locally
285
prisma migrate dev
286
287
# Create your feature migration
288
prisma migrate dev --name your-feature
289
```
290
291
### Production Deployment
292
293
```bash
294
# CI/CD pipeline deployment
295
prisma migrate deploy
296
297
# Manual deployment with checks
298
prisma migrate status # Check pending migrations
299
prisma migrate deploy # Apply migrations
300
```
301
302
## Advanced Migration Patterns
303
304
### Custom Migration SQL
305
306
```sql
307
-- Custom business logic in migration
308
BEGIN;
309
310
-- Generated schema changes
311
CREATE TABLE "Order" (
312
"id" SERIAL NOT NULL,
313
"userId" INTEGER NOT NULL,
314
"total" DECIMAL(65,30) NOT NULL,
315
CONSTRAINT "Order_pkey" PRIMARY KEY ("id")
316
);
317
318
-- Custom data migration
319
INSERT INTO "Order" (userId, total)
320
SELECT id, 0.00 FROM "User" WHERE "User"."createdAt" < '2024-01-01';
321
322
-- Add foreign key constraint
323
ALTER TABLE "Order" ADD CONSTRAINT "Order_userId_fkey"
324
FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
325
326
COMMIT;
327
```
328
329
### Migration Rollback Strategy
330
331
```bash
332
# Create rollback migration
333
prisma migrate dev --name rollback-feature-x --create-only
334
335
# Edit migration to reverse changes
336
# Apply rollback
337
prisma migrate dev
338
```
339
340
### Environment-Specific Migrations
341
342
```bash
343
# Staging deployment
344
DATABASE_URL=$STAGING_DATABASE_URL prisma migrate deploy
345
346
# Production deployment
347
DATABASE_URL=$PRODUCTION_DATABASE_URL prisma migrate deploy
348
```
349
350
## Error Handling
351
352
Common migration errors:
353
354
- **Schema Drift**: Database schema differs from migration history
355
- **Failed Migrations**: SQL errors during migration execution
356
- **Conflicting Changes**: Multiple developers creating conflicting migrations
357
- **Data Loss**: Migrations that would destroy data
358
- **Constraint Violations**: Migrations violating database constraints
359
- **Lock Conflicts**: Concurrent migration attempts
360
361
## Integration
362
363
### CI/CD Integration
364
365
```yaml
366
# GitHub Actions example
367
- name: Run migrations
368
run: prisma migrate deploy
369
env:
370
DATABASE_URL: ${{ secrets.DATABASE_URL }}
371
372
- name: Generate client
373
run: prisma generate
374
```
375
376
### Docker Integration
377
378
```dockerfile
379
# Dockerfile
380
COPY prisma ./prisma/
381
RUN npx prisma generate
382
CMD ["sh", "-c", "npx prisma migrate deploy && npm start"]
383
```
384
385
### Testing Integration
386
387
```bash
388
# Test database migrations
389
DATABASE_URL="postgresql://test:test@localhost:5432/test" prisma migrate reset --force
390
DATABASE_URL="postgresql://test:test@localhost:5432/test" npm run test
391
```