# Move a Sequelize App From sync() to Migrations

Yes. An agent replaces sync({ force: true }) with sequelize-cli migrations and a seeder that match your models exactly, proves the schemas agree, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-database-migrations/sequelize/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads where the schema comes from today before writing a migration. In an app laid out like the `express-main-example` in sequelize/express-example, the only place tables are created is `sqlite-example-database/setup.js`, which calls `sequelize.sync({ force: true })` and then `bulkCreate`s four users and three orchestras and gives each orchestra ten instruments with random types and purchase dates; `index.js` never syncs, it calls `sequelize.authenticate()` and listens on 8080. The models are plain `sequelize.define` calls under `sequelize/models/`: `user` with an explicit auto-increment `id` and a unique `username` validated by `/^\w{3,}$/`, `orchestra` with a `name`, and `instrument` with `type` and `purchaseDate`; `sequelize/extra-setup.js` adds `orchestra.hasMany(instrument)` and `instrument.belongsTo(orchestra)`, which is how `instruments` gets its `orchestraId` column. Timestamps are on by default, so `sync` also creates `createdAt` and `updatedAt` on every table, and the JSON the API returns shows them. `sequelize/index.js` opens SQLite at a fixed path with `benchmark: true`, `.gitignore` excludes `*.sqlite`, `.npmrc` sets `package-lock=false`, and `package.json` has no dev dependencies and no test script.

The agent adds `sequelize-cli` as a dev dependency and a `.sequelizerc` that points `config` at a new `config/config.js`, which reads the same dialect and `storage` path `sequelize/index.js` uses so the CLI and the app open one file, and sets `migrations-path` and `seeders-path` under `sequelize/` beside the models. The first migration, `create-initial-schema`, has an `up` that calls `queryInterface.createTable` for `users`, `orchestras` and `instruments` with the columns `sync` produced: the integer primary keys, `username` with `allowNull: false` and `unique: true`, `name`, `type` and `purchaseDate` with `allowNull: false`, `createdAt` and `updatedAt`, and on `instruments` an `orchestraId` with `references: { model: 'orchestras', key: 'id' }`, `onDelete: 'SET NULL'` and `onUpdate: 'CASCADE'`, which are the defaults `hasMany` gives the foreign key. The `down` drops the three tables in reverse order. The `is` regex on `username` stays in the model, where Sequelize validates it, since SQLite has no check for it.

The seed data moves to `sequelize/seeders/` as one seeder whose `up` inserts the same users and orchestras with `queryInterface.bulkInsert` and the instruments with the `pickRandom` and `randomDate` helpers from `sqlite-example-database/helpers/random.js`, and whose `down` deletes them. `package.json` gets `db:migrate`, `db:migrate:undo` and `db:seed` scripts, and `setup-example-db` becomes `migrate` then `seed` instead of running `setup.js`, which is deleted; `readme.md`'s instructions follow. `sync` is gone from the codebase, and the app's `authenticate` call in `index.js` stays as it is.

The proof is a schema comparison in the sandbox. The agent builds one database with the old `setup.js` and one with `npx sequelize-cli db:migrate` on an empty file, reads both through `sequelize.getQueryInterface().describeTable()` for each of the three tables, and diffs the column definitions, so the pull request shows the two agree on types, nullability, keys and the foreign key. It then runs `db:migrate:undo`, `db:migrate` again and `db:seed:all`, starts the server and reads `/api/orchestras?includeInstruments` to show the seeded data comes back through the association, and pastes the `SequelizeMeta` row that records the migration.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Replace sync() with migrations in this Express and Sequelize app. Read package.json, .npmrc, .gitignore, readme.md, index.js, sequelize/index.js, sequelize/extra-setup.js, the three files under sequelize/models/, sqlite-example-database/setup.js and sqlite-example-database/helpers/random.js first. Add sequelize-cli as a dev dependency, a .sequelizerc pointing at config/config.js that reuses the dialect and storage path from sequelize/index.js, with migrations and seeders under sequelize/. Write one migration that creates users, orchestras and instruments with exactly the columns sync produces, including createdAt and updatedAt and an orchestraId foreign key with the defaults hasMany gives it, and a down that drops them. Move the seed data from setup.js into a seeder using the random helpers, add db:migrate, db:migrate:undo and db:seed scripts, make setup-example-db run migrate then seed, delete setup.js and update the readme. Do not change the models or index.js. In the sandbox, build one database with the old setup.js and one with the migration, diff describeTable for each table, run undo, migrate and seed again, start the server and read /api/orchestras?includeInstruments. Open a pull request that pastes the diff and the output.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that adds `.sequelizerc`, `config/config.js`, one file under `sequelize/migrations/` and one under `sequelize/seeders/`, changes `package.json` and `readme.md`, and deletes `sqlite-example-database/setup.js`. The models, `sequelize/index.js` and `index.js` are unchanged. The description pastes the `describeTable` diff for `users`, `orchestras` and `instruments`, which is empty when the migration matches `sync`, and the output of the migrate, undo, migrate and seed runs.

