gorm

package module
v0.0.0-...-fde3b76 Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2026 License: MIT Imports: 18 Imported by: 0

README

GORM Database Adapter for Hyperion

Production-ready GORM v2 adapter providing database connectivity and declarative transaction management for Hyperion framework.

Features

  • Multiple Database Support: PostgreSQL, MySQL, SQLite
  • Declarative Transactions: Automatic commit/rollback with panic recovery
  • Connection Pooling: Configurable connection pool settings
  • Transaction Propagation: Type-safe transaction context propagation
  • Nested Transactions: Automatic savepoint management
  • Health Checks: Built-in database health monitoring
  • Low Overhead: < 5% performance overhead vs native GORM

Installation

go get github.com/mapoio/hyperion/adapter/gorm

Quick Start

1. Configure Database

Create a config.yaml file:

database:
  driver: postgres
  host: localhost
  port: 5432
  username: myuser
  password: mypassword
  database: mydb
  sslmode: disable

  # Connection pool (optional)
  max_open_conns: 25
  max_idle_conns: 5
  conn_max_lifetime: 5m

  # GORM settings (optional)
  log_level: warn
  slow_threshold: 200ms
  prepare_stmt: true
2. Initialize Application
package main

import (
    "go.uber.org/fx"
    viperadapter "github.com/mapoio/hyperion/adapter/viper"
    gormadapter "github.com/mapoio/hyperion/adapter/gorm"
    "github.com/mapoio/hyperion"
)

func main() {
    app := fx.New(
        hyperion.CoreModule,  // Core infrastructure (required)
        viperadapter.Module,  // Config provider
        gormadapter.Module,   // Database provider
        fx.Invoke(run),
    )
    app.Run()
}

func run(db hyperion.Database, uow hyperion.UnitOfWork) {
    // Database is ready to use
}
3. Use Database
Basic Query
type UserRepository struct {
    db hyperion.Database
}

func (r *UserRepository) FindByEmail(ctx context.Context, email string) (*User, error) {
    executor := r.db.Executor()
    db := executor.Unwrap().(*gorm.DB)

    var user User
    if err := db.WithContext(ctx).Where("email = ?", email).First(&user).Error; err != nil {
        return nil, err
    }
    return &user, nil
}
Transaction
type UserService struct {
    uow      hyperion.UnitOfWork
    userRepo *UserRepository
}

func (s *UserService) RegisterUser(ctx hyperion.Context, email string) error {
    return s.uow.WithTransaction(ctx, func(txCtx hyperion.Context) error {
        // Create user
        user := &User{Email: email}
        if err := s.userRepo.Create(txCtx, user); err != nil {
            return err  // Automatic rollback
        }

        // Create profile
        profile := &Profile{UserID: user.ID}
        if err := s.profileRepo.Create(txCtx, profile); err != nil {
            return err  // Automatic rollback
        }

        return nil  // Automatic commit
    })
}

Configuration Reference

Basic Configuration
Key Type Default Description
driver string sqlite Database driver: postgres, mysql, sqlite
host string localhost Database host
port int 5432 Database port
username string - Database username
password string - Database password
database string - Database name (or file path for SQLite)
dsn string - Complete DSN string (overrides individual params)
Connection Pool
Key Type Default Description
max_open_conns int 25 Maximum open connections
max_idle_conns int 5 Maximum idle connections
conn_max_lifetime duration 5m Connection max lifetime
conn_max_idle_time duration 10m Connection max idle time
GORM Settings
Key Type Default Description
log_level string warn Log level: silent, error, warn, info
slow_threshold duration 200ms Slow query threshold
skip_default_transaction bool false Skip default transaction for single operations
prepare_stmt bool true Use prepared statements
Driver-Specific Options
PostgreSQL
database:
  driver: postgres
  sslmode: disable  # disable, require, verify-ca, verify-full
MySQL
database:
  driver: mysql
  charset: utf8mb4  # Character set

Advanced Usage

Transaction Options

Set isolation level and read-only mode:

opts := &hyperion.TransactionOptions{
    Isolation: hyperion.IsolationLevelSerializable,
    ReadOnly:  false,
}

