persistence

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Dec 26, 2024 License: MIT Imports: 20 Imported by: 0

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
type Config struct {
    Debug         bool
    Driver        string
    Server        string
    Database      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) GetDatabase() string {
    return c.Database
}

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

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

config := &Config{
    Driver: "postgres",
    Server: "localhost:5432",
    Database: "myapp",
    PingTimeout: 5 * time.Second,
}

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()
Migrations
// SQL migrations
client.RegisterSQLMigrations(migrations.FS)

// Programmatic migrations
client.RegisterFuncMigrations(persistence.MigratorFunc{
    Up: func(ctx context.Context, db *bun.DB) error {
        _, err := db.NewCreateTable().Model((*User)(nil)).Exec(ctx)
        return err
    },
    Down: func(ctx context.Context, db *bun.DB) error {
        _, err := db.NewDropTable().Model((*User)(nil)).Exec(ctx)
        return err
    },
})

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

// Load fixtures
if err := client.Seed(context.Background()); err != nil {
    log.Fatal(err)
}
Model Registration
type User struct {
    ID   int64  `bun:"id,pk,autoincrement"`
    Name string
}

persistence.RegisterModel((*User)(nil))

Configuration Options

  • WithTruncateTables(): Truncate tables before loading fixtures
  • WithDropTables(): Drop tables before loading fixtures
  • WithFS(dir fs.FS): Add filesystem for fixtures/migrations
  • WithTemplateFuncs(funcMap TplMap): Add template functions for fixtures
  • WithFileFilter(fn func(path, name string) bool): Custom file filtering

Features

  • Database connection management
  • SQL and programmatic migrations
  • Fixtures support
  • OpenTelemetry integration
  • Debug mode with query logging

License

MIT

Copyright (c) 2024 goliatone

Documentation

Index

Constants

View Source
const DefaultDriver = "postgres"

DefaultDriver is the Postgres driver

View Source
const Name = "persistence"

Name is the string identifier of the module

Variables

View Source
var Priority int

Priority is the module's loading priority

Functions

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{})

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) (*Client, error)

New creates a new client

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) DB

func (c Client) DB() bun.IDB

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) Log added in v0.0.2

func (c Client) Log(format string, a ...any)

func (Client) Migrate

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

Migrate will migrate db

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) Priority

func (c *Client) Priority() int

Priority will return the module priority

func (Client) RegisterFixtures

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

RegisterFixtures adds file based fixtures

func (Client) RegisterFuncMigrations

func (c Client) RegisterFuncMigrations(migrations ...MigratorFunc) *Migrations

RegisterFuncMigrations adds SQL based migrations

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, db *bun.DB, 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(l func(format string, a ...any))

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

type Config

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

Config has values for configurable properties

type DriverConfig

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

DriverConfig provides a way to abstract the connection process

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 a file

func (*Fixtures) LoadFile

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

LoadFile will load a file

type Migrations

type Migrations struct {
	Files []fs.FS
	Func  []MigratorFunc
	// contains filtered or unexported fields
}

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

func (*Migrations) Migrate

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

Migrate will execute every registered migration. Method can be called multiple times, the ORM knows how to manage executed migrations.

func (*Migrations) RegisterFuncMigrations

func (m *Migrations) RegisterFuncMigrations(migrations ...MigratorFunc) *Migrations

RegisterFuncMigrations adds SQL based migrations

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 migrations. 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 previously executed migrations. It will rollback a group at a time. See https://bun.uptrace.dev/guide/migrations.html#migration-groups-and-rollbacks.

func (*Migrations) RollbackAll

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

RollbackAll rollbacks every registered migration group.

type MigratorFunc

type MigratorFunc struct {
	Up   migrate.MigrationFunc
	Down migrate.MigrationFunc
}

MigratorFunc holds a migration

Jump to

Keyboard shortcuts

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