db

package
v2.0.0-...-ce7e00b Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2026 License: MIT Imports: 7 Imported by: 7

README

DB Library

The DB library provides a comprehensive wrapper around GORM (Go Object Relational Mapper) for database operations in the EVO Framework. It simplifies database interactions and provides additional functionality for schema management, migrations, health checks, and connection management.

Installation

import "github.com/getevo/evo/v2/lib/db"

Features

  • Context-Aware Database Access: Proper context propagation for timeouts and cancellation
  • Health Checks: Comprehensive health monitoring with connection pool statistics
  • Connection Management: Functions for managing database connections
  • CRUD Operations: Simple functions for creating, reading, updating, and deleting records
  • Query Building: Methods for constructing complex database queries
  • Transaction Support: Functions for handling database transactions
  • Schema Management: Tools for managing database schemas and migrations
  • Model Registration: Ability to register and manage database models
  • Multi-Dialect Support: MySQL, PostgreSQL with shared schema abstractions

Subdirectories

The DB library includes several subdirectories for specialized functionality:

  • entity: Provides base entity structures and functionality
  • schema: Tools for schema management and migrations (DB-agnostic)
  • types: Custom data types for database interactions

Quick Start

import (
    "context"
    "github.com/getevo/evo/v2"
)

func handler(r *evo.Request) any {
    ctx := r.Context()
    db := evo.GetDB(ctx)  // Context-aware database instance

    var users []User
    db.Find(&users)

    return users
}
Health Check Endpoint
import (
    "github.com/getevo/evo/v2/lib/db"
)

func healthHandler(r *evo.Request) any {
    ctx := r.Context()
    database := evo.GetDBO()

    result := db.HealthCheck(ctx, database)
    if !result.Healthy {
        r.Status(503)
        return map[string]any{
            "status": "unhealthy",
            "error": result.Error,
        }
    }

    return map[string]any{
        "status": "healthy",
        "response_time_ms": result.ResponseTime.Milliseconds(),
        "connections_open": result.ConnectionsOpen,
        "connections_idle": result.ConnectionsIdle,
    }
}

Health Check API

db.Ping(ctx context.Context, db *gorm.DB) error

Simple ping to check if database is alive.

if err := db.Ping(ctx, database); err != nil {
    log.Error("Database unreachable:", err)
}
db.HealthCheck(ctx context.Context, db *gorm.DB) HealthCheckResult

Comprehensive health check with connection pool statistics.

result := db.HealthCheck(ctx, database)
fmt.Printf("Healthy: %v, Response Time: %v\n", result.Healthy, result.ResponseTime)
fmt.Printf("Connections: %d open, %d in use, %d idle\n",
    result.ConnectionsOpen, result.ConnectionsInUse, result.ConnectionsIdle)

HealthCheckResult Structure:

type HealthCheckResult struct {
    Healthy          bool          // Overall health status
    ResponseTime     time.Duration // Ping response time
    ConnectionsOpen  int           // Total open connections
    ConnectionsInUse int           // Connections currently in use
    ConnectionsIdle  int           // Idle connections available
    MaxOpenConns     int           // Maximum allowed connections
    Error            string        // Error message if unhealthy
}
db.WaitForDB(ctx context.Context, db *gorm.DB, maxRetries int, retryInterval time.Duration) error

Wait for database to become available with retries. Useful during application startup.

ctx := context.Background()
err := db.WaitForDB(ctx, database, 10, 2*time.Second)
if err != nil {
    log.Fatal("Database not available:", err)
}
db.GetConnectionStats(db *gorm.DB) (sql.DBStats, error)

Get detailed connection pool statistics.

stats, err := db.GetConnectionStats(database)
if err == nil {
    fmt.Printf("Max Open Connections: %d\n", stats.MaxOpenConnections)
    fmt.Printf("Connections In Use: %d\n", stats.InUse)
}
db.CloseConnection(db *gorm.DB) error

Gracefully close database connection.

defer db.CloseConnection(database)

Usage Examples

Basic CRUD Operations
package main

import (
    "github.com/getevo/evo/v2"
)

type User struct {
    ID   uint   `gorm:"primaryKey"`
    Name string
    Age  int
}

func main() {
    evo.Setup()

    db := evo.GetDBO()

    // Register models
    schema.UseModel(db, User{})

    // Create a new user
    user := User{Name: "John Doe", Age: 30}
    db.Create(&user)

    // Find a user
    var foundUser User
    db.First(&foundUser, user.ID)

    // Update a user
    db.Model(&foundUser).Update("Age", 31)

    // Delete a user
    db.Delete(&foundUser)
}
Context-Aware Query with Timeout
func GetUserByID(ctx context.Context, id int64) (*User, error) {
    // Create a 5-second timeout context
    ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
    defer cancel()

    var user User
    db := evo.GetDB(ctx)

    if err := db.Where("id = ?", id).First(&user).Error; err != nil {
        return nil, err
    }

    return &user, nil
}
Using Transactions
package main

import (
    "context"
    "github.com/getevo/evo/v2"
)

func createUsers(ctx context.Context) error {
    db := evo.GetDB(ctx)

    // Start a transaction
    return db.Transaction(func(tx *gorm.DB) error {
        // Perform operations within the transaction
        if err := tx.Create(&User{Name: "User 1"}).Error; err != nil {
            // Return error will rollback the transaction
            return err
        }

        if err := tx.Create(&User{Name: "User 2"}).Error; err != nil {
            return err
        }

        // Return nil will commit the transaction
        return nil
    })
}
Graceful Startup with Database Wait
func main() {
    evo.Setup()

    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()

    database := evo.GetDBO()

    // Wait up to 30 seconds for database
    if err := db.WaitForDB(ctx, database, 15, 2*time.Second); err != nil {
        log.Fatal("Failed to connect to database:", err)
    }

    log.Info("Database connected successfully")

    evo.Run()
}
Monitor Connection Pool
func monitorConnectionPool() {
    ticker := time.NewTicker(30 * time.Second)
    defer ticker.Stop()

    database := evo.GetDBO()

    for range ticker.C {
        stats, err := db.GetConnectionStats(database)
        if err != nil {
            log.Error("Failed to get stats:", err)
            continue
        }

        log.Info("Connection Pool Stats",
            "open", stats.OpenConnections,
            "in_use", stats.InUse,
            "idle", stats.Idle,
            "wait_count", stats.WaitCount,
            "wait_duration", stats.WaitDuration,
        )

        // Alert if connection pool is exhausted
        if stats.InUse >= stats.MaxOpenConnections {
            log.Warning("Connection pool exhausted!")
        }
    }
}
Schema Migrations
package main

import (
    "github.com/getevo/evo/v2"
    "github.com/getevo/evo/v2/lib/db/schema"
)

func main() {
    evo.Setup()

    db := evo.GetDBO()

    // Register models
    schema.UseModel(db, User{})

    // Get migration script (dry run)
    scripts := schema.GetMigrationScript(db)
    for _, script := range scripts {
        fmt.Println(script)
    }

    // Or perform migration directly
    err := evo.DoMigration()
    if err != nil {
        log.Fatal("Migration failed:", err)
    }
}

Advanced Query Building

package main

import (
    "github.com/getevo/evo/v2"
)

func main() {
    var users []User

    ctx := context.Background()
    db := evo.GetDB(ctx)

    // Complex query with conditions, ordering, and limits
    db.Where("age > ?", 18).
       Where("name LIKE ?", "%Doe%").
       Order("age DESC").
       Limit(10).
       Find(&users)

    // Using scopes for reusable query parts
    db.Scopes(ActiveUsers, AgeGreaterThan(18)).Find(&users)
}

