| name | cursor-plugin-convex-migration-helper |
| description | Plan and execute Convex schema migrations safely, including adding fields, creating tables, and data transformations. Use when schema changes affect existing data. |
| metadata | {"version":"0.1.0"} |
Convex Migration Helper
Safely migrate Convex schemas and data when making breaking changes.
When to Use
- Adding new required fields to existing tables
- Changing field types or structure
- Splitting or merging tables
- Renaming fields
- Migrating from nested to relational data
Migration Principles
- No Automatic Migrations: Convex doesn't automatically migrate data
- Additive Changes are Safe: Adding optional fields or new tables is safe
- Breaking Changes Need Code: Required fields, type changes need migration code
- Zero-Downtime: Write migrations to keep app running during migration
Safe Changes (No Migration Needed)
Adding Optional Field
users: defineTable({
name: v.string(),
})
users: defineTable({
name: v.string(),
bio: v.optional(v.string()),
})
Adding New Table
posts: defineTable({
userId: v.id("users"),
title: v.string(),
}).index("by_user", ["userId"])
Adding Index
users: defineTable({
name: v.string(),
email: v.string(),
})
.index("by_email", ["email"])
Breaking Changes (Migration Required)
Adding Required Field
Problem: Existing documents won't have the new field.
Solution: Add as optional first, backfill data, then make required.
users: defineTable({
name: v.string(),
email: v.optional(v.string()),
})
import { internalMutation } from "./_generated/server";
import { v } from "convex/values";
export const backfillEmails = internalMutation({
args: {},
handler: async (ctx) => {
const users = await ctx.db.query("users").collect();
for (const user of users) {
if (!user.email) {
await ctx.db.patch(user._id, {
email: `user-${user._id}@example.com`,
});
}
}
},
});
users: defineTable({
name: v.string(),
email: v.(),
})
Changing Field Type
Example: Change tags: v.array(v.string()) to separate table
tags: defineTable({
name: v.string(),
}).index("by_name", ["name"]),
postTags: defineTable({
postId: v.id("posts"),
tagId: v.id("tags"),
})
.index("by_post", ["postId"])
.index("by_tag", ["tagId"]),
posts: defineTable({
title: v.string(),
tags: v.optional(v.array(v.string())),
})
export const migrateTags = internalMutation({
args: { batchSize: v.optional(v.number()) },
handler: async (ctx, args) => {
const batchSize = args.batchSize ?? 100;
const posts = await ctx.db
.query("posts")
.( q.(q.(), ))
.(batchSize);
( post posts) {
(!post. || post.. === ) {
ctx..(post., { : });
;
}
( tagName post.) {
tag = ctx.
.()
.(, q.(, tagName))
.();
(!tag) {
tagId = ctx..(, { : tagName });
tag = { : tagId, : tagName };
}
existing = ctx.
.()
.(, q.(, post.))
.( q.(q.(), tag.))
.();
(!existing) {
ctx..(, {
: post.,
: tag.,
});
}
}
ctx..(post., { : });
}
{ : posts. };
},
});
: ({
: v.(),
})
Renaming Field
users: defineTable({
name: v.string(),
displayName: v.optional(v.string()),
})
export const renameField = internalMutation({
handler: async (ctx) => {
const users = await ctx.db.query("users").collect();
for (const user of users) {
await ctx.db.patch(user._id, {
displayName: user.name,
});
}
},
});
users: defineTable({
displayName: v.string(),
})
Migration Patterns
Batch Processing
For large tables, process in batches:
export const migrateBatch = internalMutation({
args: {
cursor: v.optional(v.string()),
batchSize: v.number(),
},
handler: async (ctx, args) => {
const batchSize = args.batchSize;
let query = ctx.db.query("largeTable");
const items = await query.take(batchSize);
for (const item of items) {
await ctx.db.patch(item._id, {
});
}
return {
processed: items.length,
hasMore: items.length === batchSize,
};
},
});
Scheduled Migration
Use cron jobs for gradual migration:
import { cronJobs } from "convex/server";
import { internal } from "./_generated/api";
const crons = cronJobs();
crons.interval(
"migrate-batch",
{ minutes: 5 },
internal.migrations.migrateBatch,
{ batchSize: 100 }
);
export default crons;
Dual-Write Pattern
For zero-downtime migrations:
export const createPost = mutation({
args: { title: v.string(), tags: v.array(v.string()) },
handler: async (ctx, args) => {
const user = await getCurrentUser(ctx);
const postId = await ctx.db.insert("posts", {
userId: user._id,
title: args.title,
tags: args.tags,
});
for (const tagName of args.tags) {
let tag = await ctx.db
.query("tags")
.withIndex("by_name", q => q.eq("name", tagName))
.unique();
if (!tag) {
const tagId = await ctx.db.insert(, { : tagName });
tag = { : tagId };
}
ctx..(, {
postId,
: tag.,
});
}
postId;
},
});
Testing Migrations
Verify Migration Success
export const verifyMigration = query({
args: {},
handler: async (ctx) => {
const total = (await ctx.db.query("users").collect()).length;
const migrated = (await ctx.db
.query("users")
.filter(q => q.neq(q.field("newField"), undefined))
.collect()
).length;
return {
total,
migrated,
remaining: total - migrated,
percentComplete: (migrated / total) * 100,
};
},
});
Migration Checklist
Common Pitfalls
- Don't make field required immediately: Always add as optional first
- Don't migrate in a single transaction: Batch large migrations
- Don't forget to update queries: Update all code using old field
- Don't delete old field too soon: Wait until all data migrated
- Test thoroughly: Verify migration on dev environment first
Example: Complete Migration Flow
export default defineSchema({
users: defineTable({
name: v.string(),
}),
});
export default defineSchema({
users: defineTable({
name: v.string(),
role: v.optional(v.union(
v.literal("user"),
v.literal("admin")
)),
}),
});
export const addDefaultRoles = internalMutation({
handler: async (ctx) => {
const users = await ctx.db.query("users").collect();
for (const user of users) {
if (!user.role) {
await ctx.db.patch(user._id, { role: "user" });
}
}
},
});
({
: ({
: v.(),
: v.(
v.(),
v.()
),
}),
});