Skip to main content

How do I add a new database migration script?

Objective: This article explains how to add a new database migration script and execute it.

Steps:

  1. Add a new file in the services' migration scripts directory:
    • services/<service>/api/migrations/scripts/
  2. Add the database migration logic (See examples below).
  3. Run pnpm run db:<service> or pnpm run db:all to execute the script.

Examples:

// services/<service>/api/migrations/scripts/
// Execute a database migration against an entire document collection:

import { MyModel } from '@hectare/platform.modules.<module>.core'
import { utils } from '@hectare/platform.components.ravendb'
import { DocumentSession, DocumentStore } from 'ravendb'

export const up = async (store: DocumentStore) => {
const patchModel = async (session: DocumentSession, model: MyModel) => {
model.price = 250
}

await utils.patch(MyModel, store, patchModel)
}

export const down = async () => {}

// services/<service>/api/migrations/scripts/
// Execute a database migration against a single document:

import { MyModel } from '@hectare/platform.modules.<module>.core'
import { DocumentStore } from 'ravendb'

export const up = async (store: DocumentStore) => {
const session = store.openSession()
const model = await session.load<MyModel>('MyModels/1-A')

model.price = 250

await session.saveChanges()
}

export const down = async () => {}

Note: Migrations must be idempotent, they must be able to be executed multiple times.

Related Articles: