kat

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

README

Kat

License Go Report Card Go Reference CI Release Docs

Graph-based SQL migrations. Kat treats your schema as a DAG, not a linear log — enabling parallel development, explicit dependencies, and deterministic ordering. Supports PostgreSQL and SQLite.

Kat Banner

Linear (traditional):     Graph-based (Kat):

001_users                 001_users ──┬─→ 003_posts
002_posts                             │
003_add_email             002_add_email ──┘

Order: 1→2→3              Order: 1→2→3 OR 1→3→2
(rigid)                   (flexible, dependency-aware)

Install

# macOS & Linux
curl -sSL https://kat.bolaji.de/install | sudo bash

# From source
git clone https://github.com/BolajiOlajide/kat.git && cd kat && make install

Pre-compiled binaries are available on the releases page.

Quick Start

kat init                        # Initialize project
kat add create_users_table      # Create a migration
kat add add_email_column        # Kat resolves the parent automatically
kat up                          # Apply all pending migrations
kat down --count 1              # Roll back last migration
kat ping                        # Test DB connection
kat export --file graph.dot     # Export dependency graph (DOT format)
Migration Structure
migrations/
├── 1679012345_create_users_table/
│   ├── up.sql
│   ├── down.sql
│   └── metadata.yaml
└── 1679012398_add_email_column/
    ├── up.sql
    ├── down.sql
    └── metadata.yaml      # parents: [1679012345]
Configuration (kat.conf.yaml)
migration:
  tablename: migrations
  directory: migrations
database:
  driver: postgres
  url: postgres://user:pass@localhost:5432/mydb
  # or: url: ${DATABASE_URL}

  # driver: sqlite
  # path: ./kat.db

Commands

Command Description
kat init Initialize a new project
kat add NAME Create a new migration
kat up [--count N] Apply pending migrations
kat down [--count N] Roll back migrations
kat ping Test DB connectivity
kat export [--file F] Export migration graph (DOT format)
kat version Display version

Go Library

//go:embed migrations
var migrationsFS embed.FS

func main() {
    m, err := kat.New(kat.PostgresDriver, "postgres://user:pass@localhost:5432/db", migrationsFS, "migrations")
    if err != nil {
        log.Fatal(err)
    }

    ctx := context.Background()
    m.Up(ctx, 0)   // apply all
    m.Down(ctx, 1)  // roll back one
}

Comparison

Feature Kat Flyway Goose Atlas
Graph-based dependencies ⚠️
Parallel development friendly ⚠️
Raw SQL migrations ⚠️
Go library + CLI
Migration visualization

Documentation

Full docs at kat.bolaji.de — covers installation, configuration, migrations, custom loggers, and more.

Contributing

Contributions welcome! Fork, branch, commit, and open a PR.

License

Apache License 2.0 — see LICENSE.

Acknowledgments

Inspired by Sourcegraph's internal CLI tooling.

Documentation

Overview

Kat is a lightweight, embeddable library for PostgreSQL and SQLite database migrations.

For more information about the project, visit: https://kat.bolaji.de

Package kat provides a lightweight, embeddable library for PostgreSQL and SQLite database migrations.

Kat allows you to manage your database schema using SQL files with a simple, intuitive workflow. It features:

  • Simple SQL Migrations: Write raw SQL for both up and down migrations
  • Graph-Based Migration System: Manages parent-child relationships between migrations
  • Explicit Dependencies: Migrations can declare parent dependencies
  • Transaction Support: Migrations run within transactions for safety
  • Migration Tracking: Applied migrations are recorded in a database table
  • Rollback Support: Easily revert migrations

Basic usage:

// Create a new migration manager with a connection string
m, err := kat.New(kat.PostgresDriver, "postgres://user:pass@localhost:5432/db", fsys, "migrations")
if err != nil {
	log.Fatal(err)
}

// Or use an existing *sql.DB connection
m, err = kat.NewWithDB(kat.PostgresDriver, db, fsys, "migrations")
if err != nil {
	log.Fatal(err)
}

