migrate

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 28, 2025 License: MIT Imports: 6 Imported by: 0

README

Velocity Database Migrations

Database schema versioning and evolution system for Velocity.

Features

  • ✅ Timestamp-based versioning (no conflicts in team environments)
  • ✅ Up/Down migrations with rollback support
  • ✅ TableBuilder DSL for type-safe schema definitions
  • ✅ Cross-database support (SQLite, MySQL, PostgreSQL)
  • ✅ Automatic migration tracking (migrations table)
  • ✅ Batch-based rollbacks

Quick Start

1. Create a Migration

migrations/20251009120000_create_users.go:

package migrations

import "github.com/velocitykode/velocity/pkg/orm/migrate"

func init() {
    migrate.Register(&migrate.Migration{
        Version: "20251009120000",
        Up: func(m *migrate.Migrator) error {
            return m.CreateTable("users", func(t *migrate.TableBuilder) {
                t.ID()
                t.String("email").Unique()
                t.String("name")
                t.Timestamps()
            })
        },
        Down: func(m *migrate.Migrator) error {
            return m.DropTable("users")
        },
    })
}
2. Run Migrations
import (
    "github.com/velocitykode/velocity/pkg/orm"
    "github.com/velocitykode/velocity/pkg/orm/migrate"
    _ "myapp/migrations" // Import to register
)

// Initialize ORM
orm.Init("sqlite", map[string]any{"database": "./database.db"})

// Run migrations
migrator := migrate.NewMigrator(orm.DB(), orm.GetDriver())
err := migrator.Up()

TableBuilder API

t.ID()                           // Auto-increment primary key
t.String("name")                 // VARCHAR(255)
t.String("code", 10)            // VARCHAR(10)
t.Integer("count")              // INTEGER
t.Boolean("active")             // BOOLEAN
t.Timestamps()                  // created_at, updated_at

// Modifiers
t.String("email").Unique()      // UNIQUE constraint
t.String("bio").Nullable()      // Allow NULL
t.Integer("status").Default(0)  // Default value

Commands

migrator := migrate.NewMigrator(orm.DB(), orm.GetDriver())

// Run pending migrations
migrator.Up()

// Rollback last batch
migrator.Down(1)

// Check status
statuses, _ := migrator.Status()
for _, s := range statuses {
    fmt.Printf("%s: %s\n", s.Version, s.State)
}

Version Format

Migrations use timestamp-based versioning: YYYYMMDDHHmmss

Example: 20251009143052 = December 9, 2025 at 14:30:52

See Also

  • /specs/002-database-testing-system/contracts/migration-api.md - Full API reference
  • /specs/002-database-testing-system/quickstart.md - Complete tutorial

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Down

func Down(steps int) error

Down rolls back the last N batches using the default ORM connection

func Register

func Register(migration *Migration)

Register adds a migration to the global registry

func Up

func Up() error

Up runs all pending migrations using the default ORM connection

Types

type Column

type Column struct {
	Name          string
	Type          string
	Length        int
	Nullable      bool
	Default       interface{}
	Unique        bool
	PrimaryKey    bool
	AutoIncrement bool
}

Column represents a table column definition

type Migration

type Migration struct {
	Version     string
	Description string
	Up          func(*Migrator) error
	Down        func(*Migrator) error
}

Migration represents a database schema change

func All

func All() []Migration

All returns all registered migrations

func Find

func Find(version string) (*Migration, error)

Find returns a migration by version

func Pending

func Pending(db *sql.DB, driver string) ([]Migration, error)

Pending returns migrations not yet applied

func (*Migration) Validate

func (m *Migration) Validate() error

Validate checks if the migration is valid

type MigrationRegistry

type MigrationRegistry struct {
	// contains filtered or unexported fields
}

MigrationRegistry is a global registry for all migrations

func (*MigrationRegistry) All

func (r *MigrationRegistry) All() []Migration

All returns all registered migrations sorted by version

func (*MigrationRegistry) Find

func (r *MigrationRegistry) Find(version string) (*Migration, error)

Find returns a migration by version

func (*MigrationRegistry) Pending

func (r *MigrationRegistry) Pending(db *sql.DB, driver string) ([]Migration, error)

Pending returns migrations that haven't been applied yet

type MigrationStatus

type MigrationStatus struct {
	Version    string
	State      string // "Applied", "Pending", "Failed"
	Batch      int
	ExecutedAt *string
}

MigrationStatus represents the status of a single migration

func Status

func Status() ([]MigrationStatus, error)

Status returns migration status using the default ORM connection

type Migrator

type Migrator struct {
	// contains filtered or unexported fields
}

Migrator handles migration execution for a specific database connection

func NewMigrator

func NewMigrator(db *sql.DB, driver string) *Migrator

NewMigrator creates a new Migrator instance

func (*Migrator) CreateTable

func (m *Migrator) CreateTable(name string, fn func(*TableBuilder)) error

CreateTable creates a new database table using the fluent TableBuilder API

func (*Migrator) Down

func (m *Migrator) Down(steps int) error

Down rolls back the last N batches of migrations

func (*Migrator) DropTable

func (m *Migrator) DropTable(name string) error

DropTable drops a database table

func (*Migrator) Fresh

func (m *Migrator) Fresh() error

Fresh drops all tables and re-runs all migrations

func (*Migrator) Raw

func (m *Migrator) Raw(sql string) error

Raw executes arbitrary SQL

func (*Migrator) SetMigrationsPath

func (m *Migrator) SetMigrationsPath(path string)

SetMigrationsPath sets the path to migration files

func (*Migrator) Status

func (m *Migrator) Status() ([]MigrationStatus, error)

Status returns the status of all migrations

func (*Migrator) Up

func (m *Migrator) Up() error

Up runs all pending migrations

type TableBuilder

type TableBuilder struct {
	// contains filtered or unexported fields
}

TableBuilder provides a fluent API for defining database tables

func (*TableBuilder) Boolean

func (t *TableBuilder) Boolean(name string) *TableBuilder

Boolean adds a BOOLEAN column

func (*TableBuilder) Default

func (t *TableBuilder) Default(value interface{}) *TableBuilder

Default sets a default value for the previous column

func (*TableBuilder) ID

func (t *TableBuilder) ID() *TableBuilder

ID adds an auto-increment primary key column named 'id'

func (*TableBuilder) Integer

func (t *TableBuilder) Integer(name string) *TableBuilder

Integer adds an INTEGER column

func (*TableBuilder) Nullable

func (t *TableBuilder) Nullable() *TableBuilder

Nullable allows NULL values for the previous column

func (*TableBuilder) String

func (t *TableBuilder) String(name string, length ...int) *TableBuilder

String adds a VARCHAR column

func (*TableBuilder) Timestamps

func (t *TableBuilder) Timestamps() *TableBuilder

Timestamps adds created_at and updated_at columns

func (*TableBuilder) ToSQL

func (t *TableBuilder) ToSQL() string

ToSQL generates driver-specific CREATE TABLE SQL

func (*TableBuilder) Unique

func (t *TableBuilder) Unique() *TableBuilder

Unique marks the previous column as unique

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL