본문으로 건너뛰기
cccskills
무료GitHub에 공개

convex-migrations

Changes a live Convex schema without downtime: make a field optional, backfill in batches, flip the validator, then clean up. Uses the @convex-dev/migrations component where it fits. Use when renaming or removing a field, changing a type, splitting a table, or when deploy fails with a schema validation error on existing documents.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(6)

  • SKILL.md8.4 KB
  • agents/openai.yaml91 B
  • assets/large-logo.png3.2 KB
  • assets/small-logo.svg1.2 KB
  • references/migration-patterns.md8.7 KB
  • references/migrations-component.md4.5 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Convex migrations

Produces a schema change plus a batched backfill that keeps every deploy green. The one rule: the schema must describe the documents that exist right now, not the documents you want. Change the data first, then tighten the validator.

Convex has no migration files or migrate command. npx convex dev pushes the schema and validates every existing document against it. Existing data is never transformed for you.

When to reach for this

  • Adding a field that should be required, but the table already has rows
  • Renaming a field, changing its type, or removing it
  • Splitting one table into two or merging two into one
  • npx convex dev fails with Schema validation failed after a schema edit
  • A backfill needs to touch more rows than one mutation can handle

For step by step recipes (rename, change type, split, merge, add required, remove) open references/migration-patterns.md. For installing and running @convex-dev/migrations open references/migrations-component.md.

The safe sequence

Every migration follows the same six steps. Skipping one is how deploys break.

  1. Make the field optional in convex/schema.ts (or add the new field as v.optional).
  2. Deploy with npx convex dev. Update readers to handle undefined and writers to set the new shape.
  3. Backfill existing documents in batches with an internal mutation or the migrations component.
  4. Flip the validator to its final shape (v.string() instead of v.optional(v.string()), or drop the old field).
  5. Deploy again. Validation now passes because every document already matches.
  6. Clean up: delete fallback code, remove the backfill function, drop stale indexes.

Steps 1 and 2 must ship before step 3 starts. Otherwise new writes keep producing old shaped documents while the backfill runs.

Hand rolled batched backfill

One internalMutation that pages through the table with paginate, patches only documents that still need it, then reschedules itself with the continue cursor. Each batch is its own transaction, so a large table never hits the per function limit.

// convex/migrations.ts
import { internalMutation } from "./_generated/server";
import { internal } from "./_generated/api";
import { v } from "convex/values";

const BATCH_SIZE = 100;

export const backfillAvatarUrl = internalMutation({
  args: { cursor: v.union(v.string(), v.null()) },
  returns: v.null(),
  handler: async (ctx, args) => {
    const result = await ctx.db
      .query("users")
      .paginate({ numItems: BATCH_SIZE, cursor: args.cursor });

    for (const user of result.page) {
      // Idempotent: skip documents that already have the field
      if (user.avatarUrl === undefined) {
        await ctx.db.patch(user._id, {
          avatarUrl: defaultAvatar(user.name),
        });
      }
    }

    // Reschedule with the cursor until the table is exhausted
    if (!result.isDone) {
      await ctx.scheduler.runAfter(0, internal.migrations.backfillAvatarUrl, {
        cursor: result.continueCursor,
      });
    }
    return null;
  },
});

function defaultAvatar(name: string): string {
  return `https://api.dicebear.com/7.x/initials/svg?seed=${encodeURIComponent(name)}`;
}

Start it from the CLI against the dev deployment:

npx convex run migrations:backfillAvatarUrl '{"cursor": null}'

Keep the mutation idempotent. Re running it after a partial failure must be safe. Use internalMutation, never a public mutation, so it cannot be called from a client. Use ctx.db.patch for adding or changing fields and ctx.db.patch(id, { field: undefined }) to remove one.

When to use the component instead

@convex-dev/migrations wraps the pattern above and adds what the hand rolled version lacks: persisted progress per migration, status checks, dry runs, cancel, and ordered runs of several migrations. Reach for it when:

  • The project will run more than one or two migrations over its life
  • You need to know whether a migration already completed in production
  • You want a dry run before touching real data
  • Several migrations must run in a fixed order

Minimal setup:

// convex/convex.config.ts
import { defineApp } from "convex/server";
import migrations from "@convex-dev/migrations/convex.config.js";

const app = defineApp();
app.use(migrations);
export default app;
// convex/migrations.ts
import { Migrations } from "@convex-dev/migrations";
import { components } from "./_generated/api";
import { DataModel } from "./_generated/dataModel";

export const migrations = new Migrations<DataModel>(components.migrations);