// Scope example
func ActiveUsers(d *gorm.DB) *gorm.DB {
    return d.Where("active = ?", true)
}

func AgeGreaterThan(age int) func(*gorm.DB) *gorm.DB {
    return func(d *gorm.DB) *gorm.DB {
        return d.Where("age > ?", age)
    }
}

Best Practices

1. Always Use Context
// ✅ Good - with context
db := evo.GetDB(r.Context())

// ❌ Avoid - without context
db := evo.GetDBO()
2. Set Query Timeouts
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()

db := evo.GetDB(ctx)
3. Monitor Health in Production
// Register health check endpoint
evo.Get("/health", healthCheckHandler)
evo.Get("/health/db", databaseHealthHandler)
4. Handle Graceful Shutdown
func shutdown() {
    database := evo.GetDBO()
    if err := db.CloseConnection(database); err != nil {
        log.Error("Error closing database:", err)
    }
}
5. Use Connection Pool Wisely
// Configure connection pool in config.yml
Database:
  MaxIdleConns: 10
  MaxOpenConns: 100
  ConnMaxLifTime: 1h

Configuration

Database configuration is managed through the settings package:

Database:
  Enabled: true
  Type: mysql  # or postgres
  Server: localhost:3306
  Username: root
  Password: password
  Database: mydb
  MaxIdleConns: 10
  MaxOpenConns: 100
  ConnMaxLifTime: 1h
  SlowQueryThreshold: 500ms
  Debug: 3  # 0=Silent, 2=Error, 3=Warn, 4=Info
  SSLMode: false
  Params: "charset=utf8mb4&parseTime=True&loc=Local"
  • entity: Base entity structures and functionality
  • schema: Schema management and migrations (database-agnostic)
  • types: Custom data types for database interactions
  • settings: Configuration management
  • log: Logging system

See Also

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Enabled = false

Functions

func AddError

func AddError(err error) error

AddError add error to db

func Assign

func Assign(attrs ...any) (tx *gorm.DB)

Assign provide attributes used in FirstOrCreate or FirstOrInit

Assign adds attributes even if the record is found. If using FirstOrCreate, this means that records will be updated even if they are found.

// assign an email regardless of if the record is not found
db.Where(User{Name: "non_existing"}).Assign(User{Email: "fake@fake.org"}).FirstOrInit(&user)
// user -> User{Name: "non_existing", Email: "fake@fake.org"}

// assign email regardless of if record is found
db.Where(User{Name: "jinzhu"}).Assign(User{Email: "fake@fake.org"}).FirstOrInit(&user)
// user -> User{Name: "jinzhu", Age: 20, Email: "fake@fake.org"}

func Attrs

func Attrs(attrs ...any) (tx *gorm.DB)

Attrs provide attributes used in FirstOrCreate or FirstOrInit

Attrs only adds attributes if the record is not found.

// assign an email if the record is not found
db.Where(User{Name: "non_existing"}).Attrs(User{Email: "fake@fake.org"}).FirstOrInit(&user)
// user -> User{Name: "non_existing", Email: "fake@fake.org"}

// assign an email if the record is not found, otherwise ignore provided email
db.Where(User{Name: "jinzhu"}).Attrs(User{Email: "fake@fake.org"}).FirstOrInit(&user)
// user -> User{Name: "jinzhu", Age: 20}

func Begin

func Begin(opts ...*sql.TxOptions) *gorm.DB

Begin begins a transaction with any transaction options opts

func Clauses

func Clauses(conds ...clause.Expression) (tx *gorm.DB)

Clauses Add clauses

This supports both standard clauses (clause.OrderBy, clause.Limit, clause.Where) and more advanced techniques like specifying lock strength and optimizer hints. See the docs for more depth.

// add a simple limit clause
db.Clauses(clause.Limit{Limit: 1}).Find(&User{})
// tell the optimizer to use the `idx_user_name` index
db.Clauses(hints.UseIndex("idx_user_name")).Find(&User{})
// specify the lock strength to UPDATE
db.Clauses(clause.Locking{Strength: "UPDATE"}).Find(&users)