// Apply all pending migrations
err = m.Up(context.Background(), 0)
if err != nil {
	log.Fatal(err)
}

// Roll back the most recent migration
err = m.Down(context.Background(), 1)
if err != nil {
	log.Fatal(err)
}

Index

Constants

View Source
const (
	// PostgresDriver is the driver for PostgreSQL databases.
	PostgresDriver = dbdriver.PostgresDriver
	// SQLiteDriver is the driver for SQLite databases.
	SQLiteDriver = dbdriver.SqliteDriver
)

Variables

This section is empty.

Functions

This section is empty.

Types

type DBConfig added in v0.2.0

type DBConfig = database.DBConfig

DBConfig holds database connection configuration options.

func DefaultDBConfig added in v0.2.0

func DefaultDBConfig(drv Driver) DBConfig

DefaultDBConfig returns sensible default configuration for Kat migrations.

type Driver added in v0.2.0

type Driver = dbdriver.DatabaseDriver

Driver represents a supported database driver type.

func ParseDriver added in v0.2.0

func ParseDriver(name string) (Driver, error)

ParseDriver converts a driver name string into a Driver. Accepted values: "postgres", "postgresql", "" (defaults to postgres), "sqlite", "sqlite3".

type Logger added in v0.0.9

type Logger = loggr.Logger

Logger is the interface used for logging within kat. Implement this interface to provide custom logging behavior.

type Migration

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

Migration manages database schema migrations using a graph-based approach. It tracks applied migrations in a database table and ensures dependencies are respected when applying or rolling back migrations.

func New

func New(drv Driver, connStr string, f fs.FS, migrationTableName string, options ...MigrationOption) (*Migration, error)

New creates a new Migration instance that opens a database connection from a connection string.

Parameters:

  • drv: Database driver (kat.PostgresDriver or kat.SQLiteDriver)
  • connStr: Database connection string (e.g., "postgres://user:pass@host:port/db")
  • f: Filesystem containing migration directories
  • migrationTableName: Name of the table to track applied migrations
  • options: Optional configuration (WithLogger, WithDBConfig, WithConnectTimeout, WithPoolLimits)

func NewWithDB added in v0.0.6

func NewWithDB(drv Driver, sqlDB *sql.DB, f fs.FS, migrationTableName string, options ...MigrationOption) (*Migration, error)

NewWithDB creates a new Migration instance using an existing *sql.DB connection. The caller is responsible for managing the connection's lifecycle, pool settings, and closing the *sql.DB. For SQLite, the caller should set db.SetMaxOpenConns(1) to avoid "database is locked" errors.

Database configuration options (WithDBConfig, WithConnectTimeout, WithPoolLimits) are not supported with NewWithDB — configure the *sql.DB directly instead.

Parameters:

  • drv: Database driver (kat.PostgresDriver or kat.SQLiteDriver)
  • sqlDB: An existing *sql.DB connection (must not be nil)
  • f: Filesystem containing migration directories
  • migrationTableName: Name of the table to track applied migrations
  • options: Optional configuration (WithLogger)

func (*Migration) Close added in v0.2.0

func (m *Migration) Close() error

Close releases resources held by the Migration instance. If the Migration was created with New (kat owns the connection), the database connection is closed. If created with NewWithDB (caller owns the connection), this is a no-op — the caller is responsible for closing the *sql.DB.

func (*Migration) Down

func (m *Migration) Down(ctx context.Context, count int) error

Down rolls back applied migrations from the database. Migrations are rolled back in reverse dependency order. Each rollback runs within a transaction and removes the migration record from the tracking table.

Parameters:

  • ctx: Context for the operation (supports cancellation)
  • count: Number of migrations to roll back (must be positive)

func (*Migration) Up

func (m *Migration) Up(ctx context.Context, count int) error

Up applies pending migrations to the database. Migrations are executed in dependency order as determined by the migration graph. Each migration runs within a transaction for safety.

