persistence

package module
v0.16.1 Latest Latest
Warning

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

Go to latest
Published: May 22, 2026 License: MIT Imports: 34 Imported by: 12

README

Go Persistence BUN

A package for managing database connections, migrations, and fixtures using BUN.

Installation

go get github.com/goliatone/go-persistence-bun

Usage

Basic Setup
import (
    "database/sql"
    "time"
    
    persistence "github.com/goliatone/go-persistence-bun"
    "github.com/uptrace/bun/dialect/pgdialect"
    _ "github.com/lib/pq" // PostgreSQL driver
)

// Define your configuration struct that implements the Config interface
type Config struct {
    Debug          bool
    Driver         string
    Server         string
    PingTimeout    time.Duration
    OtelIdentifier string
}

func (c *Config) GetDebug() bool {
    return c.Debug
}

func (c *Config) GetDriver() string {
    return c.Driver
}

func (c *Config) GetServer() string {
    return c.Server
}

func (c *Config) GetPingTimeout() time.Duration {
    return c.PingTimeout
}

func (c *Config) GetOtelIdentifier() string {
    return c.OtelIdentifier
}

// Initialize the client
config := &Config{
    Driver:      persistence.DefaultDriver, // "postgres"
    Server:      "localhost:5432",
    PingTimeout: 5 * time.Second,
}

// Create connection string (example for PostgreSQL)
connectionString := "postgres://user:password@localhost:5432/myapp?sslmode=disable"

db, err := sql.Open(config.GetDriver(), connectionString)
if err != nil {
    log.Fatal(err)
}

client, err := persistence.New(config, db, pgdialect.New())
if err != nil {
    log.Fatal(err)
}
defer client.Close()
Query Hooks

Custom query hooks are configured via ClientOptions passed to New. Built-in hooks are opt-in and use config values when enabled.

client, err := persistence.New(
    config,
    db,
    pgdialect.New(),
    persistence.WithQueryHooks(adm.DebugQueryHook()),
    persistence.WithBundebug(), // uses GetDebug() for verbosity
    persistence.WithBunotel(),  // uses GetOtelIdentifier() for DB name
)
if err != nil {
    log.Fatal(err)
}
defer client.Close()

To control registration order, use WithQueryHooksPriority(priority, hooks...).

Transaction Helper (validation_runs + validation_issues)

Use RunInTx to atomically persist a validation run and all related issues.

type ValidationRun struct {
    bun.BaseModel `bun:"table:validation_runs"`
    ID         int64               `bun:"id,pk,autoincrement"`
    MerchantID string              `bun:"merchant_id,notnull"`
    Channel    string              `bun:"channel,notnull"`
    Status     string              `bun:"status,notnull"`
    Counts     persistence.JSONMap `bun:"counts,type:jsonb"` // use type:json for sqlite
}

type ValidationIssue struct {
    bun.BaseModel `bun:"table:validation_issues"`
    ID        int64  `bun:"id,pk,autoincrement"`
    RunID     int64  `bun:"run_id,notnull"`
    Severity  string `bun:"severity,notnull"`
    IssueCode string `bun:"issue_code,notnull"`
    Message   string `bun:"message"`
    Status    string `bun:"status,notnull"`
}

err := persistence.RunInTx(ctx, client.DB(), func(ctx context.Context, tx bun.Tx) error {
    run := &ValidationRun{
        MerchantID: "merchant-1",
        Channel:    "shopify",
        Status:     "running",
        Counts: persistence.JSONMap{
            "blocker": 1,
            "warning": 2,
            "pass":    5,
        },
    }

    if _, err := tx.NewInsert().Model(run).Exec(ctx); err != nil {
        return err
    }
    runID := run.ID

    issues := []*ValidationIssue{
        {RunID: runID, Severity: "blocker", IssueCode: "missing_tax_id", Message: "Tax ID missing", Status: "open"},
        {RunID: runID, Severity: "warning", IssueCode: "missing_logo", Message: "Logo missing", Status: "open"},
    }

    for _, issue := range issues {
        if _, err := tx.NewInsert().Model(issue).Exec(ctx); err != nil {
            return err
        }
    }
    return nil
})
if err != nil {
    log.Fatal(err)
}
Portable JSON Types

Use JSONMap and JSONStringSlice to round-trip JSON values across Postgres and SQLite.

type ValidationIssue struct {
    bun.BaseModel `bun:"table:validation_issues"`
    ID      int64                     `bun:"id,pk,autoincrement"`
    Meta    persistence.JSONMap       `bun:"meta,type:jsonb"` // use type:json for sqlite
    Tags    persistence.JSONStringSlice `bun:"tags,type:jsonb"`
}

For deterministic grouped counts, use NewGroupedCountQuery:

var counts []persistence.GroupCount
err := persistence.NewGroupedCountQuery(client.DB(), (*ValidationIssue)(nil), "severity").
    Where("run_id = ?", runID).
    Scan(ctx, &counts)
Migrations
// SQL migrations from embedded filesystem
//go:embed migrations/*.sql
var migrationsFS embed.FS

// Register migrations
client.RegisterSQLMigrations(migrationsFS)

// Run migrations
if err := client.Migrate(context.Background()); err != nil {
    log.Fatal(err)
}

// Rollback last migration group
if err := client.Rollback(context.Background()); err != nil {
    log.Fatal(err)
}

// Dialect-aware migrations (Postgres + SQLite)
//go:embed data/sql/migrations/**/*
var dialectFS embed.FS

client.RegisterDialectMigrations(
    dialectFS,
    persistence.WithDialectSourceLabel("data/sql/migrations"),
    persistence.WithValidationTargets("postgres", "sqlite"),
    persistence.WithDialectValidationContract(persistence.DialectValidationContract{
        MandatoryTargets:                  []string{"postgres", "sqlite"},
        RequireAtLeastOneSQL:              true,
        RequireUpDownPairs:                true,
        RequireVersionParityAcrossTargets: true,
    }),
    persistence.WithValidateOnMigrate(true), // optional: auto-run validation before Migrate
)
if err := client.ValidateDialects(context.Background()); err != nil {
    log.Fatal(err)
}

// Source-stable ordered package migrations
err := client.RegisterOrderedMigrationSources(
    persistence.NewStableOrderedMigrationSource("go-auth", authFS, "go-auth", 10),
    persistence.NewStableOrderedMigrationSource(
        "go-users",
        usersFS,
        "go-users",
        20,
        persistence.WithOrderedMigrationDependencies("go-auth"),
    ),
)
if err != nil {
    log.Fatal(err)
}

For detailed migration documentation, see MIGRATIONS.md.

Fixtures
// Register fixtures
client.RegisterFixtures(fixtures.FS)

// Load fixtures
if err := client.Seed(context.Background()); err != nil {
    log.Fatal(err)
}
Model Registration

Register models before creating the client to ensure they're available for migrations and fixtures:

type User struct {
    ID   int64  `bun:"id,pk,autoincrement"`
    Name string
}

// Register regular models
persistence.RegisterModel((*User)(nil))

// Register many-to-many relationship models
persistence.RegisterMany2ManyModel((*UserGroup)(nil))

Configuration Options

Config Interface

The Config interface requires the following methods:

  • GetDebug() bool: Enable debug mode with query logging
  • GetDriver() string: Database driver (default: "postgres")
  • GetServer() string: Database server address
  • GetPingTimeout() time.Duration: Connection ping timeout
  • GetOtelIdentifier() string: OpenTelemetry identifier for tracing

Optional methods that can be implemented:

  • GetMigrationsEnabled() bool: Enable/disable migrations
  • GetSeedsEnabled() bool: Enable/disable seeds/fixtures

Note: GetDebug() and GetOtelIdentifier() only affect query hooks when WithBundebug() and WithBunotel() are supplied to New(...).

Client Options
  • WithQueryHooks(hooks ...bun.QueryHook): Register custom query hooks
  • WithQueryHooksPriority(priority int, hooks ...bun.QueryHook): Register hooks with a custom priority
  • WithQueryHookErrorHandler(handler QueryHookErrorHandler): Handle invalid hook registration
  • WithBundebug(): Enable bundebug query logging (uses GetDebug() for verbosity)
  • WithBunotel(): Enable bunotel tracing (uses GetOtelIdentifier() for DB name)
Fixture Options
  • WithTruncateTables(): Truncate tables before loading fixtures
  • WithDropTables(): Drop tables before loading fixtures
  • WithFS(dir fs.FS): Add filesystem for fixtures/migrations
  • WithTemplateFuncs(funcMap template.FuncMap): Add template functions for fixtures
  • WithFileFilter(fn func(path, name string) bool): Custom file filtering
Fixture Template Functions

The fixture loader supports a small set of template functions when rendering seed files:

  • hashid: Generate a hashid string from a value.
  • hashpwd: Generate a bcrypt password hash from a value (non-deterministic across runs).

Example usage in a fixture file:

users:
  - email: "admin@example.com"
    password: '{{ hashpwd "admin123" }}'

API Reference

Client Methods
  • New(cfg Config, sqlDB *sql.DB, dialect schema.Dialect, opts ...ClientOption) (*Client, error): Create a new client
  • RunInTx(ctx context.Context, db bun.IDB, fn func(ctx context.Context, tx bun.Tx) error) error: Run writes in one transaction with rollback safety
  • DB() *bun.DB: Get the underlying BUN database instance
  • Check() error: Check database connection
  • MustConnect(): Panic if connection fails
  • Close() error: Close database connection
  • SetLogger(logger Logger): Set a custom logger