func CloseConnection

func CloseConnection(db *gorm.DB) error

CloseConnection gracefully closes the database connection

func Commit

func Commit() *gorm.DB

Commit commits the changes in a transaction

func Connection

func Connection(fc func(tx *gorm.DB) error) (err error)

Connection uses a db connection to execute an arbitrary number of commands in fc. When finished, the connection is returned to the connection pool.

func Count

func Count(count *int64) (tx *gorm.DB)

func Create

func Create(value any) (tx *gorm.DB)

Create inserts value, returning the inserted data's primary key in value's id

func CreateInBatches

func CreateInBatches(value any, batchSize int) (tx *gorm.DB)

CreateInBatches inserts value in batches of batchSize

func DB

func DB() (*sql.DB, error)

DB returns `*sql.DB`

func Debug

func Debug() (tx *gorm.DB)

Debug start debug mode

func Delete

func Delete(value any, conds ...any) (tx *gorm.DB)

Delete deletes value matching given conditions. If value contains primary key it is included in the conditions. If value includes a deleted_at field, then Delete performs a soft delete instead by setting deleted_at with the current time if null.

func DialectName

func DialectName() string

DialectName returns the current database dialect name ("mysql", "postgres", etc.) Returns empty string if no database is connected.

func Distinct

func Distinct(args ...any) (tx *gorm.DB)

Distinct specify distinct fields that you want querying

// Select distinct names of users
db.Distinct("name").Find(&results)
// Select distinct name/age pairs from users
db.Distinct("name", "age").Find(&results)

func DoMigration

func DoMigration() error

func DryRunMigration

func DryRunMigration() []string

func DumpSchema

func DumpSchema() []string

func Exec

func Exec(sql string, values ...any) (tx *gorm.DB)

Exec executes raw sql

func Find

func Find(dest any, conds ...any) (tx *gorm.DB)

Find finds all records matching given conditions conds

func FindInBatches

func FindInBatches(dest any, batchSize int, fc func(tx *gorm.DB, batch int) error) *gorm.DB

FindInBatches finds all records in batches of batchSize

func First

func First(dest any, conds ...any) (tx *gorm.DB)

First finds the first record ordered by primary key, matching given conditions conds

func FirstOrCreate

func FirstOrCreate(dest any, conds ...any) (tx *gorm.DB)

FirstOrCreate finds the first matching record, otherwise if not found creates a new instance with given conds. Each conds must be a struct or map.

Using FirstOrCreate in conjunction with Assign will result in an update to the database even if the record exists.

// assign an email if the record is not found
result := db.Where(User{Name: "non_existing"}).Attrs(User{Email: "fake@fake.org"}).FirstOrCreate(&user)
// user -> User{Name: "non_existing", Email: "fake@fake.org"}
// result.RowsAffected -> 1

// assign email regardless of if record is found
result := db.Where(User{Name: "jinzhu"}).Assign(User{Email: "fake@fake.org"}).FirstOrCreate(&user)
// user -> User{Name: "jinzhu", Age: 20, Email: "fake@fake.org"}
// result.RowsAffected -> 1

func FirstOrInit

func FirstOrInit(dest any, conds ...any) (tx *gorm.DB)

FirstOrInit finds the first matching record, otherwise if not found initializes a new instance with given conds. Each conds must be a struct or map.

FirstOrInit never modifies the database. It is often used with Assign and Attrs.

// assign an email if the record is not found
db.Where(User{Name: "non_existing"}).Attrs(User{Email: "fake@fake.org"}).FirstOrInit(&user)
// user -> User{Name: "non_existing", Email: "fake@fake.org"}