err := uow.WithTransactionOptions(ctx, opts, func(txCtx hyperion.Context) error {
    // Transaction with custom options
    return orderRepo.Create(txCtx, order)
})
Nested Transactions

GORM automatically handles nested transactions using savepoints:

err := uow.WithTransaction(ctx, func(txCtx hyperion.Context) error {
    // Outer transaction
    userRepo.Create(txCtx, user)

    // Nested transaction (creates savepoint)
    return uow.WithTransaction(txCtx, func(nestedCtx hyperion.Context) error {
        // Inner transaction
        return profileRepo.Create(nestedCtx, profile)
    })
})
Health Checks

Check database connectivity:

if err := db.Health(ctx); err != nil {
    log.Fatal("database unhealthy", err)
}
Accessing Native GORM

Use Unwrap() to access GORM-specific features:

func (r *UserRepository) ComplexQuery(ctx hyperion.Context) ([]User, error) {
    db := ctx.DB().Unwrap().(*gorm.DB)

    var users []User
    err := db.WithContext(ctx).
        Preload("Profile").
        Where("age > ?", 18).
        Order("created_at DESC").
        Find(&users).Error

    return users, err
}

Supported Databases

PostgreSQL
database:
  driver: postgres
  host: localhost
  port: 5432
  username: user
  password: pass
  database: mydb
  sslmode: disable

Tested with PostgreSQL 14+

MySQL
database:
  driver: mysql
  host: localhost
  port: 3306
  username: user
  password: pass
  database: mydb
  charset: utf8mb4

Tested with MySQL 8.0+

SQLite
database:
  driver: sqlite
  database: /path/to/database.db

Or in-memory:

database:
  driver: sqlite
  database: ":memory:"

Best Practices

  1. Always use hyperion.Context for database operations
  2. Use WithTransaction for multi-step operations requiring atomicity
  3. Let transactions commit/rollback automatically - avoid manual commit/rollback
  4. Use Unwrap() when you need GORM-specific features
  5. Configure connection pool based on your workload
  6. Enable prepared statements for better performance (prepare_stmt: true)
  7. Set slow query threshold for monitoring (slow_threshold: 200ms)
  8. Use health checks in readiness probes

Performance Considerations

The adapter adds minimal overhead compared to native GORM:

  • Executor interface: ~1-2% overhead
  • Transaction management: ~2-3% overhead
  • Total overhead: < 5%
Optimization Tips
  1. Connection pooling: Adjust max_open_conns based on workload
  2. Prepared statements: Enabled by default, reduces parsing overhead
  3. Skip default transaction: Set skip_default_transaction: true for read-heavy workloads
  4. Batch operations: Use GORM's batch insert for bulk operations

Troubleshooting

Connection Refused
Error: failed to connect to database: dial tcp: connection refused

Solution: Verify database host, port, and ensure database is running.

Too Many Connections
Error: pq: sorry, too many clients already

Solution: Reduce max_open_conns or increase database max connections.

Transaction Deadlock
Error: deadlock detected

Solution: Use appropriate isolation level or implement retry logic.

Slow Queries

Solution:

  • Check log_level: info to see slow query logs
  • Adjust slow_threshold to identify slow queries
  • Add database indexes

Limitations

  1. GORM v2 only: Supports GORM v1.25.0+, no support for GORM v1
  2. Savepoints: Nested transactions require database support (not all SQLite configurations)
  3. Nested depth: Limited by database capabilities

Examples

See examples directory for complete working examples.

Contributing

Contributions are welcome! Please read CONTRIBUTING.md for guidelines.

License

See LICENSE for details.

Documentation

Overview

Package gorm provides a production-ready GORM v2 adapter for Hyperion framework.

This adapter implements hyperion.Database, hyperion.Executor, and hyperion.UnitOfWork interfaces, providing database connectivity and declarative transaction management.

Supported Databases

The adapter supports three database drivers:

  • PostgreSQL (via gorm.io/driver/postgres)
  • MySQL (via gorm.io/driver/mysql)
  • SQLite (via gorm.io/driver/sqlite)

Installation

Add the adapter to your application:

import (
    "go.uber.org/fx"
    gormadapter "github.com/mapoio/hyperion/adapter/gorm"
    "github.com/mapoio/hyperion"
)

