Documentation
¶
Overview ¶
Package gostgrator provides database migration capabilities.
Package gostgrator provides database migration capabilities.
Package gostgrator provides database migration capabilities.
Package gostgrator provides database-agnostic schema migration utilities for Go applications. It loads *.sql* migration files, tracks execution state in a table you choose, and moves the database forward or backward to any version you specify.
A thin driver layer (currently PostgreSQL and SQLite) supplies SQL dialect differences. Companion CLI tools live under sub-packages *pg* and *sqlite*; the core logic is here.
Install ¶
go get github.com/bcomnes/gostgrator@latest
Quick start ¶
import (
"context"
"database/sql"
_ "github.com/jackc/pgx/v5/stdlib" // or sqlite3
"github.com/bcomnes/gostgrator"
)
func main() {
db, _ := sql.Open("pgx", os.Getenv("DATABASE_URL"))
cfg := gostgrator.Config{
Driver: "pg",
MigrationPattern: "migrations/*.sql",
}
g, _ := gostgrator.NewGostgrator(cfg, db)
g.Migrate(context.Background(), "max")
}
Configuration ¶
Use Config to tweak behaviour:
- Driver — database driver name ("pg", "sqlite3")
- SchemaTable — table that stores migration state (default "schemaversion")
- MigrationPattern — glob for locating migration files
- Newline — line-ending style when scaffolding new migrations
- ValidateChecksums — compare MD5 hashes before running *up* migrations
You can merge Config with your own JSON/YAML file or set it inline.
Migration files ¶
A migration *pair* is two files with the same version and name:
001.do.create_users.sql // apply 001.undo.create_users.sql // roll back
Versions may be plain integers (*001*, *002*, …) or timestamps if you prefer. The CLI’s *new* command scaffolds these files for you.
Programmatic API ¶
NewGostgrator(cfg, db) → *Gostgrator (*Gostgrator).Migrate(ctx, v) → []Migration, error (*Gostgrator).Down(ctx, n) → []Migration, error (*Gostgrator).GetMigrations() → []Migration, error (*Gostgrator).GetDatabaseVersion(ctx) → int, error
All operations are context-aware; cancel the context to abort long runs.
CLI helpers ¶
If you prefer shell commands, install driver-specific binaries:
go get -tool github.com/bcomnes/gostgrator/pg@latest # PostgreSQL go get -tool github.com/bcomnes/gostgrator/sqlite@latest # SQLite
See each sub-package’s doc for flags and usage.
Exit codes ¶
The library returns errors; the CLIs exit with non-zero status on any failure. ValidateErrors include version and MD5 info for easy triage.
Versioning ¶
A semantic version string is exposed as:
var Version = "vX.Y.Z"
Embed it in your own commands to surface gostgrator’s build version.
Generated documentation; update whenever public API or CLI flags change.
Package gostgrator provides database migration capabilities.
Index ¶
- Variables
- func CreateMigration(cfg Config, description string, mode string) error
- type Client
- type Config
- type Gostgrator
- func (g *Gostgrator) CreateMigration(description, mode string) error
- func (g *Gostgrator) Down(ctx context.Context, steps int) ([]Migration, error)
- func (g *Gostgrator) GetDatabaseVersion(ctx context.Context) (int, error)
- func (g *Gostgrator) GetMaxVersion() (int, error)
- func (g *Gostgrator) GetMigrations() ([]Migration, error)
- func (g *Gostgrator) GetRunnableMigrations(databaseVersion, targetVersion int) ([]Migration, error)
- func (g *Gostgrator) Migrate(ctx context.Context, target string) ([]Migration, error)
- func (g *Gostgrator) QueryContext(ctx context.Context, query string) (*sql.Rows, error)
- func (g *Gostgrator) RunMigrations(ctx context.Context, migrations []Migration) ([]Migration, error)
- func (g *Gostgrator) ValidateMigrations(ctx context.Context, databaseVersion int) error
- type Migration
- type PostgresClient
- func (c *PostgresClient) EnsureTable(ctx context.Context) error
- func (c *PostgresClient) ExecContext(ctx context.Context, script string) (sql.Result, error)
- func (c *PostgresClient) GetDatabaseVersionSql() string
- func (c *PostgresClient) GetMd5Sql(m Migration) string
- func (c *PostgresClient) HasVersionTable(ctx context.Context) (bool, error)
- func (c *PostgresClient) PersistActionSql(m Migration) string
- func (c *PostgresClient) QueryContext(ctx context.Context, query string) (*sql.Rows, error)
- type Sqlite3Client
- func (c *Sqlite3Client) EnsureTable(ctx context.Context) error
- func (c *Sqlite3Client) ExecContext(ctx context.Context, script string) (sql.Result, error)
- func (c *Sqlite3Client) GetDatabaseVersionSql() string
- func (c *Sqlite3Client) GetMd5Sql(m Migration) string
- func (c *Sqlite3Client) HasVersionTable(ctx context.Context) (bool, error)
- func (c *Sqlite3Client) PersistActionSql(m Migration) string
- func (c *Sqlite3Client) QueryContext(ctx context.Context, query string) (*sql.Rows, error)
Constants ¶
This section is empty.
Variables ¶
var DefaultConfig = Config{ SchemaTable: "schemaversion", ValidateChecksums: true, }
DefaultConfig provides default values for configuration.
var (
Version = "1.0.4"
)
Functions ¶
func CreateMigration ¶
CreateMigration creates a new pair of migration files (do/undo). description: a human-readable description that will be kebab-cased for the filename. mode: "int" for integer increment (default) or "timestamp" to use the Unix timestamp.
Types ¶
type Client ¶
type Client interface {
QueryContext(ctx context.Context, query string) (*sql.Rows, error)
ExecContext(ctx context.Context, script string) (sql.Result, error)
GetDatabaseVersionSql() string
HasVersionTable(ctx context.Context) (bool, error)
EnsureTable(ctx context.Context) error
GetMd5Sql(m Migration) string
PersistActionSql(m Migration) string
}
Client defines the interface for migration clients.
func NewClient ¶
NewClient creates a new Client based on the provided configuration and database connection.
func NewPostgresClient ¶
NewPostgresClient creates a new PostgresClient.
type Config ¶
type Config struct {
// Driver is the database driver, e.g., "pg" or "sqlite3".
Driver string
// SchemaTable is the name of the migration table.
SchemaTable string
// MigrationPattern is the glob pattern for migration files (e.g. "./migrations/*.sql").
MigrationPattern string
// Newline is the desired newline style ("LF", "CR", or "CRLF").
Newline string
// ValidateChecksums indicates if the tool should validate migration checksums.
ValidateChecksums bool
}
Config holds settings for migrations.
type Gostgrator ¶
type Gostgrator struct {
// contains filtered or unexported fields
}
Gostgrator is the main orchestrator for running database migrations.
It loads migration files, determines the current database version, validates checksums (if enabled), and runs the necessary migrations to reach a target version.
func NewGostgrator ¶
func NewGostgrator(cfg Config, db *sql.DB) (*Gostgrator, error)
NewGostgrator creates a new Gostgrator instance with the provided configuration and database connection.
func (*Gostgrator) CreateMigration ¶
func (g *Gostgrator) CreateMigration(description, mode string) error
(Optional) If you prefer to expose this functionality as a method on Gostgrator, you can add the following method.
func (*Gostgrator) Down ¶
Down rolls back the migrations by the given number of steps. It computes the target version as the current version minus steps (not going below zero), and then calls Migrate to perform the undo operations.
func (*Gostgrator) GetDatabaseVersion ¶
func (g *Gostgrator) GetDatabaseVersion(ctx context.Context) (int, error)
GetDatabaseVersion returns the current database version. If the migration table is not initialized, it returns 0.
func (*Gostgrator) GetMaxVersion ¶
func (g *Gostgrator) GetMaxVersion() (int, error)
GetMaxVersion returns the highest migration version available.
func (*Gostgrator) GetMigrations ¶
func (g *Gostgrator) GetMigrations() ([]Migration, error)
func (*Gostgrator) GetRunnableMigrations ¶
func (g *Gostgrator) GetRunnableMigrations(databaseVersion, targetVersion int) ([]Migration, error)
func (*Gostgrator) Migrate ¶
Migrate moves the schema to the target version. If target is "max" or empty, it migrates to the highest available version.
func (*Gostgrator) QueryContext ¶
QueryContext is a helper to execute a query using the underlying client.
func (*Gostgrator) RunMigrations ¶
func (g *Gostgrator) RunMigrations(ctx context.Context, migrations []Migration) ([]Migration, error)
RunMigrations applies the provided migrations in sequence.
func (*Gostgrator) ValidateMigrations ¶
func (g *Gostgrator) ValidateMigrations(ctx context.Context, databaseVersion int) error
ValidateMigrations verifies that applied migrations have not changed by comparing MD5 checksums.
type Migration ¶
type Migration struct {
// Version of the migration.
Version int
// Action, e.g., "do" or "undo".
Action string
// Filename is the path to the migration file.
Filename string
// Name is an optional descriptive name of the migration.
Name string
// Md5 is the MD5 checksum of the migration file.
Md5 string
}
Migration represents a single migration file.
type PostgresClient ¶
type PostgresClient struct {
// contains filtered or unexported fields
}
PostgresClient implements the Client interface for PostgreSQL.
func (*PostgresClient) EnsureTable ¶
EnsureTable creates the migration table if it does not exist and adds missing columns.
func (*PostgresClient) ExecContext ¶
Exposing ExecContext from the configured db connection.
func (*PostgresClient) GetDatabaseVersionSql ¶
func (c *PostgresClient) GetDatabaseVersionSql() string
GetDatabaseVersionSql returns SQL to fetch the highest applied migration version.
func (*PostgresClient) GetMd5Sql ¶
GetMd5Sql returns SQL to fetch the MD5 checksum for a migration version.
func (*PostgresClient) HasVersionTable ¶
HasVersionTable checks for the existence of the migration table.
func (*PostgresClient) PersistActionSql ¶
PersistActionSql generates SQL to record a migration action.
type Sqlite3Client ¶
type Sqlite3Client struct {
// contains filtered or unexported fields
}
Sqlite3Client implements the Client interface for SQLite.
func (*Sqlite3Client) EnsureTable ¶
EnsureTable creates the migration table if it does not exist and adds missing columns.
func (*Sqlite3Client) ExecContext ¶
Exposing ExecContext from the configured db connection.
func (*Sqlite3Client) GetDatabaseVersionSql ¶
func (c *Sqlite3Client) GetDatabaseVersionSql() string
GetDatabaseVersionSql returns SQL to fetch the highest applied migration version.
func (*Sqlite3Client) GetMd5Sql ¶
GetMd5Sql returns SQL to fetch the MD5 checksum for a migration version.
func (*Sqlite3Client) HasVersionTable ¶
HasVersionTable checks for the existence of the migration table.
func (*Sqlite3Client) PersistActionSql ¶
PersistActionSql generates SQL to record a migration action.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package main provides gostgrator-pg, a PostgreSQL-specific command-line interface for the gostgrator migration library.
|
Package main provides gostgrator-pg, a PostgreSQL-specific command-line interface for the gostgrator migration library. |
|
Package main provides gostgrator-sqlite, a SQLite-specific command-line interface for the gostgrator migration library.
|
Package main provides gostgrator-sqlite, a SQLite-specific command-line interface for the gostgrator migration library. |