Migrations
  • Migrate(ctx context.Context) error: Run pending migrations
  • MigrateSources(ctx context.Context, sourceNames ...string) error: Run pending migrations for a selected source subset
  • Plan(ctx context.Context) (*MigrationPlan, error): Resolve the current execution plan for all registered sources
  • PlanSources(ctx context.Context, sourceNames ...string) (*MigrationPlan, error): Resolve the plan for a selected source subset
  • LastPlan() *MigrationPlan: Return the last resolved migration plan
  • RegisterSQLMigrations(migrations ...fs.FS) *Migrations: Register SQL migrations
  • RegisterOrderedMigrationSources(sources ...OrderedMigrationSource) error: Register ordered, source-aware SQL migration sources
  • NewStableOrderedMigrationSource(...) OrderedMigrationSource: Build a source-stable ordered source with explicit key/order/dependencies
  • BackfillStableOrderedMigrationMarkers(...) error: Repair legacy positional ordered markers for source-stable adoption
  • GetMigrations() *Migrations: Get migrations manager
  • Rollback(ctx context.Context, opts ...migrate.MigrationOption) error: Rollback one migration group
  • RollbackAll(ctx context.Context, opts ...migrate.MigrationOption) error: Rollback all migrations
  • Report() *migrate.MigrationGroup: Get migration status report
Fixtures
  • Seed(ctx context.Context) error: Load fixtures
  • RegisterFixtures(migrations ...fs.FS) *Fixtures: Register fixtures
  • GetFixtures() *Fixtures: Get fixtures manager
Service Interface
  • Start(ctx context.Context) error: Start the service (for service-based architectures)
  • Stop(ctx context.Context) error: Stop the service
  • Name() string: Get service name ("persistence")
  • Priority() int: Get service priority

Features

  • Database connection management with connection pooling
  • SQL migrations support via filesystem
  • Fixtures/seeds support with template functions
  • OpenTelemetry integration for distributed tracing (opt-in via WithBunotel)
  • Debug mode with comprehensive query logging (opt-in via WithBundebug)
  • Support for multiple database dialects through BUN
  • Model registration for ORM operations
  • Many-to-many relationship support
  • Transaction support through BUN's API
  • Additive transaction helper (RunInTx) for portable service-level writes
  • Portable JSON wrappers (JSONMap, JSONStringSlice) for Postgres JSONB and SQLite JSON/TEXT
  • Context-aware operations

License

MIT

Copyright (c) 2024 goliatone

Documentation

Index

Constants

View Source
const (
	VirtualDialectPostgres = "postgres"
	VirtualDialectSQLite   = "sqlite"
)
View Source
const DefaultDriver = "postgres"

DefaultDriver is the Postgres driver

View Source
const MaxOrderedMigrationSourceOrder = 999999

MaxOrderedMigrationSourceOrder is the largest explicit source-stable order that fits the fixed-width lexical migration name prefix.

View Source
const Name = "persistence"

Name is the string identifier of the module

Variables

View Source
var (
	ErrQueryHookNil        = errors.New("query hook is nil")
	ErrQueryHookNilPointer = errors.New("query hook is a nil pointer")
)
View Source
var (
	ErrOrderedSourceInvalidConfig   = errors.New("invalid ordered migration source configuration")
	ErrOrderedSourceMixedIdentity   = errors.New("mixed ordered migration source identity modes")
	ErrOrderedSourceDuplicateKey    = errors.New("duplicate ordered migration source key")
	ErrOrderedSourceUnknownDep      = errors.New("unknown ordered migration source dependency")
	ErrOrderedSourceCycle           = errors.New("ordered migration source dependency cycle")
	ErrOrderedSourceOrderInversion  = errors.New("ordered migration source dependency order inversion")
	ErrOrderedSourceMissingSelected = errors.New("selected ordered migration source dependency is missing")
)
View Source
var (
	ErrOrderedSourceDrift                 = errors.New("ordered migration source graph drift")
	ErrOrderedSourceRepair                = errors.New("ordered migration source repair failed")
	ErrOrderedSourceRepairMissingMapping  = errors.New("ordered migration source repair missing legacy mapping")
	ErrOrderedSourceRepairAmbiguousMarker = errors.New("ordered migration source repair ambiguous legacy marker")
	ErrOrderedSourceRepairMarkerMismatch  = errors.New("ordered migration source repair marker/source mismatch")
)
View Source
var (
	// ErrTxDBNil indicates RunInTx was called with a nil database handle.
	ErrTxDBNil = errors.New("persistence: transaction db handle is nil")
	// ErrTxFuncNil indicates RunInTx was called with a nil callback.
	ErrTxFuncNil = errors.New("persistence: transaction callback is nil")
)
View Source
var LoggerEnabled = false
View Source
var Priority int