app := fx.New(
    viper.Module,        // Provides Config
    gormadapter.Module,  // Provides Database and UnitOfWork
    fx.Invoke(func(db hyperion.Database) {
        // Database is ready to use
    }),
)

Configuration

Configure the database via YAML configuration file:

database:
  driver: postgres
  host: localhost
  port: 5432
  username: dbuser
  password: dbpass
  database: mydb
  sslmode: disable

  # Connection pool settings
  max_open_conns: 25
  max_idle_conns: 5
  conn_max_lifetime: 5m
  conn_max_idle_time: 10m

  # GORM settings
  log_level: warn
  slow_threshold: 200ms
  skip_default_transaction: false
  prepare_stmt: true

Alternatively, use a DSN string:

database:
  driver: postgres
  dsn: "postgres://user:pass@localhost:5432/dbname?sslmode=disable"

Basic Usage

## Querying Data

type UserRepository struct {
    db hyperion.Database
}

func (r *UserRepository) FindByEmail(ctx context.Context, email string) (*User, error) {
    executor := r.db.Executor()
    db := executor.Unwrap().(*gorm.DB)

    var user User
    if err := db.WithContext(ctx).Where("email = ?", email).First(&user).Error; err != nil {
        return nil, err
    }
    return &user, nil
}

## Using Executor Interface

func (r *UserRepository) CountUsers(ctx hyperion.Context) (int64, error) {
    var count int64
    sql := "SELECT COUNT(*) FROM users"

    err := ctx.DB().Query(ctx, &count, sql)
    return count, err
}

Transaction Management

The adapter provides declarative transaction management via UnitOfWork:

type UserService struct {
    uow      hyperion.UnitOfWork
    userRepo *UserRepository
}

func (s *UserService) RegisterUser(ctx hyperion.Context, email string) error {
    return s.uow.WithTransaction(ctx, func(txCtx hyperion.Context) error {
        // Create user
        user := &User{Email: email}
        if err := s.userRepo.Create(txCtx, user); err != nil {
            return err  // Automatic rollback
        }

        // Create profile
        profile := &Profile{UserID: user.ID}
        if err := s.profileRepo.Create(txCtx, profile); err != nil {
            return err  // Automatic rollback
        }

        return nil  // Automatic commit
    })
}

Transaction Options

Set isolation level and read-only mode:

opts := &hyperion.TransactionOptions{
    Isolation: hyperion.IsolationLevelSerializable,
    ReadOnly:  false,
}

err := uow.WithTransactionOptions(ctx, opts, func(txCtx hyperion.Context) error {
    // Transaction with custom options
    return orderRepo.Create(txCtx, order)
})

Transaction Propagation

Transactions automatically propagate through hyperion.Context:

func (r *UserRepository) Create(ctx hyperion.Context, user *User) error {
    // ctx.DB() returns transaction executor if inside WithTransaction
    // Otherwise, returns the default executor
    db := ctx.DB().Unwrap().(*gorm.DB)
    return db.Create(user).Error
}

Nested Transactions

GORM automatically handles nested transactions using savepoints:

err := uow.WithTransaction(ctx, func(txCtx hyperion.Context) error {
    // Outer transaction

    // Nested transaction (creates savepoint)
    return uow.WithTransaction(txCtx, func(nestedCtx hyperion.Context) error {
        // Inner transaction
        return userRepo.Create(nestedCtx, user)
    })
})

Panic Recovery

Transactions are automatically rolled back on panic:

err := uow.WithTransaction(ctx, func(txCtx hyperion.Context) error {
    userRepo.Create(txCtx, user)
    panic("something went wrong")  // Transaction rolled back
})

Health Checks

Check database connectivity:

if err := db.Health(ctx); err != nil {
    log.Fatal("database unhealthy", err)
}

Graceful Shutdown

The adapter automatically closes connections during fx shutdown:

app := fx.New(
    gormadapter.Module,
    // ... other modules
)

// Database connection closed automatically when app.Stop() is called

Performance Considerations

The adapter adds minimal overhead (<5%) compared to native GORM:

  • Executor interface: ~1-2% overhead
  • Transaction management: ~2-3% overhead
  • Total overhead: <5%

