database

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2025 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package database provides optional GORM integration helpers for EchoNext applications. This is a contrib package and is completely optional - you can use GORM directly if preferred.

Package database provides optional GORM integration helpers for EchoNext applications.

This is a contrib package and is completely optional. You can use GORM directly if you prefer, or use these helpers to reduce boilerplate code.

Features:

  • Connection management with retry logic
  • Generic Repository[T] pattern with CRUD operations
  • Transaction helpers (WithTx, WithTxResult)
  • Migration utilities
  • Connection pool configuration

Example usage:

import (
    "github.com/abdussamadbello/echonext/pkg/contrib/database"
    "gorm.io/driver/postgres"
)

// Connect to database
cfg := database.DefaultConfig()
cfg.DSN = "postgres://user:pass@localhost/mydb"
db, err := database.Connect(postgres.Open(cfg.DSN), cfg)

// Use repository pattern
userRepo := database.NewRepository[User](db)
user, err := userRepo.Find(1)
users, err := userRepo.FindAll()

// Use transactions
err = database.WithTx(db, func(tx *gorm.DB) error {
    // All operations here are within a transaction
    return userRepo.WithTx(tx).Create(&user)
})

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AutoMigrate

func AutoMigrate(db *gorm.DB, models ...interface{}) error

AutoMigrate runs GORM auto-migration for the given models

func Close

func Close(db *gorm.DB) error

Close closes the database connection

func ColumnExists

func ColumnExists(db *gorm.DB, model interface{}, column string) bool

ColumnExists checks if a column exists in the given model's table

func Connect

func Connect(dialector gorm.Dialector, cfg Config) (*gorm.DB, error)

Connect establishes a database connection with the given dialector and config

func CreateIndex

func CreateIndex(db *gorm.DB, model interface{}, name string, columns ...string) error

CreateIndex creates an index on the given columns

func DropIndex

func DropIndex(db *gorm.DB, model interface{}, name string) error

DropIndex drops an index if it exists

func DropTables

func DropTables(db *gorm.DB, models ...interface{}) error

DropTables drops the given tables if they exist

func InTx

func InTx(db *gorm.DB) bool

InTx checks if the current database instance is within a transaction

func Ping

func Ping(db *gorm.DB) error

Ping checks if the database connection is alive

func TableExists

func TableExists(db *gorm.DB, model interface{}) bool

TableExists checks if a table exists for the given model

func WithRetry

func WithRetry(dialector gorm.Dialector, cfg Config, maxRetries int, retryDelay time.Duration) (*gorm.DB, error)

WithRetry wraps database connection with retry logic

func WithTx

func WithTx(db *gorm.DB, fn func(*gorm.DB) error) error

WithTx executes a function within a database transaction If the function returns an error, the transaction is rolled back Otherwise, the transaction is committed

func WithTxResult

func WithTxResult[T any](db *gorm.DB, fn func(*gorm.DB) (T, error)) (T, error)

WithTxResult executes a function within a transaction and returns a result If the function returns an error, the transaction is rolled back

Types

type BaseRepository

type BaseRepository[T any] struct {
	// contains filtered or unexported fields
}

BaseRepository provides a generic GORM-based repository implementation

func NewRepository

func NewRepository[T any](db *gorm.DB) *BaseRepository[T]

NewRepository creates a new base repository for the given entity type

func (*BaseRepository[T]) Count

func (r *BaseRepository[T]) Count() (int64, error)

Count returns the total number of entities

func (*BaseRepository[T]) Create

func (r *BaseRepository[T]) Create(entity *T) error

Create inserts a new entity

func (*BaseRepository[T]) DB

func (r *BaseRepository[T]) DB() *gorm.DB

DB returns the underlying GORM database instance for custom queries

func (*BaseRepository[T]) Delete

func (r *BaseRepository[T]) Delete(id any) error

Delete removes an entity by ID

func (*BaseRepository[T]) Find

func (r *BaseRepository[T]) Find(id any) (*T, error)

Find retrieves a single entity by ID

func (*BaseRepository[T]) FindAll

func (r *BaseRepository[T]) FindAll() ([]*T, error)

FindAll retrieves all entities

func (*BaseRepository[T]) Limit

func (r *BaseRepository[T]) Limit(limit int) *BaseRepository[T]

Limit adds a LIMIT clause to the query

func (*BaseRepository[T]) Offset

func (r *BaseRepository[T]) Offset(offset int) *BaseRepository[T]

Offset adds an OFFSET clause to the query

func (*BaseRepository[T]) Order

func (r *BaseRepository[T]) Order(value interface{}) *BaseRepository[T]

Order adds an ORDER BY clause to the query

func (*BaseRepository[T]) Update

func (r *BaseRepository[T]) Update(entity *T) error

Update modifies an existing entity

func (*BaseRepository[T]) Where

func (r *BaseRepository[T]) Where(query interface{}, args ...interface{}) *BaseRepository[T]

Where adds a WHERE clause to the query and returns a new repository

func (*BaseRepository[T]) WithTx

func (r *BaseRepository[T]) WithTx(tx *gorm.DB) *BaseRepository[T]

WithTx creates a new repository scoped to the given transaction

type Config

type Config struct {
	Driver       string          // Database driver (postgres, mysql, sqlite, etc.)
	DSN          string          // Data Source Name connection string
	MaxIdleConns int             // Maximum idle connections in pool
	MaxOpenConns int             // Maximum open connections in pool
	MaxLifetime  time.Duration   // Maximum connection lifetime
	LogLevel     logger.LogLevel // GORM log level
}

Config holds database connection configuration

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns sensible defaults for database configuration

type Migration

type Migration struct {
	ID   string
	Up   func(*gorm.DB) error
	Down func(*gorm.DB) error
}

Migration represents a database migration with up and down functions

type MigrationManager

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

MigrationManager manages database migrations

func NewMigrationManager

func NewMigrationManager(db *gorm.DB) *MigrationManager

NewMigrationManager creates a new migration manager

func (*MigrationManager) Down

func (m *MigrationManager) Down() error

Down rolls back all registered migrations in reverse order

func (*MigrationManager) Register

func (m *MigrationManager) Register(migration Migration)

Register adds a migration to the manager

func (*MigrationManager) Up

func (m *MigrationManager) Up() error

Up runs all registered migrations

type Repository

type Repository[T any] interface {
	Find(id any) (*T, error)
	FindAll() ([]*T, error)
	Create(entity *T) error
	Update(entity *T) error
	Delete(id any) error
	Count() (int64, error)
}

Repository defines a generic CRUD interface for database operations This is completely optional - use only if it fits your needs

Jump to

Keyboard shortcuts

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