Priority is the module's loading priority

Functions

func LogQueryHookErrorHandler added in v0.10.0

func LogQueryHookErrorHandler(db *bun.DB, hook bun.QueryHook, err error)

LogQueryHookErrorHandler logs and skips invalid query hooks.

func NewGroupedCountQuery added in v0.11.0

func NewGroupedCountQuery(db bun.IDB, model any, groupColumn string) *bun.SelectQuery

NewGroupedCountQuery builds a grouped count query ordered by group key.

The query uses bun.Ident placeholders to avoid string-concatenated SQL.

func PanicQueryHookErrorHandler added in v0.10.0

func PanicQueryHookErrorHandler(db *bun.DB, hook bun.QueryHook, err error)

PanicQueryHookErrorHandler panics on invalid query hooks.

func RegisterMany2ManyModel added in v0.0.3

func RegisterMany2ManyModel(model ...any)

func RegisterModel

func RegisterModel(model ...any)

RegisterModel registers a model in Bun or, if the global instance is not yet initialized, will enqueue the models, which will be registered once the global instance is initialized. RegisterModel registers models by name so they can be referenced in table relations and fixtures. persistence.RegisterModel((*models.User)(nil)) persistence.RegisterModel(&model.User{})

func RunInTx added in v0.11.0

func RunInTx(ctx context.Context, db bun.IDB, fn func(ctx context.Context, tx bun.Tx) error) (err error)

RunInTx executes fn in a transaction.

When db is an existing bun.Tx (or *bun.Tx), fn is executed directly without starting a nested transaction/savepoint. Otherwise, a new transaction is started and committed on success, and rolled back on error or panic.

func VirtualFieldExpr added in v0.7.0

func VirtualFieldExpr(dialect, sourceField, key string, asJSON bool) string

VirtualFieldExpr returns a SQL snippet for the given dialect to access a JSON/JSONB field. When asJSON is false, text extraction is used (suitable for comparisons/order-by). When asJSON is true, the raw JSON value is returned.

Types

type Client

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

Client is the persistence client

func New

func New(cfg Config, sqlDB *sql.DB, dialect schema.Dialect, opts ...ClientOption) (*Client, error)

New creates a new client Optionally if Config has defined these methods they will configure the related functionality: - GetSeedsEnabled - GetMigrationsEnabled

func (Client) Check

func (c Client) Check() error

Check will check connection

func (Client) Close

func (c Client) Close() error

Close will close the client

func (Client) Config added in v0.9.0

func (c Client) Config() Config

Config returns the client configuration

func (Client) DB

func (c Client) DB() *bun.DB

DB returns a database

func (Client) GetFixtures

func (c Client) GetFixtures() *Fixtures

GetFixtures will return fixtures

func (Client) GetMigrations

func (c Client) GetMigrations() *Migrations

GetMigrations will migrate db

func (Client) LastPlan added in v0.13.1

func (c Client) LastPlan() *MigrationPlan

LastPlan returns the last resolved migration plan.

func (Client) Migrate

func (c Client) Migrate(ctx context.Context) error

Migrate will migrate db

func (Client) MigrateSources added in v0.13.1

func (c Client) MigrateSources(ctx context.Context, sourceNames ...string) error

MigrateSources runs migrations for a selected subset of registered sources.

func (Client) MustConnect

func (c Client) MustConnect()

MustConnect will panic if no connection

func (*Client) Name

func (c *Client) Name() string

Name will return the module name

func (Client) Ping added in v0.9.0

func (c Client) Ping(ctx context.Context) error

Ping will ping the database

func (Client) Plan added in v0.13.1

func (c Client) Plan(ctx context.Context) (*MigrationPlan, error)

Plan resolves the current migration plan for all registered sources.

func (Client) PlanSources added in v0.13.1

func (c Client) PlanSources(ctx context.Context, sourceNames ...string) (*MigrationPlan, error)

PlanSources resolves the migration plan for a selected subset of sources.

func (*Client) Priority

func (c *Client) Priority() int

Priority will return the module priority

func (Client) RegisterDialectMigrations added in v0.6.0

func (c Client) RegisterDialectMigrations(root fs.FS, opts ...DialectMigrationOption) *Migrations

RegisterDialectMigrations adds dialect-aware SQL migrations.

func (Client) RegisterFixtures

func (c Client) RegisterFixtures(migrations ...fs.FS) *Fixtures

RegisterFixtures adds file based fixtures

func (Client) RegisterOrderedMigrationSources added in v0.12.0