Best Practices

1. Always use hyperion.Context for database operations 2. Use WithTransaction for multi-step operations 3. Let transactions commit/rollback automatically 4. Use Unwrap() when you need GORM-specific features 5. Configure connection pool based on workload 6. Enable prepared statements for better performance 7. Set appropriate slow query threshold for monitoring

Limitations

1. Only supports GORM v2 (v1.25.0+) 2. Savepoints require database support (not all SQLite configurations) 3. Nested transaction depth limited by database

See Also

  • hyperion.Database: Core database interface
  • hyperion.Executor: Database operation executor
  • hyperion.UnitOfWork: Transaction management
  • hyperion.Context: Type-safe context with DB access
  • GORM v2 documentation: https://gorm.io/docs/

Index

Constants

View Source
const (
	// DriverPostgres represents the PostgreSQL driver.
	DriverPostgres = "postgres"
	// DriverMySQL represents the MySQL driver.
	DriverMySQL = "mysql"
	// DriverSQLite represents the SQLite driver.
	DriverSQLite = "sqlite"
)

Variables

View Source
var (
	// ErrNoDialectorProvided is returned when FromDialector is called with nil dialector.
	ErrNoDialectorProvided = errors.New("gorm: no dialector provided")

	// ErrNoDBProvided is returned when FromDB is called with nil *gorm.DB.
	ErrNoDBProvided = errors.New("gorm: no *gorm.DB provided")
)

Error variables for GORM adapter.

View Source
var AutoModule = hyperion.WrapAdapter(
	fx.Module("hyperion.adapter.gorm.auto",
		fx.Provide(
			fx.Annotate(
				NewAutoDatabase,
				fx.As(new(hyperion.Database)),
			),
		),
		fx.Provide(
			fx.Annotate(
				NewAutoUnitOfWork,
				fx.As(new(hyperion.UnitOfWork)),
			),
		),
		fx.Invoke(registerAutoShutdownHook),
	),
	"database",
)

AutoModule provides Level 1 (Zero-Config) API with capability declaration. It auto-configures GORM Database and UnitOfWork from hyperion.Config.

Usage:

hyperion.NewApp(
    viper.Module,        // Provides hyperion.Config
    gorm.AutoModule,     // Auto-configured from config.yaml - auto-detected capabilities
    handler.Module,
)

Configuration in config.yaml:

database:
  driver: postgres
  host: localhost
  port: 5432
  username: user
  password: pass
  database: mydb
  max_open_conns: 100
  max_idle_conns: 10
View Source
var Module = AutoModule

Module provides GORM-based Database and UnitOfWork implementations with capability declaration. This is the default module using Level 1 (Zero-Config) API.

Usage:

hyperion.NewApp(
    viper.Module,  // Provides Config
    gorm.Module,   // Provides Database and UnitOfWork - auto-detected capability
    myapp.Module,
).Run()

Configuration example (config.yaml):

database:
  driver: postgres
  host: localhost
  port: 5432
  username: dbuser
  password: dbpass
  database: mydb

For Level 2 (Configuration-Driven) API, use WithOptions() instead. For Level 3 (Custom Provider) API, use FromDialector() or FromDB() instead.

Functions

func FromDB

func FromDB(db *gorm.DB) fx.Option

FromDB provides Level 3 (Custom Provider) API from existing *gorm.DB. This is useful when you have an already-configured GORM instance.

IMPORTANT: When using this function, the caller is responsible for shutting down the database. Hyperion will NOT automatically close it.

Usage:

db, err := gorm.Open(postgres.Open("..."), &gorm.Config{})
if err != nil {
    panic(err)
}

hyperion.NewApp(
    gorm.FromDB(db),
    myapp.Module,
)

// You must close the database yourself
defer func() {
    sqlDB, _ := db.DB()
    sqlDB.Close()
}()

func FromDBWithShutdown

func FromDBWithShutdown(db *gorm.DB) fx.Option

FromDBWithShutdown provides Level 3 API from existing *gorm.DB with automatic shutdown. Unlike FromDB, this variant will automatically close the database on application stop.

Usage:

db, err := gorm.Open(postgres.Open("..."), &gorm.Config{})
if err != nil {
    panic(err)
}

hyperion.NewApp(
    gorm.FromDBWithShutdown(db),
    myapp.Module,
)

func FromDialector

func FromDialector(dialector gorm.Dialector, config *gorm.Config) fx.Option

FromDialector provides Level 3 (Custom Provider) API with automatic shutdown. It accepts a user-provided GORM Dialector and optional Config, and automatically shuts down the database when the application stops.

This allows applications to fully control GORM initialization and version, while still using Hyperion's Database and UnitOfWork abstractions.

Usage:

import (
    "gorm.io/driver/postgres"
    "gorm.io/gorm"
)

dialector := postgres.Open("postgres://user:pass@localhost/mydb")
config := &gorm.Config{
    Logger: myCustomLogger,
    PrepareStmt: true,
}

hyperion.NewApp(
    gorm.FromDialector(dialector, config),
    myapp.Module,
)

func NewAutoDatabase

func NewAutoDatabase(cfg hyperion.Config) (hyperion.Database, error)

NewAutoDatabase creates a Database from auto-configuration. It reads config from hyperion.Config and initializes GORM automatically.

func NewAutoUnitOfWork

func NewAutoUnitOfWork(db hyperion.Database) hyperion.UnitOfWork

NewAutoUnitOfWork creates a UnitOfWork from auto-configured Database.

func NewDatabaseFromDialector

func NewDatabaseFromDialector(dialector gorm.Dialector, config *gorm.Config) (hyperion.Database, error)

NewDatabaseFromDialector creates a Database from a GORM Dialector and Config.

func NewDatabaseFromOptions

func NewDatabaseFromOptions(opts Options) (hyperion.Database, error)

NewDatabaseFromOptions creates a Database from Options.

func NewGormDatabase

func NewGormDatabase(cfg hyperion.Config) (hyperion.Database, error)

NewGormDatabase creates a new GORM database instance from configuration. It supports PostgreSQL, MySQL, and SQLite drivers.

func NewGormProvider deprecated

func NewGormProvider(cfg hyperion.Config) (hyperion.Database, error)

Deprecated: Use AutoModule, WithOptions(), or FromDialector() instead. This function is kept for backward compatibility.

func NewGormUnitOfWork

func NewGormUnitOfWork(db hyperion.Database) hyperion.UnitOfWork

NewGormUnitOfWork creates a new UnitOfWork from a Database instance.

func NewGormUnitOfWorkProvider deprecated

func NewGormUnitOfWorkProvider(db hyperion.Database) hyperion.UnitOfWork

Deprecated: Use AutoModule, WithOptions(), or FromDialector() instead. This function is kept for backward compatibility.

func NewUnitOfWorkFromCustom

func NewUnitOfWorkFromCustom(db hyperion.Database) hyperion.UnitOfWork

NewUnitOfWorkFromCustom creates a UnitOfWork from a custom Database.

func NewUnitOfWorkFromOptions

func NewUnitOfWorkFromOptions(db hyperion.Database) hyperion.UnitOfWork

NewUnitOfWorkFromOptions creates a UnitOfWork from options-based Database.

func WithOptions

func WithOptions(opts Options) fx.Option

WithOptions provides Level 2 (Configuration-Driven) API. It creates Database and UnitOfWork from programmatic Options.

Usage:

opts, err := gorm.NewOptionsBuilder().
    ForPostgres("localhost", 5432, "user", "pass", "mydb").
    WithMaxOpenConns(100).
    WithMaxIdleConns(10).
    Build()
if err != nil {
    panic(err)
}

hyperion.NewApp(
    gorm.WithOptions(opts),
    myapp.Module,
)

Types

type Config

