db

package
v1.4.1 Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2025 License: MIT Imports: 10 Imported by: 0

README

Database Package

This package provides a unified database interface that works with both MySQL and PostgreSQL databases. It handles connection management, pooling, and query execution.

Features

  • Unified interface for MySQL and PostgreSQL
  • Connection pooling with configurable parameters
  • Context-aware query execution with timeout support
  • Transaction support
  • Proper error handling

Usage

Configuration

Configure the database connection using the Config struct:

cfg := db.Config{
    Type:            "mysql", // or "postgres"
    Host:            "localhost",
    Port:            3306,
    User:            "user",
    Password:        "password",
    Name:            "dbname",
    MaxOpenConns:    25,
    MaxIdleConns:    5,
    ConnMaxLifetime: 5 * time.Minute,
    ConnMaxIdleTime: 5 * time.Minute,
}
Connecting to the Database
// Create a new database instance
database, err := db.NewDatabase(cfg)
if err != nil {
    log.Fatalf("Failed to create database instance: %v", err)
}

// Connect to the database
if err := database.Connect(); err != nil {
    log.Fatalf("Failed to connect to database: %v", err)
}
defer database.Close()
Executing Queries
// Context with timeout
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

// Execute a query that returns rows
rows, err := database.Query(ctx, "SELECT id, name FROM users WHERE age > ?", 18)
if err != nil {
    log.Fatalf("Query failed: %v", err)
}
defer rows.Close()

// Process rows
for rows.Next() {
    var id int
    var name string
    if err := rows.Scan(&id, &name); err != nil {
        log.Printf("Failed to scan row: %v", err)
        continue
    }
    fmt.Printf("User: %d - %s\n", id, name)
}

if err = rows.Err(); err != nil {
    log.Printf("Error during row iteration: %v", err)
}
Executing Statements
// Execute a statement
result, err := database.Exec(ctx, "UPDATE users SET active = ? WHERE last_login < ?", true, time.Now().AddDate(0, -1, 0))
if err != nil {
    log.Fatalf("Statement execution failed: %v", err)
}

// Get affected rows
rowsAffected, err := result.RowsAffected()
if err != nil {
    log.Printf("Failed to get affected rows: %v", err)
}
fmt.Printf("Rows affected: %d\n", rowsAffected)
Using Transactions
// Start a transaction
tx, err := database.BeginTx(ctx, nil)
if err != nil {
    log.Fatalf("Failed to start transaction: %v", err)
}

// Execute statements within the transaction
_, err = tx.ExecContext(ctx, "INSERT INTO users (name, email) VALUES (?, ?)", "John", "john@example.com")
if err != nil {
    tx.Rollback()
    log.Fatalf("Failed to execute statement in transaction: %v", err)
}

_, err = tx.ExecContext(ctx, "UPDATE user_stats SET user_count = user_count + 1")
if err != nil {
    tx.Rollback()
    log.Fatalf("Failed to execute statement in transaction: %v", err)
}

// Commit the transaction
if err := tx.Commit(); err != nil {
    log.Fatalf("Failed to commit transaction: %v", err)
}

Error Handling

The package defines several common database errors:

  • ErrNotFound: Record not found
  • ErrAlreadyExists: Record already exists
  • ErrInvalidInput: Invalid input parameters
  • ErrNotImplemented: Functionality not implemented
  • ErrNoDatabase: No database connection

These can be used for standardized error handling in your application.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound       = errors.New("record not found")
	ErrAlreadyExists  = errors.New("record already exists")
	ErrInvalidInput   = errors.New("invalid input")
	ErrNotImplemented = errors.New("not implemented")
	ErrNoDatabase     = errors.New("no database connection")
)

Common database errors

Functions

This section is empty.

Types

type Config

type Config struct {
	Type     string
	Host     string
	Port     int
	User     string
	Password string
	Name     string
	// Connection pool settings
	MaxOpenConns    int
	MaxIdleConns    int
	ConnMaxLifetime time.Duration
	ConnMaxIdleTime time.Duration
}

Config represents database connection configuration

func (*Config) SetDefaults

func (c *Config) SetDefaults()

SetDefaults sets default values for the configuration if they are not set

type Database

type Database interface {
	// Core database operations
	Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
	QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row
	Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

	// Transaction support
	BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)

	// Connection management
	Connect() error
	Close() error
	Ping(ctx context.Context) error

	// Metadata
	DriverName() string
	ConnectionString() string

	// DB object access (for specific DB operations)
	DB() *sql.DB
}

Database represents a generic database interface

func NewDatabase

func NewDatabase(config Config) (Database, error)

NewDatabase creates a new database connection based on the provided configuration

type DatabaseConnectionConfig added in v1.3.0

type DatabaseConnectionConfig struct {
	ID       string `json:"id"`   // Unique identifier for this connection
	Type     string `json:"type"` // mysql or postgres
	Host     string `json:"host"`
	Port     int    `json:"port"`
	User     string `json:"user"`
	Password string `json:"password"`
	Name     string `json:"name"`
}

DatabaseConnectionConfig represents a single database connection configuration

type Manager added in v1.3.0

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

Manager manages multiple database connections

func NewDBManager added in v1.3.0

func NewDBManager() *Manager

NewDBManager creates a new database manager

func (*Manager) Close added in v1.3.0

func (m *Manager) Close() error

Close closes all database connections

func (*Manager) Connect added in v1.3.0

func (m *Manager) Connect() error

Connect establishes connections to all configured databases

func (*Manager) GetDB added in v1.3.0

func (m *Manager) GetDB(id string) (Database, error)

GetDB returns a database connection by its ID

func (*Manager) ListDatabases added in v1.3.0

func (m *Manager) ListDatabases() []string

ListDatabases returns a list of all available database connections

func (*Manager) LoadConfig added in v1.3.0

func (m *Manager) LoadConfig(configJSON []byte) error

LoadConfig loads database configurations from JSON

func (*Manager) Ping added in v1.3.0

func (m *Manager) Ping(ctx context.Context) map[string]error

Ping checks if all database connections are alive

type MultiDBConfig added in v1.3.0

type MultiDBConfig struct {
	Connections []DatabaseConnectionConfig `json:"connections"`
}

MultiDBConfig represents the configuration for multiple database connections

Jump to

Keyboard shortcuts

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