Parameters:

  • ctx: Context for the operation (supports cancellation)
  • count: Number of migrations to apply (0 means apply all pending)

type MigrationOption added in v0.0.9

type MigrationOption func(*migrationConfig) error

MigrationOption is a function that configures migration settings. Options are applied during construction and only affect configuration, not connection source (use New vs NewWithDB for that).

func WithConnectTimeout added in v0.2.0

func WithConnectTimeout(timeout time.Duration) MigrationOption

WithConnectTimeout configures just the connection establishment timeout. This is a convenience function for the most common configuration need. Only applicable when using New (not NewWithDB).

Example:

m, err := kat.New(kat.PostgresDriver, connStr, fsys, "migrations",
	kat.WithConnectTimeout(5 * time.Second),
)

func WithDBConfig added in v0.2.0

func WithDBConfig(config DBConfig) MigrationOption

WithDBConfig configures the migration to use custom database settings. This allows fine-tuning of connection timeouts, pool limits, and statement timeouts for production deployments. Only applicable when using New (not NewWithDB).

Example:

config := kat.DBConfig{
	ConnectTimeout:   5 * time.Second,
	StatementTimeout: 5 * time.Minute,
	MaxOpenConns:     20,
	MaxIdleConns:     10,
	ConnMaxLifetime:  1 * time.Hour,
	DefaultTimeout:   60 * time.Second,
}
m, err := kat.New(kat.PostgresDriver, connStr, fsys, "migrations",
	kat.WithDBConfig(config),
)

func WithLogger added in v0.0.9

func WithLogger(logger Logger) MigrationOption

WithLogger configures the migration to use a custom logger implementation. The logger must implement the Logger interface with Debug, Info, Warn, and Error methods.

Example:

m, err := kat.New(kat.PostgresDriver, connStr, fsys, "migrations",
	kat.WithLogger(customLogger),
)

func WithPoolLimits added in v0.2.0

func WithPoolLimits(maxOpen, maxIdle int, connMaxLifetime time.Duration) MigrationOption

WithPoolLimits configures the database connection pool limits. This is useful for controlling resource usage in production environments. Only applicable when using New (not NewWithDB).

Example:

m, err := kat.New(kat.PostgresDriver, connStr, fsys, "migrations",
	kat.WithPoolLimits(20, 10, 1*time.Hour),
)

Directories

Path Synopsis
cmd
kat command
examples
lib-demo command
internal
config
Package config handles loading and managing configuration for the kat migration tool.
Package config handles loading and managing configuration for the kat migration tool.
database
Package database provides database connectivity and operations for PostgreSQL and SQLite.
Package database provides database connectivity and operations for PostgreSQL and SQLite.
graph
Package graph provides a directed acyclic graph (DAG) implementation for managing migration dependencies.
Package graph provides a directed acyclic graph (DAG) implementation for managing migration dependencies.
migration
Package migration provides functionality for creating, managing, and executing database migrations.
Package migration provides functionality for creating, managing, and executing database migrations.
output
This file was referenced from https://github.com/sourcegraph/sourcegraph-public-snapshot/blob/0aa8310ca4d924c084a7a3f836d7a4cbc45c3338/lib/output/style.go#L12
This file was referenced from https://github.com/sourcegraph/sourcegraph-public-snapshot/blob/0aa8310ca4d924c084a7a3f836d7a4cbc45c3338/lib/output/style.go#L12
pointers
SOURCE: https://sourcegraph.com/r/github.com/sourcegraph/sourcegraph-public-snapshot@6d5493b/-/blob/lib/pointers/ptr.go
SOURCE: https://sourcegraph.com/r/github.com/sourcegraph/sourcegraph-public-snapshot@6d5493b/-/blob/lib/pointers/ptr.go
types
Package types defines the core data structures and types used throughout the kat migration system.
Package types defines the core data structures and types used throughout the kat migration system.

Jump to

Keyboard shortcuts

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