database

package
v1.4.8 Latest Latest
Warning

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

Go to latest
Published: Dec 29, 2025 License: MIT Imports: 12 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 EnsureAtlasInstalled added in v1.3.0

func EnsureAtlasInstalled() error

EnsureAtlasInstalled checks if Atlas is installed and returns an error if not

func InTx

func InTx(db *gorm.DB) bool

InTx checks if the current database instance is within a transaction

func InitMigrationDir added in v1.3.0

func InitMigrationDir(dir string) error

InitMigrationDir initializes a new migration directory structure

func InstallAtlas added in v1.3.0

func InstallAtlas() string

InstallAtlas provides instructions for installing Atlas

func IsAtlasInstalled added in v1.3.0

func IsAtlasInstalled() bool

IsInstalled checks if Atlas CLI is installed

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 Atlas added in v1.3.0

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

Atlas provides methods for running Atlas migrations

func NewAtlas added in v1.3.0

func NewAtlas(config *AtlasConfig) *Atlas

NewAtlas creates a new Atlas instance with the given configuration

func (*Atlas) Apply added in v1.3.0

func (a *Atlas) Apply(ctx context.Context) error

Apply runs pending migrations

func (*Atlas) ApplyN added in v1.3.0

func (a *Atlas) ApplyN(ctx context.Context, n int) error

ApplyN applies N migrations

func (*Atlas) Diff added in v1.3.0

func (a *Atlas) Diff(ctx context.Context, name string) (string, error)

Diff generates a new migration by comparing the schema to the database

func (*Atlas) Down added in v1.3.0

func (a *Atlas) Down(ctx context.Context) error

Down reverts the last migration

func (*Atlas) DownN added in v1.3.0

func (a *Atlas) DownN(ctx context.Context, n int) error

DownN reverts N migrations

func (*Atlas) Hash added in v1.3.0

func (a *Atlas) Hash(ctx context.Context) error

Hash updates the atlas.sum file

func (*Atlas) Lint added in v1.3.0

func (a *Atlas) Lint(ctx context.Context) error

Lint checks migrations for issues

func (*Atlas) New added in v1.3.0

func (a *Atlas) New(ctx context.Context, name string) (string, error)

New creates a new empty migration file

func (*Atlas) SchemaInspect added in v1.3.0

func (a *Atlas) SchemaInspect(ctx context.Context) (string, error)

SchemaInspect inspects the current database schema

func (*Atlas) Status added in v1.3.0

func (a *Atlas) Status(ctx context.Context) (*AtlasStatus, error)

Status returns the current migration status

func (*Atlas) Validate added in v1.3.0

func (a *Atlas) Validate(ctx context.Context) error

Validate validates the migrations directory

type AtlasConfig added in v1.3.0

type AtlasConfig struct {
	// Dir is the path to the migrations directory
	Dir string
	// URL is the database connection URL
	URL string
	// DevURL is the dev database URL for schema calculations
	DevURL string
	// Env is the Atlas environment to use (local, staging, production)
	Env string
	// ConfigFile is the path to atlas.hcl configuration file
	ConfigFile string
	// DryRun enables dry-run mode for migrations
	DryRun bool
	// Verbose enables verbose output
	Verbose bool
}

AtlasConfig holds configuration for Atlas migrations

func DefaultAtlasConfig added in v1.3.0

func DefaultAtlasConfig() *AtlasConfig

DefaultAtlasConfig returns a default Atlas configuration

type AtlasStatus added in v1.3.0

type AtlasStatus struct {
	Current    string            `json:"Current"`
	Next       string            `json:"Next,omitempty"`
	Pending    []MigrationStatus `json:"Pending,omitempty"`
	Applied    []MigrationStatus `json:"Applied,omitempty"`
	TotalCount int               `json:"TotalCount"`
}

AtlasStatus represents the overall migration status

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 MigrationStatus added in v1.3.0

type MigrationStatus struct {
	Version     string `json:"Version"`
	Description string `json:"Description"`
	Applied     bool   `json:"Applied"`
	AppliedAt   string `json:"AppliedAt,omitempty"`
}

MigrationStatus represents the status of a single migration

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