type Config struct {
	// String fields (16 bytes on 64-bit: 8-byte pointer + 8-byte length)
	Driver   string `json:"driver" yaml:"driver" validate:"required,oneof=postgres mysql sqlite"` // Driver specifies the database driver (postgres, mysql, sqlite)
	DSN      string `json:"dsn" yaml:"dsn"`                                                       // DSN allows providing a complete connection string
	Host     string `json:"host" yaml:"host" validate:"omitempty,hostname|ip"`                    // Connection host
	Username string `json:"username" yaml:"username"`                                             // Connection username
	Password string `json:"password" yaml:"password"`                                             // Connection password
	Database string `json:"database" yaml:"database"`                                             // Database name (required for non-SQLite unless DSN provided)
	SSLMode  string `json:"sslmode" yaml:"sslmode" validate:"omitempty,oneof=disable require verify-ca verify-full"`
	Charset  string `json:"charset" yaml:"charset"`     // MySQL charset
	LogLevel string `json:"log_level" yaml:"log_level"` // Log level: silent, error, warn, info

	// Duration fields (8 bytes each)
	ConnMaxLifetime time.Duration `json:"conn_max_lifetime" yaml:"conn_max_lifetime" validate:"omitempty,min=0"`
	ConnMaxIdleTime time.Duration `json:"conn_max_idle_time" yaml:"conn_max_idle_time" validate:"omitempty,min=0"`
	SlowThreshold   time.Duration `json:"slow_threshold" yaml:"slow_threshold" validate:"omitempty,min=0"`

	// Int fields (8 bytes on 64-bit)
	MaxOpenConns int `json:"max_open_conns" yaml:"max_open_conns" validate:"omitempty,min=0"`
	MaxIdleConns int `json:"max_idle_conns" yaml:"max_idle_conns" validate:"omitempty,min=0"`
	Port         int `json:"port" yaml:"port" validate:"omitempty,min=1,max=65535"`

	// Bool fields (1 byte each) - use pointers to distinguish unset from false
	// Using pointers allows us to differentiate between "not provided" (nil) and "explicitly set to false"
	SkipDefaultTransaction *bool `json:"skip_default_transaction" yaml:"skip_default_transaction"`
	PrepareStmt            *bool `json:"prepare_stmt" yaml:"prepare_stmt"`
	AutoMigrate            *bool `json:"auto_migrate" yaml:"auto_migrate"`
}

Config represents the database configuration. Fields are ordered for optimal memory alignment (larger types first).

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a configuration with sensible defaults.

func (*Config) Open

func (c *Config) Open() (*gorm.DB, error)

Open opens a database connection with the configured settings.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks if the configuration is valid using validator. Validation rules are defined in struct tags (validate:"..."). Additional custom validation is performed after struct validation.

type Options

type Options struct {
	// Database connection
	Driver   string
	DSN      string // Complete DSN (overrides individual connection fields)
	Host     string
	Port     *int // Use pointer to allow explicit 0 (use default port)
	Username string
	Password string
	Database string
	SSLMode  string // postgres: disable, require, verify-ca, verify-full
	Charset  string // mysql: utf8mb4

	// Connection pool configuration
	// Use pointers to allow explicit 0 values (unlimited connections, no timeout, etc.)
	MaxOpenConns    *int           // 0 = unlimited connections
	MaxIdleConns    *int           // 0 = unlimited idle connections
	ConnMaxLifetime *time.Duration // 0 = connections never close due to age
	ConnMaxIdleTime *time.Duration // 0 = idle connections never close

	// GORM configuration
	// Use pointers to distinguish between "not set" (nil) and "explicitly false"
	SkipDefaultTransaction *bool
	PrepareStmt            *bool
	DisableNestedTxn       *bool // Disable nested transaction (SavePoint/RollbackTo)
	AllowGlobalUpdate      *bool // Allow global update without WHERE clause
	QueryFields            *bool // Select all fields by "SELECT *"
	CreateBatchSize        *int  // Default batch size for batch insert (0 = disable batching)

	// Logging configuration
	LogLevel      string         // silent, error, warn, info
	SlowThreshold *time.Duration // Slow SQL threshold (0 = disable slow query logging)

	// Auto migration (for development only)
	AutoMigrate *bool
	Models      []any // Models to auto-migrate

	// Advanced: Custom dialector and plugins (Level 2+)
	// These fields allow users to provide custom GORM components
	// while still using the Options API for other configurations
	CustomDialector gorm.Dialector `json:"-"` // Custom dialector (overrides Driver/DSN)
	Plugins         []gorm.Plugin  `json:"-"` // GORM plugins to register
}