export const addDefaultRole = migrations.define({
  table: "users",
  migrateOne: async (ctx, user) => {
    if (user.role === undefined) {
      await ctx.db.patch(user._id, { role: "user" });
    }
  },
});
npx convex run migrations:addDefaultRole '{"dryRun": true}'
npx convex run migrations:addDefaultRole

A one off backfill on a small table does not need the component. The hand rolled mutation is fine.

Reading the deploy time schema error

When a schema push fails, npx convex dev prints the table, one offending document id, and the field that does not match:

Schema validation failed
Document with ID "j57abc..." in table "users" does not match the schema:
Object is missing the required field `avatarUrl`.
Consider wrapping the field validator in `v.optional(...)` if this is expected.

Read it as: existing data in users predates the field. The fix is never to delete the document. Wrap the field in v.optional, deploy, backfill, then remove the v.optional. If the error says the field has the wrong type (for example string where number is expected), widen the validator to v.union(v.string(), v.number()), backfill the conversion, then narrow it.

Do not pass { schemaValidation: false } to defineSchema to make the push succeed. It hides the mismatch and moves the failure into your queries.

Common mistakes

MistakeWhy it breaksDo instead
Add a required field in one deployExisting documents fail validation, push is rejectedAdd as v.optional, backfill, then require
Start the backfill before deploying the new writersNew rows keep arriving in the old shapeDeploy schema and code first, backfill second
One mutation that .collect()s the whole tableHits the transaction size and time limitsPage with paginate and reschedule per batch
Backfill with a public mutationAnyone can call it and re run itinternalMutation or migrations.define
Non idempotent patchRe running after a failure double appliesCheck the field before patching
Removing the old field before readers stop using itFallback code reads undefinedSwitch readers, then remove
Using .filter() to find unmigrated rowsFull scan on every batchPaginate the whole table or use customRange with an index
Turning off schemaValidation to pass the deployBad data reaches queries at runtimeFix the data, keep validation on
Running a backfill against production firstNo way to catch a wrong conversionRun on dev, then --prod

Checklist

  • New or changed field is v.optional (or a widened v.union) in the first deploy
  • Readers handle undefined and writers produce the new shape before the backfill starts
  • Backfill is an internalMutation or migrations.define, never public
  • Backfill pages with paginate and reschedules via ctx.scheduler.runAfter(0, internal....)
  • Each patch is guarded so re running is safe
  • Backfill ran to completion on dev before touching prod
  • Validator flipped to its final shape and deployed without a validation error
  • Fallback code, old field, and backfill function removed
  • Indexes that referenced the old field are dropped or renamed

Docs

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Keeps a change scoped to what was asked. Flags extra features, refactors, and 'while we are here' edits, and moves them to a suggestions list instead of the diff. Use when a request is small and the agent is about to expand it, when a PRD grows beyond its problem statement, or when the user says 'just do what I asked'.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

waynesutton/builder-skills4062026년 9월 28일 업데이트

convex

무료

Routes Convex work to the right builder skill and covers the handful of rules that apply everywhere: validators on every function, withIndex over filter, idempotent mutations, internal functions for scheduling. Use when a task mentions Convex and no more specific skill matches, or as the first stop before picking one.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

waynesutton/builder-skills4062026년 9월 28일 업데이트

Builds AI agents on the Convex agent component: threads, messages, tools that call queries and mutations, streaming, RAG with vector search, and workflows for multi step jobs. Use when adding a chat assistant, tool calling agent, or retrieval feature to a Convex app.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

waynesutton/builder-skills4062026년 9월 28일 업데이트

Production patterns for Convex apps and the rules the @convex-dev/eslint-plugin enforces: validators, indexes, idempotent mutations, avoiding OCC conflicts, thin function wrappers, error handling. Use when reviewing Convex code, asking whether a pattern is right, setting up ESLint, or fixing write conflicts and slow queries.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

waynesutton/builder-skills4062026년 9월 28일 업데이트

Creates reusable Convex components with defineComponent, a clean client wrapper, their own schema, and an npm publish setup. Use when extracting a feature into a package, building something for the Convex component directory, or when a component's functions are not showing up in the parent app.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

waynesutton/builder-skills4062026년 9월 28일 업데이트

Schedules work in Convex: cron jobs in convex/crons.ts, one off scheduled functions with runAfter and runAt, batching large jobs, and cancelling or inspecting the queue. Use when something needs to run on a timer, later, or in the background, or when a cron is not firing.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

waynesutton/builder-skills4062026년 9월 28일 업데이트

waynesutton의 스킬 모두 보기

이 스킬의 문제 신고