// assign email regardless of if record is found
db.Where(User{Name: "jinzhu"}).Assign(User{Email: "fake@fake.org"}).FirstOrInit(&user)
// user -> User{Name: "jinzhu", Age: 20, Email: "fake@fake.org"}

func Get

func Get(key string) (any, bool)

Get value with key from current db instance's context

func GetConnectionStats

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

GetConnectionStats returns current database connection pool statistics

func GetContext

func GetContext(inputs ...interface{}) *gorm.DB

func GetInstance

func GetInstance() *gorm.DB

GetInstance returns the global database instance, or nil if not initialized

func GetMigrationScript

func GetMigrationScript() []string

func GetModel

func GetModel(name string) *schema.Model

func Group

func Group(name string) (tx *gorm.DB)

Group specify the group method on the find

// Select the sum age of users with given names
db.Model(&User{}).Select("name, sum(age) as total").Group("name").Find(&results)

func Having

func Having(query any, args ...any) (tx *gorm.DB)

Having specify HAVING conditions for GROUP BY

// Select the sum age of users with name jinzhu
db.Model(&User{}).Select("name, sum(age) as total").Group("name").Having("name = ?", "jinzhu").Find(&result)

func InnerJoins

func InnerJoins(query string, args ...any) (tx *gorm.DB)

InnerJoins specify inner joins conditions db.InnerJoins("Account").Find(&user)

func InstanceGet

func InstanceGet(key string) (any, bool)

InstanceGet get value with key from current db instance's context

func InstanceSet

func InstanceSet(key string, value any) *gorm.DB

InstanceSet store value with key into current db instance's context

func IsEnabled

func IsEnabled() bool

func Joins

func Joins(query string, args ...any) (tx *gorm.DB)

Joins specify Joins conditions

db.Joins("Account").Find(&user)
db.Joins("JOIN emails ON emails.user_id = users.id AND emails.email = ?", "jinzhu@example.org").Find(&user)
db.Joins("Account", DB.Select("id").Where("user_id = users.id AND name = ?", "someName").Model(&Account{}))

func Last

func Last(dest any, conds ...any) (tx *gorm.DB)

Last finds the last record ordered by primary key, matching given conditions conds

func Limit

func Limit(limit int) (tx *gorm.DB)

Limit specify the number of records to be retrieved

Limit conditions can be cancelled by using `Limit(-1)`.

// retrieve 3 users
db.Limit(3).Find(&users)
// retrieve 3 users into users1, and all users into users2
db.Limit(3).Find(&users1).Limit(-1).Find(&users2)

func Model

func Model(value any) (tx *gorm.DB)

Model specify the model you would like to run db operations

// update all user's name to `hello`
db.Model(&User{}).Update("name", "hello")
// if user's primary key is non-blank, will use it as condition, then will only update that user's name to `hello`
db.Model(&user).Update("name", "hello")

func Models

func Models() []schema.Model

func Not

func Not(query any, args ...any) (tx *gorm.DB)

Not add NOT conditions

Not works similarly to where, and has the same syntax.

// Find the first user with name not equal to jinzhu
db.Not("name = ?", "jinzhu").First(&user)

func Offset

func Offset(offset int) (tx *gorm.DB)

Offset specify the number of records to skip before starting to return the records

Offset conditions can be cancelled by using `Offset(-1)`.

// select the third user
db.Offset(2).First(&user)
// select the first user by cancelling an earlier chained offset
db.Offset(5).Offset(-1).First(&user)

func Omit

func Omit(columns ...string) (tx *gorm.DB)

Omit specify fields that you want to ignore when creating, updating and querying

func OnAfterMigration

func OnAfterMigration(callback func(db *gorm.DB))

func OnBeforeMigration

func OnBeforeMigration(callback func(db *gorm.DB))

func OnPrepareContext

func OnPrepareContext(fn func(db *gorm.DB, v interface{}) *gorm.DB)

func Or

func Or(query any, args ...any) (tx *gorm.DB)

Or add OR conditions