Options provides programmatic configuration for the GORM adapter. This is used for Level 2 (Configuration-Driven) API with Builder pattern.

Example usage:

opts := gorm.NewOptionsBuilder().
    WithDriver("postgres").
    WithHost("localhost").
    WithPort(5432).
    WithUsername("user").
    WithPassword("pass").
    WithDatabase("mydb").
    WithMaxOpenConns(100).
    Build()

hyperion.NewApp(
    gorm.WithOptions(opts),
    myapp.Module,
)

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns sensible default options for local development.

func (Options) Defaults

func (o Options) Defaults() hyperion.AdapterOptions

Defaults returns the default options for GORM adapter.

func (Options) Merge

Merge combines user-provided options with default options. User options take precedence over defaults.

func (Options) Validate

func (o Options) Validate() error

Validate checks if the options are valid.

type OptionsBuilder

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

OptionsBuilder provides a fluent API for building GORM Options. It implements the builder pattern for better ergonomics.

Example usage:

opts, err := gorm.NewOptionsBuilder().
    WithDriver("postgres").
    WithHost("localhost").
    WithPort(5432).
    WithUsername("user").
    WithPassword("pass").
    WithDatabase("mydb").
    WithMaxOpenConns(100).
    WithMaxIdleConns(10).
    Build()

func NewOptionsBuilder

func NewOptionsBuilder() *OptionsBuilder

NewOptionsBuilder creates a new OptionsBuilder with default options.

func (*OptionsBuilder) Build

func (b *OptionsBuilder) Build() (Options, error)

Build finalizes the builder and returns the Options instance. It validates the options before returning.

func (*OptionsBuilder) ForDevelopment

func (b *OptionsBuilder) ForDevelopment() *OptionsBuilder

ForDevelopment applies recommended settings for development environment.

func (*OptionsBuilder) ForMySQL

func (b *OptionsBuilder) ForMySQL(host string, port int, user, password, dbname string) *OptionsBuilder

ForMySQL configures the builder for MySQL with the given parameters.

func (*OptionsBuilder) ForPostgres

func (b *OptionsBuilder) ForPostgres(host string, port int, user, password, dbname string) *OptionsBuilder

ForPostgres configures the builder for PostgreSQL with the given parameters.

func (*OptionsBuilder) ForProduction

func (b *OptionsBuilder) ForProduction() *OptionsBuilder

ForProduction applies recommended settings for production environment.

func (*OptionsBuilder) ForSQLite

func (b *OptionsBuilder) ForSQLite(filepath string) *OptionsBuilder

ForSQLite configures the builder for SQLite with the given file path.

func (*OptionsBuilder) WithAllowGlobalUpdate

func (b *OptionsBuilder) WithAllowGlobalUpdate(allow bool) *OptionsBuilder

WithAllowGlobalUpdate allows global updates without WHERE clause. CAUTION: This is dangerous in production. Only use for development/testing.

func (*OptionsBuilder) WithAutoMigrate

func (b *OptionsBuilder) WithAutoMigrate(enable bool) *OptionsBuilder

WithAutoMigrate enables automatic schema migration on startup. CAUTION: Only use this in development. Use proper migrations in production.

func (*OptionsBuilder) WithCharset

func (b *OptionsBuilder) WithCharset(charset string) *OptionsBuilder

WithCharset sets the charset for MySQL. Default: utf8mb4.

func (*OptionsBuilder) WithConnMaxIdleTime

func (b *OptionsBuilder) WithConnMaxIdleTime(d time.Duration) *OptionsBuilder

WithConnMaxIdleTime sets the maximum idle time of a connection.

func (*OptionsBuilder) WithConnMaxLifetime

func (b *OptionsBuilder) WithConnMaxLifetime(d time.Duration) *OptionsBuilder

WithConnMaxLifetime sets the maximum lifetime of a connection.

func (*OptionsBuilder) WithCreateBatchSize

func (b *OptionsBuilder) WithCreateBatchSize(size int) *OptionsBuilder

WithCreateBatchSize sets the default batch size for batch insert operations.

func (*OptionsBuilder) WithCustomDialector

