Skip to main content
Sonamu automatically generates database migrations based on Entity definitions.

Migration Overview

Auto Generation

Entity → Migration No manual writing needed

Version Control

Timestamp-based Sequential execution guaranteed

Up/Down

Apply and rollback Bidirectional support

Knex-based

Standard Knex API Compatibility guaranteed

Migration Generation Flow

From Entity to Migration

1. Entity Definition

2. Auto-Generated Migration

Migration filename: {timestamp}_{action}_{table_name}.ts - Timestamp: YYYYMMDDHHmmss format - Action: create, alter, foreign, drop, etc. - Table name: underscore-separated

Migration File Structure

up Function - Apply Changes

down Function - Rollback Changes

The down function is required!You must define the reverse operation of up for rollbacks.

Generated Migration Types

CREATE TABLE

ALTER TABLE - Add Column

ALTER TABLE - Drop Column

Add FOREIGN KEY

Database Comparison

Sonamu detects differences by comparing the current DB schema with Entities:

Comparison Targets

  1. Tables: existence, name
  2. Columns: type, length, nullable, default
  3. Indexes: unique, index, composite indexes
  4. Foreign Keys: referenced table, onUpdate, onDelete
  5. Constraints: CHECK, DEFAULT, etc.

Difference Detection

Migration Execution Order

1. Timestamp-based Sorting

2. Dependency Consideration

Foreign keys are generated as separate migrations!CREATE TABLE only creates columns; foreign key constraints are added later in separate migrations.

Execution Tracking

knex_migrations Table

Knex tracks executed migrations:
  • batch: Group executed together (rollback unit)
  • migration_time: Execution time

Entity Type to Migration Mapping

Basic Types

Relation Types

Indexes

where is a raw SQL predicate for creating a PostgreSQL partial index. Sonamu compares the predicate from DB introspection with the one in entity.json, and does not generate an additional migration if the conditions are equivalent.

Advanced Features

Generated Columns

Full-text Search Index

Vector Search Index

Next Steps

Creating Migrations

Generate in Sonamu UI

Running Migrations

migrate run command

Rolling Back

Undo changes

Entity Definition

Understanding Entity structure