Or is used to chain together queries with an OR.

// Find the first user with name equal to jinzhu or john
db.Where("name = ?", "jinzhu").Or("name = ?", "john").First(&user)

func Order

func Order(value any) (tx *gorm.DB)

Order specify order when retrieving records from database

db.Order("name DESC")
db.Order(clause.OrderByColumn{Column: clause.Column{Name: "name"}, Desc: true})

func Ping

func Ping(ctx context.Context, db *gorm.DB) error

Ping checks if the database connection is alive and returns basic stats

func Pluck

func Pluck(column string, dest any) (tx *gorm.DB)

Pluck queries a single column from a model, returning in the slice dest. E.g.:

var ages []int64
db.Model(&users).Pluck("age", &ages)

func Preload

func Preload(query string, args ...any) (tx *gorm.DB)

Preload preload associations with given conditions

// get all users, and preload all non-cancelled orders
db.Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users)

func QuoteIdent

func QuoteIdent(name string) string

QuoteIdent returns the dialect-appropriate quoted identifier. MySQL uses backticks: `name`, PostgreSQL uses double quotes: "name"

func Raw

func Raw(sql string, values ...any) (tx *gorm.DB)

func Register

func Register(obj *gorm.DB)

func RegisterDriver

func RegisterDriver(d Driver)

RegisterDriver sets the active database driver.

func Rollback

func Rollback() *gorm.DB

Rollback rollbacks the changes in a transaction

func RollbackTo

func RollbackTo(name string) *gorm.DB

func Row

func Row() *sql.Row

func Rows

func Rows() (*sql.Rows, error)

func Save

func Save(value any) (tx *gorm.DB)

Save updates value in database. If value doesn't contain a matching primary key, value is inserted.

func SavePoint

func SavePoint(name string) *gorm.DB

func Scan

func Scan(dest any) (tx *gorm.DB)

Scan scans selected value to the struct dest

func ScanRows

func ScanRows(rows *sql.Rows, dest any) error

func Scopes

func Scopes(funcs ...func(*gorm.DB) *gorm.DB) (tx *gorm.DB)

Scopes pass current database connection to arguments `func(DB) DB`, which could be used to add conditions dynamically

func AmountGreaterThan1000(db *gorm.DB) *gorm.DB {
    return db.Where("amount > ?", 1000)
}

func OrderStatus(status []string) func  *gorm.DB {
    return func  *gorm.DB {
        return db.Scopes(AmountGreaterThan1000).Where("status in (?)", status)
    }
}

db.Scopes(AmountGreaterThan1000, OrderStatus([]string{"paid", "shipped"})).Find(&orders)

func Select

func Select(query any, args ...any) (tx *gorm.DB)

Select specify fields that you want when querying, creating, updating

Use Select when you only want a subset of the fields. By default, GORM will select all fields. Select accepts both string arguments and arrays.

// Select name and age of user using multiple arguments
db.Select("name", "age").Find(&users)
// Select name and age of user using an array
db.Select([]string{"name", "age"}).Find(&users)

func Session

func Session(config *gorm.Session) *gorm.DB

Session create new db session

func Set

func Set(key string, value any) *gorm.DB

Set store value with key into current db instance's context

func SetDefaultCharset

func SetDefaultCharset(charset string)

func SetDefaultCollation

func SetDefaultCollation(collation string)

func SetDefaultEngine

func SetDefaultEngine(engine string)

func SetupJoinTable

func SetupJoinTable(model any, field string, joinTable any) error

SetupJoinTable setup join table schema

func Table

func Table(name string, args ...any) (tx *gorm.DB)

Table specify the table you would like to run db operations

// Get a user
db.Table("users").take(&result)

func Take

func Take(dest any, conds ...any) (tx *gorm.DB)

Take finds the first record returned by the database in no specified order, matching given conditions conds

func ToSQL

func ToSQL(queryFn func(tx *gorm.DB) *gorm.DB) string

