Module migration

Module migration 

Source
Expand description

Schema migration management.

Contains the Migrator struct for registering models and executing automatic table creation and foreign key assignment.

§Migration Module

This module provides schema migration management functionality for Bottle ORM. It handles the registration and execution of database schema changes, including table creation and foreign key constraint assignment.

§Overview

The migration system follows a two-phase approach:

  1. Table Creation Phase: Creates all registered tables with their columns, indexes, and constraints (except foreign keys)
  2. Foreign Key Phase: Assigns foreign key constraints after all tables exist

This ensures that foreign keys can reference tables that haven’t been created yet.

§Features

  • Automatic Ordering: Handles dependencies between tables automatically
  • Idempotent Operations: Safe to run multiple times (uses IF NOT EXISTS)
  • Type Safety: Leverages Rust’s type system for compile-time validation
  • Async Execution: Non-blocking migration execution

§Example Usage

use bottle_orm::{Database, Model};
use uuid::Uuid;

#[derive(Model)]
struct User {
    #[orm(primary_key)]
    id: Uuid,
    username: String,
}

#[derive(Model)]
struct Post {
    #[orm(primary_key)]
    id: Uuid,
    #[orm(foreign_key = "User::id")]
    user_id: Uuid,
    title: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let db = Database::connect("postgres://localhost/mydb").await?;

    // Register and run migrations
    db.migrator()
        .register::<User>()
        .register::<Post>()
        .run()
        .await?;

    Ok(())
}

Structs§

Migrator
Schema migration manager.

Type Aliases§

MigrationTask
Type alias for migration tasks (e.g., Create Table, Add Foreign Key).