1
---
2
name: data-migration-scripts
3
description: >
4
Create safe, reversible database migration scripts with rollback capabilities,
5
data validation, and zero-downtime deployments. Use when changing database
6
schemas, migrating data between systems, or performing large-scale data
7
transformations.
8
---
9
10
# Data Migration Scripts
11
12
## Table of Contents
13
14
- [Overview](#overview)
15
- [When to Use](#when-to-use)
16
- [Quick Start](#quick-start)
17
- [Reference Guides](#reference-guides)
18
- [Best Practices](#best-practices)
19
20
## Overview
21
22
Create robust, safe, and reversible data migration scripts for database schema changes and data transformations with minimal downtime.
23
24
## When to Use
25
26
- Database schema changes
27
- Adding/removing/modifying columns
28
- Migrating between database systems
29
- Data transformations and cleanup
30
- Splitting or merging tables
31
- Changing data types
32
- Adding indexes and constraints
33
- Backfilling data
34
- Multi-tenant data migrations
35
36
## Quick Start
37
38
Minimal working example:
39
40
```typescript
41
import { Knex } from "knex";
42
43
// migrations/20240101000000_add_user_preferences.ts
44
export async function up(knex: Knex): Promise<void> {
45
// Create new table
46
await knex.schema.createTable("user_preferences", (table) => {
47
table.uuid("id").primary().defaultTo(knex.raw("gen_random_uuid()"));
48
table
49
.uuid("user_id")
50
.notNullable()
51
.references("id")
52
.inTable("users")
53
.onDelete("CASCADE");
54
table.jsonb("preferences").defaultTo("{}");
55
table.timestamp("created_at").defaultTo(knex.fn.now());
56
table.timestamp("updated_at").defaultTo(knex.fn.now());
57
58
table.index("user_id");
59
});
60
61
// Migrate existing data
62
await knex.raw(`
63
INSERT INTO user_preferences (user_id, preferences)
64
SELECT id, jsonb_build_object(
65
'theme', COALESCE(theme, 'light'),
66
// ... (see reference guides for full implementation)
67
```
68
69
## Reference Guides
70
71
Detailed implementations in the `references/` directory:
72
73
| Guide | Contents |
74
|---|---|
75
| [Knex.js Migrations (Node.js)](references/knexjs-migrations-nodejs.md) | Knex.js Migrations (Node.js) |
76
| [Alembic Migrations (Python/SQLAlchemy)](references/alembic-migrations-pythonsqlalchemy.md) | Alembic Migrations (Python/SQLAlchemy) |
77
| [Large Data Migration with Batching](references/large-data-migration-with-batching.md) | Large Data Migration with Batching |
78
| [Zero-Downtime Migration Pattern](references/zero-downtime-migration-pattern.md) | Zero-Downtime Migration Pattern |
79
| [Migration Validation](references/migration-validation.md) | Migration Validation |
80
| [Cross-Database Migration](references/cross-database-migration.md) | Cross-Database Migration |
81
82
## Best Practices
83
84
### ✅ DO
85
86
- Always write both `up` and `down` migrations
87
- Test migrations on production-like data
88
- Use transactions for atomic operations
89
- Process large datasets in batches
90
- Add indexes after data insertion
91
- Validate data after migration
92
- Log progress and errors
93
- Use feature flags for application code changes
94
- Back up database before running migrations
95
- Test rollback procedures
96
- Document migration side effects
97
- Version control all migrations
98
- Use idempotent operations
99
100
### ❌ DON'T
101
102
- Run untested migrations on production
103
- Make breaking changes without backwards compatibility
104
- Process millions of rows in single transaction
105
- Skip rollback implementation
106
- Ignore migration failures
107
- Modify old migrations
108
- Delete data without backups
109
- Run migrations manually in production
110