The run's record holds both database builds, the diff script, the CLI output with the `SequelizeMeta` entry and the `curl` of the seeded orchestras with their instruments, so a reviewer can see the foreign key behaved through the association without checking out the branch.

Before merging, a reviewer reads the migration's column definitions against the models, decides whether `onDelete: 'SET NULL'` is the behaviour they want for instruments whose orchestra is removed, and checks that the deploy process will now run `db:migrate` where it used to run `setup.js`.

## Run it on every service still calling sync() at startup

A team sends one `POST /o/{org}/sessions` per Sequelize repository from its terminal or a script, with this prompt and the repository in `resources`, and a `request_id` that is a UUID v5 of the repository name so a retried call returns the run already started. A short script can clone each repository `GET /o/{org}/github` lists and start a run only where `sequelize.sync(` appears outside a test.

Each run reads that service's own models and associations, so a service with `through` tables or `paranoid` models gets migrations for those columns too, and each opens its own pull request. A webhook URL on the API key reports `run.completed` with the `session_url` to read the pull request link from.

## Why run it on Rush?

A first migration has to reproduce what `sync` built, column for column, or the first deploy against a database that already exists fails on a type or a missing foreign key default. The agent does not guess: it reads the models and the association setup, writes the migration, and then builds both databases in its own sandbox and diffs their `describeTable` output, which is the check a laptop session usually skips. The run keeps every command, so the pull request carries the proof rather than a promise.

Several services can be moved at once, each in its own sandbox with its own SQLite file, and nothing is installed on the reader's machine. The reviewer reads a diff of a handful of files and a schema comparison, and decides.

## Frequently asked questions

### Why keep the models' validate rules if the migration defines the columns?

Because they are different layers. The migration gives SQLite the column types, nullability, unique index and foreign key; the `is: /^\w{3,}$/` rule on `username` runs in Sequelize before a write and has no SQL equivalent here. The models stay exactly as they are and keep validating.

### What defaults does the orchestraId foreign key get?

`hasMany` creates the key with `onDelete: 'SET NULL'` and `onUpdate: 'CASCADE'` unless told otherwise, and the migration writes those out explicitly so the database matches what `sync` made. If instruments should go with their orchestra, the reviewer changes the one line to `CASCADE` and the agent can add a migration for it.

### Does the app still work with the old example-db.sqlite file?

A file built by `setup.js` has the tables but no `SequelizeMeta` table, so `db:migrate` would try to create tables that exist. The readme tells the reader to delete the ignored `*.sqlite` file once and run `npm run setup-example-db`, which now migrates and seeds; the pull request says so.

### Why a JavaScript config instead of config.json?

So the storage path is written once. `config/config.js` reads the same dialect and file path `sequelize/index.js` uses, and the CLI and the app open the same database. It also leaves room for a `DB_CONNECTION_URL` environment variable later, which the comment in `sequelize/index.js` already anticipates.

### Will the seeder give the same instruments as setup.js did?

The same shape, not the same rows: `setup.js` picks random types and dates, and the seeder reuses `pickRandom` and `randomDate`, so each seed run produces ten instruments per orchestra with random values as before. A fixed data set is a reviewer's call; the agent keeps the behaviour the project had.

## More Sequelize jobs

- [Add Dependabot to a Sequelize App](https://getrush.ai/run/add-dependabot/sequelize/)
- [Add a Dockerfile to a Sequelize App](https://getrush.ai/run/add-dockerfile/sequelize/)
- [Add GitHub Actions CI to a Sequelize App](https://getrush.ai/run/add-github-actions-ci/sequelize/)

## The same job on other stacks

- [Add Database Migrations to a Slim 4 App](https://getrush.ai/run/add-database-migrations/slim/)
- [Replace TypeORM synchronize with Migrations](https://getrush.ai/run/add-database-migrations/typeorm/)
- [Add Database Migrations to an Actix Web App](https://getrush.ai/run/add-database-migrations/actix/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
