gorm

package
v1.19.2 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

Package gorm provides a comprehensive wrapper around GORM ORM with connection management, monitoring, logging integration, and configuration validation.

Features:

  • Multiple database support (MySQL, PostgreSQL, SQLite, SQL Server)
  • Connection pooling with configurable settings
  • Logger integration with golib/logger
  • Context management for cancellation and deadlines
  • Health monitoring and connection status
  • Configuration validation with go-playground/validator
  • Thread-safe concurrent access

Example usage:

import libgorm "github.com/nabbar/golib/database/gorm"

cfg := &libgorm.Config{
    Driver: libgorm.DriverMysql,
    Name:   "mydb",
    DSN:    "user:pass@tcp(localhost:3306)/dbname?charset=utf8mb4",
    EnableConnectionPool: true,
    PoolMaxIdleConns:     10,
    PoolMaxOpenConns:     100,
}

db, err := libgorm.New(cfg)
if err != nil {
    log.Fatal(err)
}
defer db.Close()

gormDB := db.GetDB()
gormDB.Create(&User{Name: "Alice"})

Index

Constants

View Source
const (
	DriverNone       = ""
	DriverMysql      = "mysql"
	DriverPostgreSQL = "psql"
	DriverSQLite     = "sqlite"
	DriverSQLServer  = "sqlserver"
)
View Source
const (
	ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgDatabaseGorm
	ErrorDatabaseOpen
	ErrorDatabaseOpenPool
	ErrorValidatorError
	ErrorDatabaseNotInitialized
	ErrorDatabaseCannotSQLDB
	ErrorDatabasePing
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// Driver is the driver to use for the DSN. It must be one of mysql, psql, sqlite, sqlserver, clickhouse.
	Driver Driver `json:"driver" yaml:"driver" toml:"driver" mapstructure:"driver"`

	// Name is a string to identify the instance into status.
	Name string `json:"name" yaml:"name" toml:"name" mapstructure:"name"`

	// DSN is the string options to connect to database following database engine. See https://gorm.io/docs/connecting_to_the_database.html for more information.
	DSN string `json:"dsn" yaml:"dsn" toml:"dsn" mapstructure:"dsn"`

	// SkipDefaultTransaction disable the default transaction for single create, update, delete operations.
	// This single transactions by default is to ensure database data integrity.
	SkipDefaultTransaction bool `` /* 135-byte string literal not displayed */

	// FullSaveAssociations full save associations.
	FullSaveAssociations bool `` /* 127-byte string literal not displayed */

	// DryRun generate sql without execute.
	DryRun bool `json:"dry-run" yaml:"dry-run" toml:"dry-run" mapstructure:"dry-run"`

	// PrepareStmt executes the given query in cached statement.
	PrepareStmt bool `json:"prepare-stmt" yaml:"prepare-stmt" toml:"prepare-stmt" mapstructure:"prepare-stmt"`

	// DisableAutomaticPing is used to disable the automatic ping to the database server.
	DisableAutomaticPing bool `` /* 127-byte string literal not displayed */

	// DisableForeignKeyConstraintWhenMigrating is used to disable the foreign key constraint when migrating the database.
	DisableForeignKeyConstraintWhenMigrating bool `` /* 219-byte string literal not displayed */

	// DisableNestedTransaction disable nested transaction.
	DisableNestedTransaction bool `` /* 143-byte string literal not displayed */

	// AllowGlobalUpdate allow global update.
	AllowGlobalUpdate bool `json:"allow-global-update" yaml:"allow-global-update" toml:"allow-global-update" mapstructure:"allow-global-update"`

	// QueryFields executes the SQL query with all fields of the table.
	QueryFields bool `json:"query-fields" yaml:"query-fields" toml:"query-fields" mapstructure:"query-fields"`

	// CreateBatchSize default create batch size.
	CreateBatchSize int `json:"create-batch-size" yaml:"create-batch-size" toml:"create-batch-size" mapstructure:"create-batch-size"`

	// EnableConnectionPool is used to create a connection pool.
	EnableConnectionPool bool `` /* 127-byte string literal not displayed */

	// PoolMaxIdleConns sets the maximum number of connections idle in the connection pool.
	PoolMaxIdleConns int `json:"pool-max-idle-conns" yaml:"pool-max-idle-conns" toml:"pool-max-idle-conns" mapstructure:"pool-max-idle-conns"`

	// PoolMaxOpenConns sets the maximum number of connections open in the connection pool.
	PoolMaxOpenConns int `json:"pool-max-open-conns" yaml:"pool-max-open-conns" toml:"pool-max-open-conns" mapstructure:"pool-max-open-conns"`

	// PoolConnMaxLifetime sets the maximum lifetime of connections in the connection pool.
	PoolConnMaxLifetime time.Duration `` /* 127-byte string literal not displayed */

	// Disabled allow to disable a database connection without clean his configuration.
	Disabled bool `mapstructure:"disabled" json:"disabled" yaml:"disabled" toml:"disabled"`

	// Monitor defined the monitoring configuration
	Monitor moncfg.Config `mapstructure:"monitor" json:"monitor" yaml:"monitor" toml:"monitor"`
	// contains filtered or unexported fields
}