func (c Client) RegisterOrderedMigrationSources(sources ...OrderedMigrationSource) error

RegisterOrderedMigrationSources adds ordered, source-aware SQL migration sources.

func (Client) RegisterSQLMigrations

func (c Client) RegisterSQLMigrations(migrations ...fs.FS) *Migrations

RegisterSQLMigrations adds SQL based migrations

func (Client) Report

func (c Client) Report() *migrate.MigrationGroup

Report returns the status of migrations. It returns nil if Execute has not been called or has failed.

func (Client) Rollback

func (c Client) Rollback(ctx context.Context, opts ...migrate.MigrationOption) error

Rollback previously executed migrations. It will rollback a group at a time. See https://bun.uptrace.dev/guide/migrations.html#migration-groups-and-rollbacks.

func (Client) RollbackAll

func (c Client) RollbackAll(ctx context.Context, opts ...migrate.MigrationOption) error

RollbackAll rollbacks every registered migration group.

func (Client) Seed

func (c Client) Seed(ctx context.Context) error

Seed will run seeds

func (*Client) SetLogger added in v0.0.2

func (c *Client) SetLogger(logger Logger)

func (*Client) Start

func (c *Client) Start(ctx context.Context) error

Start will start the service

func (*Client) Stop

func (c *Client) Stop(ctx context.Context) error

Stop will stop the service

func (Client) ValidateDialects added in v0.6.0

func (c Client) ValidateDialects(ctx context.Context) error

ValidateDialects runs validation callbacks for registered dialect migrations.

type ClientOption added in v0.10.0

type ClientOption func(*clientOptions)

ClientOption configures the persistence client.

func WithBundebug added in v0.10.0

func WithBundebug() ClientOption

WithBundebug enables bundebug query hook registration.

func WithBunotel added in v0.10.0

func WithBunotel() ClientOption

WithBunotel enables bunotel query hook registration.

func WithQueryHookErrorHandler added in v0.10.0

func WithQueryHookErrorHandler(handler QueryHookErrorHandler) ClientOption

WithQueryHookErrorHandler sets the hook registration error handler.

func WithQueryHooks added in v0.10.0

func WithQueryHooks(hooks ...bun.QueryHook) ClientOption

WithQueryHooks registers custom query hooks with default priority.

func WithQueryHooksPriority added in v0.10.0

func WithQueryHooksPriority(priority int, hooks ...bun.QueryHook) ClientOption

WithQueryHooksPriority registers custom hooks with the given priority.

type Config

type Config interface {
	GetDebug() bool
	GetDriver() string
	GetServer() string
	GetPingTimeout() time.Duration
	GetOtelIdentifier() string
}

Config has values for configurable properties

type DialectMigrationOption added in v0.6.0

type DialectMigrationOption func(*dialectOptions)

DialectMigrationOption configures dialect-aware migration registration.

func WithDefaultDialect added in v0.6.0

func WithDefaultDialect(name string) DialectMigrationOption

WithDefaultDialect overrides the fallback dialect used when detection fails.

func WithDialectAliases added in v0.6.0

func WithDialectAliases(overrides map[string]string) DialectMigrationOption

WithDialectAliases extends or overrides the built-in alias map.

func WithDialectName added in v0.6.0

func WithDialectName(name string) DialectMigrationOption

WithDialectName forces a specific dialect to be used for this registration.

func WithDialectResolver added in v0.6.0

func WithDialectResolver(resolver DialectResolver) DialectMigrationOption

WithDialectResolver sets a callback that resolves the active dialect at runtime.

func WithDialectSourceLabel added in v0.6.0

func WithDialectSourceLabel(label string) DialectMigrationOption

WithDialectSourceLabel sets a human-readable label used in validation errors.

func WithDialectValidationContract added in v0.12.0

func WithDialectValidationContract(contract DialectValidationContract) DialectMigrationOption

WithDialectValidationContract enables strict, opt-in dialect coverage validation.

func WithDialectValidator added in v0.6.0

func WithDialectValidator(fn DialectValidationFunc) DialectMigrationOption

WithDialectValidator overrides the default panic-on-failure behavior.

func WithValidateOnMigrate added in v0.12.0

func WithValidateOnMigrate(enabled bool) DialectMigrationOption

WithValidateOnMigrate runs dialect validation before migration execution.

func WithValidationTargets added in v0.6.0

func WithValidationTargets(names ...string) DialectMigrationOption

WithValidationTargets enables dialect validation for the provided targets. Passing no names causes the resolved dialect to be validated.

type DialectResolver added in v0.6.0

type DialectResolver func(ctx context.Context, db *bun.DB) (string, error)

DialectResolver allows callers to supply a dialect name dynamically.

type DialectValidationContract added in v0.12.0

