gorm

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 29, 2026 License: MIT Imports: 12 Imported by: 0

README

database/gorm

The gorm package provides a GORM database connection factory. It is intended for services that need a consistent way to open a database, configure connection pooling, set log levels, and retry connections on startup without writing boilerplate for each project.

Import

import "github.com/raykavin/gobox/database/gorm"

What it provides

  • New() for opening a GORM connection with pooling, logging, and retry
  • DefaultGormConfig() for a sensible starting configuration
  • support for postgres, mysql, mariadb, sqlite, sqlserver, and mssql
  • ParseLoggerLevel() for mapping level strings to GORM log levels
  • UpdateConnectionPool() for adjusting pool settings on an existing connection
  • GetConnectionStats() for reading pool metrics at runtime

Main types

  • GormConfig: connection and pool settings
  • GormConfig.GormConfig: optional override for the underlying *gorm.Config

Example

package main

import (
    "log"
    "os"
    "time"

    gormkit "github.com/raykavin/gobox/database/gorm"
)

func main() {
    cfg := gormkit.DefaultGormConfig()
    cfg.DSN       = os.Getenv("DATABASE_URL")
    cfg.Dialector = "postgres"
    cfg.LogLevel  = "warn"

    db, err := gormkit.New(cfg)
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        sqlDB, _ := db.DB()
        _ = sqlDB.Close()
    }()

    // use db as a normal *gorm.DB
    _ = db
}

Default values

Field Default
MaxOpenConns 50
MaxIdleConns 50
ConnMaxLifetime 1h
ConnMaxIdleTime 30m
LogLevel "info"
SlowThreshold 200ms
SkipDefaultTx true
PrepareStmt true
RetryAttempts 3
RetryDelay 1s

Errors

Sentinel Cause
ErrInvalidDatabaseConfig nil config passed to New
ErrDatabaseDSNRequired DSN is empty
ErrDatabaseDialectorRequired Dialector is empty
ErrUnsupportedDialector Dialector is not a known driver
ErrDatabaseConnectionFailed gorm.Open failed after all retries
ErrDatabasePoolAccessFailed could not retrieve the underlying *sql.DB

Notes

  • retry applies only to the initial connection; queries are not retried automatically
  • set GormConfig.GormConfig to a custom *gorm.Config to bypass the built-in logger and configuration entirely
  • DryRun: true generates SQL without executing it, useful for testing

Documentation

Overview

Package gorm provides a GORM database connection factory with connection pooling, structured logging, and retry support.

Supported dialectors: postgres, mysql, mariadb, sqlite, sqlserver, mssql.

Basic usage

db, err := gorm.New(&gorm.GormConfig{
    DSN:       "host=localhost user=app password=secret dbname=mydb sslmode=disable",
    Dialector: "postgres",
})
if err != nil {
    log.Fatal(err)
}
defer func() {
    sqlDB, _ := db.DB()
    _ = sqlDB.Close()
}()

Starting from defaults

DefaultGormConfig returns a sensible starting point with 50 open/idle connections, 1 h lifetime, prepared statement caching, and info-level logging.

cfg := gorm.DefaultGormConfig()
cfg.DSN       = os.Getenv("DATABASE_URL")
cfg.Dialector = "postgres"

db, err := gorm.New(cfg)

Connection pool inspection

stats, err := gorm.GetConnectionStats(db)
fmt.Println(stats.OpenConnections)

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidDatabaseConfig     = errors.New("invalid database configuration")
	ErrDatabaseDSNRequired       = errors.New("database dsn is required")
	ErrDatabaseDialectorRequired = errors.New("database dialector is required")
	ErrUnsupportedDialector      = errors.New("unsupported database dialector")
	ErrDatabaseConnectionFailed  = errors.New("failed to open database connection")
	ErrDatabasePoolAccessFailed  = errors.New("failed to access database connection pool")
)

Functions

func GetConnectionStats

func GetConnectionStats(db *gorm.DB) (sql.DBStats, error)

GetConnectionStats returns current connection pool statistics

func New

func New(cfg *GormConfig) (*gorm.DB, error)

New initializes a GORM database connection with the given configuration.

func ParseLoggerLevel

func ParseLoggerLevel(levelStr string) glog.LogLevel

ParseLoggerLevel maps the logger level string to gorm's LogLevel

func UpdateConnectionPool

func UpdateConnectionPool(db *gorm.DB, cfg *GormConfig) error

UpdateConnectionPool updates the connection pool settings for an existing connection

Types

type GormConfig

type GormConfig struct {
	DSN             string        // Data Source Name for the database connection
	Dialector       string        // Database dialector (e.g., "postgres", "mysql", "sqlite", "sqlserver")
	LogLevel        string        // Log level for GORM (e.g., "silent", "info", "error", "warning")
	MaxOpenConns    int           // Maximum number of open connections to the database
	MaxIdleConns    int           // Maximum number of connections in the idle connection pool
	SkipDefaultTx   bool          // Skip default transaction for single create, update, delete operations
	PrepareStmt     bool          // Executes the given query in cached statement
	DryRun          bool          // Generate SQL without executing
	ConnMaxLifetime time.Duration // Maximum amount of time a connection may be reused
	ConnMaxIdleTime time.Duration // Maximum amount of time a connection may be idle before being closed
	SlowThreshold   time.Duration // Threshold for logging slow queries

	// Connection retry
	RetryAttempts int           // Number of retry attempts for connection failures
	RetryDelay    time.Duration // Delay between retry attempts

	// GORM Config override
	GormConfig *gorm.Config
}

GormConfig holds database configuration

func DefaultGormConfig

func DefaultGormConfig() *GormConfig

DefaultGormConfig returns a GormConfig with sensible defaults

Jump to

Keyboard shortcuts

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