func (*Config) Config

func (c *Config) Config() *gormdb.Config

func (*Config) New

func (c *Config) New(cfg *gormdb.Config) (*gormdb.DB, liberr.Error)

func (*Config) RegisterContext

func (c *Config) RegisterContext(fct context.Context)

func (*Config) RegisterGORMLogger

func (c *Config) RegisterGORMLogger(fct FuncGormLog)

func (*Config) RegisterLogger

func (c *Config) RegisterLogger(fct func() liblog.Logger, ignoreRecordNotFoundError bool, slowThreshold time.Duration)

func (*Config) Validate

func (c *Config) Validate() liberr.Error

Validate allow checking if the config' struct is valid with the awaiting model

type Database

type Database interface {
	// GetDB returns the underlying GORM DB instance.
	// Use this to access all GORM functionality directly.
	GetDB() *gormdb.DB

	// SetDb replaces the underlying GORM DB instance.
	// Use with caution as this affects all concurrent operations.
	SetDb(db *gormdb.DB)

	// Close closes the database connection and releases resources.
	// Safe to call multiple times.
	Close()

	// WaitNotify blocks until the context is cancelled or database closes.
	// Used for graceful shutdown and connection lifecycle management.
	WaitNotify(ctx context.Context, cancel context.CancelFunc)

	// CheckConn verifies the database connection is alive.
	// Returns an error if the connection is not functional.
	CheckConn() liberr.Error

	// Config returns the GORM configuration used by this database.
	Config() *gormdb.Config

	// RegisterContext registers a context function for the database.
	// The context is used for cancellation and deadlines.
	RegisterContext(fct context.Context)

	// RegisterLogger registers a golib logger for database operations.
	// Parameters:
	//   - fct: Function returning a logger instance
	//   - ignoreRecordNotFoundError: If true, record not found errors are not logged
	//   - slowThreshold: Threshold for slow query logging
	RegisterLogger(fct func() liblog.Logger, ignoreRecordNotFoundError bool, slowThreshold time.Duration)

	// RegisterGORMLogger registers a GORM-specific logger.
	// Use this for custom GORM logging behavior.
	RegisterGORMLogger(fct func() gorlog.Interface)

	// Monitor creates a monitor for health checking and status reporting.
	// Returns a Monitor instance that can be registered with a monitor pool.
	Monitor(vrs libver.Version) (montps.Monitor, error)
}

Database is the main interface for database operations. It wraps a GORM DB instance with additional features like monitoring, logging, and connection management.

func New

func New(cfg *Config) (Database, liberr.Error)

New creates a new Database instance with the given configuration. The configuration is validated before creating the database.

Parameters:

  • cfg: Database configuration including driver, DSN, and pool settings

Returns:

  • Database: Configured database instance
  • liberr.Error: Error if configuration is invalid or connection fails

Example:

cfg := &Config{
    Driver: DriverPostgres,
    DSN:    "host=localhost user=postgres dbname=mydb sslmode=disable",
}
db, err := New(cfg)
if err != nil {
    log.Fatal(err)
}
defer db.Close()

type Driver

type Driver string

func DriverFromString

func DriverFromString(drv string) Driver

func (Driver) Dialector

func (d Driver) Dialector(dsn string) gormdb.Dialector

func (Driver) String

func (d Driver) String() string

type FuncGormLog

type FuncGormLog func() gorlog.Interface

FuncGormLog is a function type that returns a GORM logger interface. Used for providing custom GORM loggers to the database instance.

Jump to

Keyboard shortcuts

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