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 ¶
- func AutoMigrate(db *gorm.DB, models ...interface{}) error
- func Close(db *gorm.DB) error
- func ColumnExists(db *gorm.DB, model interface{}, column string) bool
- func Connect(dialector gorm.Dialector, cfg Config) (*gorm.DB, error)
- func CreateIndex(db *gorm.DB, model interface{}, name string, columns ...string) error
- func DropIndex(db *gorm.DB, model interface{}, name string) error
- func DropTables(db *gorm.DB, models ...interface{}) error
- func EnsureAtlasInstalled() error
- func InTx(db *gorm.DB) bool
- func InitMigrationDir(dir string) error
- func InstallAtlas() string
- func IsAtlasInstalled() bool
- func Ping(db *gorm.DB) error
- func TableExists(db *gorm.DB, model interface{}) bool
- func WithRetry(dialector gorm.Dialector, cfg Config, maxRetries int, retryDelay time.Duration) (*gorm.DB, error)
- func WithTx(db *gorm.DB, fn func(*gorm.DB) error) error
- func WithTxResult[T any](db *gorm.DB, fn func(*gorm.DB) (T, error)) (T, error)
- type Atlas
- func (a *Atlas) Apply(ctx context.Context) error
- func (a *Atlas) ApplyN(ctx context.Context, n int) error
- func (a *Atlas) Diff(ctx context.Context, name string) (string, error)
- func (a *Atlas) Down(ctx context.Context) error
- func (a *Atlas) DownN(ctx context.Context, n int) error
- func (a *Atlas) Hash(ctx context.Context) error
- func (a *Atlas) Lint(ctx context.Context) error
- func (a *Atlas) New(ctx context.Context, name string) (string, error)
- func (a *Atlas) SchemaInspect(ctx context.Context) (string, error)
- func (a *Atlas) Status(ctx context.Context) (*AtlasStatus, error)
- func (a *Atlas) Validate(ctx context.Context) error
- type AtlasConfig
- type AtlasStatus
- type BaseRepository
- func (r *BaseRepository[T]) Count() (int64, error)
- func (r *BaseRepository[T]) Create(entity *T) error
- func (r *BaseRepository[T]) DB() *gorm.DB
- func (r *BaseRepository[T]) Delete(id any) error
- func (r *BaseRepository[T]) Find(id any) (*T, error)
- func (r *BaseRepository[T]) FindAll() ([]*T, error)
- func (r *BaseRepository[T]) Limit(limit int) *BaseRepository[T]
- func (r *BaseRepository[T]) Offset(offset int) *BaseRepository[T]
- func (r *BaseRepository[T]) Order(value interface{}) *BaseRepository[T]
- func (r *BaseRepository[T]) Update(entity *T) error
- func (r *BaseRepository[T]) Where(query interface{}, args ...interface{}) *BaseRepository[T]
- func (r *BaseRepository[T]) WithTx(tx *gorm.DB) *BaseRepository[T]
- type Config
- type Migration
- type MigrationManager
- type MigrationStatus
- type Repository
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AutoMigrate ¶
AutoMigrate runs GORM auto-migration for the given models
func ColumnExists ¶
ColumnExists checks if a column exists in the given model's table
func CreateIndex ¶
CreateIndex creates an index on the given columns
func DropTables ¶
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 InitMigrationDir ¶ added in v1.3.0
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 TableExists ¶
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
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) Diff ¶ added in v1.3.0
Diff generates a new migration by comparing the schema to the database
func (*Atlas) SchemaInspect ¶ added in v1.3.0
SchemaInspect inspects the current database schema
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 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