type DialectValidationContract struct {
	MandatoryTargets                  []string
	RequireAtLeastOneSQL              bool
	RequireUpDownPairs                bool
	RequireVersionParityAcrossTargets bool
}

DialectValidationContract enables stricter, opt-in source-level checks.

type DialectValidationFunc added in v0.6.0

type DialectValidationFunc func(ctx context.Context, result DialectValidationResult) error

DialectValidationFunc is invoked when validation detects missing coverage.

type DialectValidationResult added in v0.6.0

type DialectValidationResult struct {
	SourceLabel        string
	RegistrationIdx    int
	CheckedDialects    []string
	MissingDialects    map[string][]string
	DialectAliases     map[string]string
	AvailableLayers    []layerDiagnostic
	RequestedTargets   []string
	ValidationContract *DialectValidationContract
}

DialectValidationResult summarizes the dialect coverage outcome for a registration.

type DriverConfig

type DriverConfig interface {
	Connect(options ...bun.DBOption) (*bun.DB, *sql.DB, error)
}

DriverConfig remains the same

type FixtureOption

type FixtureOption func(s *Fixtures)

FixtureOption configures the seed manager

func WithDropTables

func WithDropTables() FixtureOption

WithDropTables will drop tables

func WithFS

func WithFS(dir fs.FS) FixtureOption

WithFS will truncate tables

func WithFileFilter

func WithFileFilter(fn func(path, name string) bool) FixtureOption

WithFileFilter will add a file filter function. Each file found in the given dir will be passed throu this function, and if it returns false the file will be filtered out.

func WithTemplateFuncs

func WithTemplateFuncs(funcMap template.FuncMap) FixtureOption

WithTemplateFuncs are used to solve functions in seed file

func WithTrucateTables

func WithTrucateTables() FixtureOption

WithTrucateTables will truncate tables

type Fixtures

type Fixtures struct {
	FileFilter func(path, name string) bool
	// contains filtered or unexported fields
}

Fixtures manages fixtures and seeds

func NewSeedManager

func NewSeedManager(db *bun.DB, opts ...FixtureOption) *Fixtures

NewSeedManager generates a new seed manger

func (*Fixtures) AddOptions

func (s *Fixtures) AddOptions(opts ...FixtureOption) *Fixtures

AddOptions will configure options

func (*Fixtures) Load

func (s *Fixtures) Load(ctx context.Context) error

Load will load all fixtures from all configured directories. It returns a rich error if any part of the process fails.

func (*Fixtures) LoadFile

func (s *Fixtures) LoadFile(ctx context.Context, file string) error

LoadFile will search for and load a single file across all configured directories.

type GroupCount added in v0.11.0

type GroupCount struct {
	Key   string `bun:"group_key"`
	Count int64  `bun:"group_count"`
}

GroupCount is a deterministic grouped-count row shape.

type JSONMap added in v0.11.0

type JSONMap map[string]any

JSONMap is a portable JSON object wrapper for Bun models. It is suitable for PostgreSQL JSONB and SQLite JSON/TEXT columns.

func (*JSONMap) Scan added in v0.11.0

func (m *JSONMap) Scan(src any) error

Scan implements sql.Scanner.

func (JSONMap) Value added in v0.11.0

func (m JSONMap) Value() (driver.Value, error)

Value implements driver.Valuer.

type JSONStringSlice added in v0.11.0

type JSONStringSlice []string

JSONStringSlice is a portable JSON string-array wrapper for Bun models. It is suitable for PostgreSQL JSONB and SQLite JSON/TEXT columns.

func (*JSONStringSlice) Scan added in v0.11.0

func (s *JSONStringSlice) Scan(src any) error

Scan implements sql.Scanner.

func (JSONStringSlice) Value added in v0.11.0

func (s JSONStringSlice) Value() (driver.Value, error)

Value implements driver.Valuer.

type Logger added in v0.1.0

type Logger interface {
	Debug(format string, args ...any)
	Info(format string, args ...any)
	Warn(format string, args ...any)
	Error(format string, args ...any)
	Fatal(format string, args ...any)
}

type MigrationPlan added in v0.13.1

type MigrationPlan struct {
	SelectedSources []string             `json:"selected_sources,omitempty"`
	Entries         []MigrationPlanEntry `json:"entries"`
}

MigrationPlan describes the resolved migration order for a source selection.

type MigrationPlanEntry added in v0.13.1