ToSQL for generate SQL string.

db.ToSQL(func(tx *gorm.DB) *gorm.DB {
		return tx.Model(&User{}).Where(&User{Name: "foo", Age: 20})
			.Limit(10).Offset(5)
			.Order("name ASC")
			.First(&User{})
})

func Transaction

func Transaction(fc func(tx *gorm.DB) error, opts ...*sql.TxOptions) (err error)

Transaction start a transaction as a block, return error will rollback, otherwise to commit. Transaction executes an arbitrary number of commands in fc within a transaction. On success the changes are committed; if an error occurs they are rolled back.

func TriggerOnAfterMigration

func TriggerOnAfterMigration()

func TriggerOnBeforeMigration

func TriggerOnBeforeMigration()

func Unscoped

func Unscoped() (tx *gorm.DB)

func Update

func Update(column string, value any) (tx *gorm.DB)

Update updates column with value using callbacks. Reference: https://gorm.io/docs/update.html#Update-Changed-Fields

func UpdateColumn

func UpdateColumn(column string, value any) (tx *gorm.DB)

func UpdateColumns

func UpdateColumns(values any) (tx *gorm.DB)

func Updates

func Updates(values any) (tx *gorm.DB)

Updates updates attributes using callbacks. values must be a struct or map. Reference: https://gorm.io/docs/update.html#Update-Changed-Fields

func Use

func Use(plugin gorm.Plugin) error

Use plugin

func UseModel

func UseModel(models ...any)

func WaitForDB

func WaitForDB(ctx context.Context, db *gorm.DB, maxRetries int, retryInterval time.Duration) error

WaitForDB waits for the database to become available with retries Useful for application startup when the database might not be ready immediately

func Where

func Where(query any, args ...any) (tx *gorm.DB)

Where add conditions

See the docs for details on the various formats that where clauses can take. By default, where clauses chain with AND.

// Find the first user with name jinzhu
db.Where("name = ?", "jinzhu").First(&user)
// Find the first user with name jinzhu and age 20
db.Where(&User{Name: "jinzhu", Age: 20}).First(&user)
// Find the first user with name jinzhu and age not equal to 20
db.Where("name = ?", "jinzhu").Where("age <> ?", "20").First(&user)

func WithContext

func WithContext(ctx context.Context) *gorm.DB

WithContext change current instance db's context to ctx

Types

type Driver

type Driver interface {
	Name() string
	Open(config DriverConfig, gormConfig *gorm.Config) (*gorm.DB, error)
	GetMigrationScript(db *gorm.DB) []string
}

Driver abstracts database connection and migration logic so that each driver (mysql, pgsql) is a self-contained package. Users pass the desired driver to evo.Setup().

func GetDriver

func GetDriver() Driver

GetDriver returns the currently registered driver, or nil.

type DriverConfig

type DriverConfig struct {
	Server   string
	Username string
	Password string
	Database string
	Schema   string // PostgreSQL schema name (defaults to 'public')
	SSLMode  string
	Params   string
}

DriverConfig holds the connection parameters extracted from DatabaseConfig.

type HealthCheckResult

type HealthCheckResult struct {
	Healthy          bool          `json:"healthy"`
	ResponseTime     time.Duration `json:"response_time"`
	ConnectionsOpen  int           `json:"connections_open"`
	ConnectionsInUse int           `json:"connections_in_use"`
	ConnectionsIdle  int           `json:"connections_idle"`
	MaxOpenConns     int           `json:"max_open_conns"`
	Error            string        `json:"error,omitempty"`
}

HealthCheckResult contains the results of a database health check

func HealthCheck

func HealthCheck(ctx context.Context, db *gorm.DB) HealthCheckResult

HealthCheck performs a comprehensive health check on the database connection and returns detailed statistics about the connection pool

Directories

Path Synopsis
migration

Jump to

Keyboard shortcuts

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