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
- Variables
- func FromDB(db *gorm.DB) fx.Option
- func FromDBWithShutdown(db *gorm.DB) fx.Option
- func FromDialector(dialector gorm.Dialector, config *gorm.Config) fx.Option
- func NewAutoDatabase(cfg hyperion.Config) (hyperion.Database, error)
- func NewAutoUnitOfWork(db hyperion.Database) hyperion.UnitOfWork
- func NewDatabaseFromDialector(dialector gorm.Dialector, config *gorm.Config) (hyperion.Database, error)
- func NewDatabaseFromOptions(opts Options) (hyperion.Database, error)
- func NewGormDatabase(cfg hyperion.Config) (hyperion.Database, error)
- func NewGormProvider(cfg hyperion.Config) (hyperion.Database, error)deprecated
- func NewGormUnitOfWork(db hyperion.Database) hyperion.UnitOfWork
- func NewGormUnitOfWorkProvider(db hyperion.Database) hyperion.UnitOfWorkdeprecated
- func NewUnitOfWorkFromCustom(db hyperion.Database) hyperion.UnitOfWork
- func NewUnitOfWorkFromOptions(db hyperion.Database) hyperion.UnitOfWork
- func WithOptions(opts Options) fx.Option
- type Config
- type Options
- type OptionsBuilder
- func (b *OptionsBuilder) Build() (Options, error)
- func (b *OptionsBuilder) ForDevelopment() *OptionsBuilder
- func (b *OptionsBuilder) ForMySQL(host string, port int, user, password, dbname string) *OptionsBuilder
- func (b *OptionsBuilder) ForPostgres(host string, port int, user, password, dbname string) *OptionsBuilder
- func (b *OptionsBuilder) ForProduction() *OptionsBuilder
- func (b *OptionsBuilder) ForSQLite(filepath string) *OptionsBuilder
- func (b *OptionsBuilder) WithAllowGlobalUpdate(allow bool) *OptionsBuilder
- func (b *OptionsBuilder) WithAutoMigrate(enable bool) *OptionsBuilder
- func (b *OptionsBuilder) WithCharset(charset string) *OptionsBuilder
- func (b *OptionsBuilder) WithConnMaxIdleTime(d time.Duration) *OptionsBuilder
- func (b *OptionsBuilder) WithConnMaxLifetime(d time.Duration) *OptionsBuilder
- func (b *OptionsBuilder) WithCreateBatchSize(size int) *OptionsBuilder
- func (b *OptionsBuilder) WithCustomDialector(dialector gorm.Dialector) *OptionsBuilder
- func (b *OptionsBuilder) WithDSN(dsn string) *OptionsBuilder
- func (b *OptionsBuilder) WithDatabase(database string) *OptionsBuilder
- func (b *OptionsBuilder) WithDisableNestedTransaction(disable bool) *OptionsBuilder
- func (b *OptionsBuilder) WithDriver(driver string) *OptionsBuilder
- func (b *OptionsBuilder) WithHost(host string) *OptionsBuilder
- func (b *OptionsBuilder) WithLogLevel(level string) *OptionsBuilder
- func (b *OptionsBuilder) WithMaxIdleConns(n int) *OptionsBuilder
- func (b *OptionsBuilder) WithMaxOpenConns(n int) *OptionsBuilder
- func (b *OptionsBuilder) WithModels(models ...any) *OptionsBuilder
- func (b *OptionsBuilder) WithPassword(password string) *OptionsBuilder
- func (b *OptionsBuilder) WithPlugins(plugins ...gorm.Plugin) *OptionsBuilder
- func (b *OptionsBuilder) WithPort(port int) *OptionsBuilder
- func (b *OptionsBuilder) WithPrepareStmt(enable bool) *OptionsBuilder
- func (b *OptionsBuilder) WithQueryFields(enable bool) *OptionsBuilder
- func (b *OptionsBuilder) WithSSLMode(sslMode string) *OptionsBuilder
- func (b *OptionsBuilder) WithSkipDefaultTransaction(skip bool) *OptionsBuilder
- func (b *OptionsBuilder) WithSlowThreshold(threshold time.Duration) *OptionsBuilder
- func (b *OptionsBuilder) WithUsername(username string) *OptionsBuilder
Constants ¶
const ( // DriverPostgres represents the PostgreSQL driver. DriverPostgres = "postgres" // DriverMySQL represents the MySQL driver. DriverMySQL = "mysql" // DriverSQLite represents the SQLite driver. DriverSQLite = "sqlite" )
Variables ¶
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.
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
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
NewDatabaseFromOptions creates a Database from Options.
func NewGormDatabase ¶
NewGormDatabase creates a new GORM database instance from configuration. It supports PostgreSQL, MySQL, and SQLite drivers.
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 ¶
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.
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 ¶
func (o Options) Merge(defaults hyperion.AdapterOptions) hyperion.AdapterOptions
Merge combines user-provided options with default options. User options take precedence over defaults.
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.