type MigrationPlanEntry struct {
	SyntheticName    string                       `json:"synthetic_name"`
	SourceName       string                       `json:"source_name"`
	SourceKind       MigrationSourceKind          `json:"source_kind"`
	SourceLabel      string                       `json:"source_label,omitempty"`
	SourceKey        string                       `json:"source_key,omitempty"`
	SourceOrder      int                          `json:"source_order,omitempty"`
	SourceDependsOn  []string                     `json:"source_depends_on,omitempty"`
	ResolvedPosition int                          `json:"resolved_source_position,omitempty"`
	IdentityMode     OrderedMigrationIdentityMode `json:"identity_mode,omitempty"`
	OriginalVersion  string                       `json:"original_version"`
	OriginalComment  string                       `json:"original_comment"`
	UpPath           string                       `json:"up_path,omitempty"`
	DownPath         string                       `json:"down_path,omitempty"`
	ExecutionOrder   int                          `json:"execution_order"`
	Dialect          string                       `json:"dialect,omitempty"`
	Applied          bool                         `json:"applied"`
	AppliedGroupID   int64                        `json:"applied_group_id,omitempty"`
	AppliedAt        time.Time                    `json:"applied_at"`
}

MigrationPlanEntry captures one resolved migration in execution order.

type MigrationSourceKind added in v0.13.1

type MigrationSourceKind string

MigrationSourceKind identifies the registration model that produced a plan entry.

const (
	MigrationSourceKindSQL     MigrationSourceKind = "sql"
	MigrationSourceKindDialect MigrationSourceKind = "dialect"
	MigrationSourceKindOrdered MigrationSourceKind = "ordered"
)

type Migrations

type Migrations struct {
	Files []fs.FS // For SQL files
	// contains filtered or unexported fields
}

Migrations holds configuration options for migrations See https://bun.uptrace.dev/guide/migrations.html

func NewMigrations added in v0.1.0

func NewMigrations() *Migrations

func (*Migrations) BackfillStableOrderedMigrationMarkers added in v0.15.0

func (m *Migrations) BackfillStableOrderedMigrationMarkers(
	ctx context.Context,
	db *bun.DB,
	legacySources []OrderedMigrationSource,
	opts ...OrderedMigrationRepairOption,
) error

func (*Migrations) LastPlan added in v0.13.1

func (m *Migrations) LastPlan() *MigrationPlan

func (*Migrations) Migrate

func (m *Migrations) Migrate(ctx context.Context, db *bun.DB) error

Migrate runs SQL file-based migrations discovered from registered filesystems.

func (*Migrations) MigrateSources added in v0.13.1

func (m *Migrations) MigrateSources(
	ctx context.Context,
	db *bun.DB,
	sourceNames ...string,
) error

MigrateSources runs migrations for a selected subset of registered sources.

func (*Migrations) Plan added in v0.13.1

func (m *Migrations) Plan(ctx context.Context, db *bun.DB) (*MigrationPlan, error)

func (*Migrations) PlanSources added in v0.13.1

func (m *Migrations) PlanSources(
	ctx context.Context,
	db *bun.DB,
	sourceNames ...string,
) (*MigrationPlan, error)

func (*Migrations) RegisterDialectMigrations added in v0.6.0

func (m *Migrations) RegisterDialectMigrations(root fs.FS, opts ...DialectMigrationOption) *Migrations

RegisterDialectMigrations registers migrations that may differ per dialect.

func (*Migrations) RegisterOrderedMigrationSources added in v0.12.0

func (m *Migrations) RegisterOrderedMigrationSources(sources ...OrderedMigrationSource) error

RegisterOrderedMigrationSources registers ordered SQL migration sources.

func (*Migrations) RegisterSQLMigrations

func (m *Migrations) RegisterSQLMigrations(migrations ...fs.FS) *Migrations

RegisterSQLMigrations adds SQL based migrations

func (*Migrations) Report

func (m *Migrations) Report() *migrate.MigrationGroup

Report returns the status of the last migration group. It returns nil if Execute has not been called or has failed.

func (*Migrations) Rollback

func (m *Migrations) Rollback(ctx context.Context, db *bun.DB, opts ...migrate.MigrationOption) error

Rollback will only roll back the most recent migration, which will be from the SQL set if it exists, otherwise from the Go set. TODO: more robust implementation which requires more complex logic

func (*Migrations) RollbackAll

func (m *Migrations) RollbackAll(ctx context.Context, db *bun.DB, opts ...migrate.MigrationOption) error

RollbackAll rollbacks every registered migration group.

func (*Migrations) SetLogger added in v0.1.0

func (m *Migrations) SetLogger(logger Logger)

func (*Migrations) ValidateDialects added in v0.6.0

func (m *Migrations) ValidateDialects(ctx context.Context, db *bun.DB) error

ValidateDialects executes configured dialect validation callbacks.

type OrderedMigrationIdentityMode added in v0.15.0

type OrderedMigrationIdentityMode int

OrderedMigrationIdentityMode controls how ordered migration source names are converted into Bun migration names.