func (b *OptionsBuilder) WithCustomDialector(dialector gorm.Dialector) *OptionsBuilder

WithCustomDialector sets a custom GORM Dialector. This allows using custom database drivers or custom connection logic. When set, this overrides the Driver and DSN settings.

func (*OptionsBuilder) WithDSN

func (b *OptionsBuilder) WithDSN(dsn string) *OptionsBuilder

WithDSN sets the complete DSN connection string. This overrides individual connection fields (Host, Port, Username, etc.).

func (*OptionsBuilder) WithDatabase

func (b *OptionsBuilder) WithDatabase(database string) *OptionsBuilder

WithDatabase sets the database name.

func (*OptionsBuilder) WithDisableNestedTransaction

func (b *OptionsBuilder) WithDisableNestedTransaction(disable bool) *OptionsBuilder

WithDisableNestedTransaction disables nested transactions (SavePoint/RollbackTo).

func (*OptionsBuilder) WithDriver

func (b *OptionsBuilder) WithDriver(driver string) *OptionsBuilder

WithDriver sets the database driver (postgres, mysql, sqlite).

func (*OptionsBuilder) WithHost

func (b *OptionsBuilder) WithHost(host string) *OptionsBuilder

WithHost sets the database host.

func (*OptionsBuilder) WithLogLevel

func (b *OptionsBuilder) WithLogLevel(level string) *OptionsBuilder

WithLogLevel sets the GORM log level. Valid values: silent, error, warn, info.

func (*OptionsBuilder) WithMaxIdleConns

func (b *OptionsBuilder) WithMaxIdleConns(n int) *OptionsBuilder

WithMaxIdleConns sets the maximum number of idle connections.

func (*OptionsBuilder) WithMaxOpenConns

func (b *OptionsBuilder) WithMaxOpenConns(n int) *OptionsBuilder

WithMaxOpenConns sets the maximum number of open connections.

func (*OptionsBuilder) WithModels

func (b *OptionsBuilder) WithModels(models ...any) *OptionsBuilder

WithModels sets the models to auto-migrate. Only used when AutoMigrate is enabled.

func (*OptionsBuilder) WithPassword

func (b *OptionsBuilder) WithPassword(password string) *OptionsBuilder

WithPassword sets the database password.

func (*OptionsBuilder) WithPlugins

func (b *OptionsBuilder) WithPlugins(plugins ...gorm.Plugin) *OptionsBuilder

WithPlugins adds GORM plugins to be registered on initialization. Plugins can extend GORM functionality (e.g., soft delete, optimistic locking).

func (*OptionsBuilder) WithPort

func (b *OptionsBuilder) WithPort(port int) *OptionsBuilder

WithPort sets the database port.

func (*OptionsBuilder) WithPrepareStmt

func (b *OptionsBuilder) WithPrepareStmt(enable bool) *OptionsBuilder

WithPrepareStmt enables/disables prepared statements. Prepared statements can improve performance but may not work with all drivers.

func (*OptionsBuilder) WithQueryFields

func (b *OptionsBuilder) WithQueryFields(enable bool) *OptionsBuilder

WithQueryFields enables selecting all fields by "SELECT *".

func (*OptionsBuilder) WithSSLMode

func (b *OptionsBuilder) WithSSLMode(sslMode string) *OptionsBuilder

WithSSLMode sets the SSL mode for PostgreSQL. Valid values: disable, require, verify-ca, verify-full.

func (*OptionsBuilder) WithSkipDefaultTransaction

func (b *OptionsBuilder) WithSkipDefaultTransaction(skip bool) *OptionsBuilder

WithSkipDefaultTransaction enables/disables default transactions for GORM. When enabled, GORM will not start a transaction for single create/update/delete operations.

func (*OptionsBuilder) WithSlowThreshold

func (b *OptionsBuilder) WithSlowThreshold(threshold time.Duration) *OptionsBuilder

WithSlowThreshold sets the slow query threshold. Queries slower than this duration will be logged as slow.

func (*OptionsBuilder) WithUsername

func (b *OptionsBuilder) WithUsername(username string) *OptionsBuilder

WithUsername sets the database username.

Jump to

Keyboard shortcuts

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