const (
	// OrderedMigrationIdentityPositional preserves the legacy registration-position
	// identity format: ord_000001_000001.
	OrderedMigrationIdentityPositional OrderedMigrationIdentityMode = iota
	// OrderedMigrationIdentitySourceStable uses source keys and explicit source
	// order values for durable migration identities.
	OrderedMigrationIdentitySourceStable
)

func (OrderedMigrationIdentityMode) String added in v0.15.0

func (mode OrderedMigrationIdentityMode) String() string

type OrderedMigrationMetadata added in v0.12.0

type OrderedMigrationMetadata struct {
	SyntheticName    string
	SourceName       string
	SourceKey        string
	SourceOrder      int
	SourceDependsOn  []string
	ResolvedPosition int
	IdentityMode     OrderedMigrationIdentityMode
	OriginalVersion  string
	OriginalComment  string
	UpPath           string
	DownPath         string
}

OrderedMigrationMetadata keeps the mapping from synthetic migration names back to source and original files for debug/reporting.

type OrderedMigrationRepairOption added in v0.15.0

type OrderedMigrationRepairOption func(*OrderedMigrationRepairOptions)

func WithOrderedMigrationRepairCleanupLegacyMarkers added in v0.15.0

func WithOrderedMigrationRepairCleanupLegacyMarkers(enabled bool) OrderedMigrationRepairOption

type OrderedMigrationRepairOptions added in v0.15.0

type OrderedMigrationRepairOptions struct {
	CleanupLegacyMarkers bool
}

type OrderedMigrationSource added in v0.12.0

type OrderedMigrationSource struct {
	Name         string
	Root         fs.FS
	Options      []DialectMigrationOption
	IdentityMode OrderedMigrationIdentityMode
	SourceKey    string
	Order        int
	DependsOn    []string
}

OrderedMigrationSource defines one named migration source in an explicit order.

func NewStableOrderedMigrationSource added in v0.15.0

func NewStableOrderedMigrationSource(
	name string,
	root fs.FS,
	sourceKey string,
	order int,
	opts ...OrderedMigrationSourceOption,
) OrderedMigrationSource

NewStableOrderedMigrationSource builds a source-stable ordered migration source.

type OrderedMigrationSourceOption added in v0.15.0

type OrderedMigrationSourceOption func(*OrderedMigrationSource)

OrderedMigrationSourceOption configures an ordered migration source.

func WithOrderedMigrationDependencies added in v0.15.0

func WithOrderedMigrationDependencies(sourceKeys ...string) OrderedMigrationSourceOption

WithOrderedMigrationDependencies declares dependencies by source key.

func WithOrderedMigrationDialectOptions added in v0.15.0

func WithOrderedMigrationDialectOptions(opts ...DialectMigrationOption) OrderedMigrationSourceOption

WithOrderedMigrationDialectOptions attaches dialect options to an ordered source.

type OrderedSourceDriftError added in v0.15.0

type OrderedSourceDriftError struct {
	SourceKey string
	Field     string
	Expected  string
	Observed  string
}

func (*OrderedSourceDriftError) Error added in v0.15.0

func (e *OrderedSourceDriftError) Error() string

func (*OrderedSourceDriftError) Unwrap added in v0.15.0

func (e *OrderedSourceDriftError) Unwrap() error

type OrderedSourceGraphError added in v0.15.0

type OrderedSourceGraphError struct {
	Kind       error
	SourceName string
	SourceKey  string
	Dependency string
	Message    string
}

func (*OrderedSourceGraphError) Error added in v0.15.0

func (e *OrderedSourceGraphError) Error() string

func (*OrderedSourceGraphError) Unwrap added in v0.15.0

func (e *OrderedSourceGraphError) Unwrap() error

type OrderedSourceRepairError added in v0.15.0

type OrderedSourceRepairError struct {
	Kind        error
	LegacyName  string
	SourceName  string
	SourceKey   string
	Expected    string
	Observed    string
	Remediation string
	Message     string
}

func (*OrderedSourceRepairError) Error added in v0.15.0

func (e *OrderedSourceRepairError) Error() string

func (*OrderedSourceRepairError) Is added in v0.15.0

func (e *OrderedSourceRepairError) Is(target error) bool

func (*OrderedSourceRepairError) Unwrap added in v0.15.0

func (e *OrderedSourceRepairError) Unwrap() error

type QueryHookErrorHandler added in v0.10.0

type QueryHookErrorHandler func(db *bun.DB, hook bun.QueryHook, err error)

QueryHookErrorHandler handles invalid query hook registrations.

type QueryHookKeyer added in v0.10.0

type QueryHookKeyer interface {
	QueryHookKey() string
}

QueryHookKeyer allows hooks to provide a stable identity for deduplication.

Jump to

Keyboard shortcuts

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