database

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 16, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package database provides database connection and operations.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound is returned when a record is not found.
	ErrNotFound = errors.New("record not found")

	// ErrDuplicateKey is returned when a unique constraint is violated.
	ErrDuplicateKey = errors.New("duplicate key violation")

	// ErrForeignKey is returned when a foreign key constraint is violated.
	ErrForeignKey = errors.New("foreign key violation")
)

Functions

func IsDuplicateKeyError

func IsDuplicateKeyError(err error) bool

IsDuplicateKeyError checks if an error is a duplicate key error.

func IsForeignKeyError

func IsForeignKeyError(err error) bool

IsForeignKeyError checks if an error is a foreign key error.

func IsNotFoundError

func IsNotFoundError(err error) bool

IsNotFoundError checks if an error is a "not found" error.

func WrapError

func WrapError(err error, operation string) error

WrapError wraps database errors with more descriptive messages.

Types

type ConnectionStats

type ConnectionStats struct {
	MaxOpenConnections int           `json:"max_open_connections"`
	OpenConnections    int           `json:"open_connections"`
	InUse              int           `json:"in_use"`
	Idle               int           `json:"idle"`
	WaitCount          int64         `json:"wait_count"`
	WaitDuration       time.Duration `json:"wait_duration"`
}

ConnectionStats represents database connection pool statistics.

type DBStats

type DBStats struct {
	MaxOpenConnections int           `json:"max_open_connections"`
	OpenConnections    int           `json:"open_connections"`
	InUse              int           `json:"in_use"`
	Idle               int           `json:"idle"`
	WaitCount          int64         `json:"wait_count"`
	WaitDuration       time.Duration `json:"wait_duration"`
	MaxIdleClosed      int64         `json:"max_idle_closed"`
	MaxLifetimeClosed  int64         `json:"max_lifetime_closed"`
}

DBStats represents database connection pool statistics (JSON-friendly).

type HealthStatus

type HealthStatus struct {
	Status      string          `json:"status"`
	Timestamp   time.Time       `json:"timestamp"`
	Latency     time.Duration   `json:"latency"`
	Connections ConnectionStats `json:"connections"`
	Error       string          `json:"error,omitempty"`
	Warning     string          `json:"warning,omitempty"`
}

HealthStatus represents the database health status.

type PaginatedResult

type PaginatedResult[T any] struct {
	Items      []T   `json:"items"`
	Total      int64 `json:"total"`
	Page       int   `json:"page"`
	PageSize   int   `json:"page_size"`
	TotalPages int   `json:"total_pages"`
}

PaginatedResult represents a paginated query result.

func NewPaginatedResult

func NewPaginatedResult[T any](items []T, total int64, pagination Pagination) PaginatedResult[T]

NewPaginatedResult creates a new PaginatedResult.

type Pagination

type Pagination struct {
	Page     int `json:"page"`
	PageSize int `json:"page_size"`
	Offset   int `json:"-"`
}

Pagination represents pagination parameters.

func NewPagination

func NewPagination(page, pageSize int) Pagination

NewPagination creates a new Pagination with defaults.

type PostgresDB

type PostgresDB struct {
	*sqlx.DB
	// contains filtered or unexported fields
}

PostgresDB wraps the sqlx.DB with additional functionality.

func NewPostgresDB

func NewPostgresDB(cfg config.DatabaseConfig, logger *logrus.Logger) (*PostgresDB, error)

NewPostgresDB creates a new PostgreSQL database connection with connection pooling.

func (*PostgresDB) Close

func (db *PostgresDB) Close() error

Close closes the database connection gracefully.

func (*PostgresDB) EnsureQueryable

func (db *PostgresDB) EnsureQueryable(tx *sqlx.Tx) Queryable

EnsureQueryable returns either the transaction or the database, implementing Queryable.

func (*PostgresDB) GetStats

func (db *PostgresDB) GetStats() DBStats

GetStats returns database statistics as a struct.

func (*PostgresDB) Health

func (db *PostgresDB) Health(ctx context.Context) error

Health checks the database health.

func (*PostgresDB) HealthCheck

func (db *PostgresDB) HealthCheck(ctx context.Context) (*HealthStatus, error)

HealthCheck performs a comprehensive health check.

func (*PostgresDB) RollbackMigration

func (db *PostgresDB) RollbackMigration(ctx context.Context) error

RollbackMigration rolls back the last migration.

func (*PostgresDB) RunMigrations

func (db *PostgresDB) RunMigrations(ctx context.Context) error

RunMigrations runs database migrations.

func (*PostgresDB) Stats

func (db *PostgresDB) Stats() sql.DBStats

Stats returns database pool statistics.

func (*PostgresDB) WithTransaction

func (db *PostgresDB) WithTransaction(ctx context.Context, fn func(tx *sqlx.Tx) error) error

WithTransaction executes a function within a transaction.

func (*PostgresDB) WithTransactionOptions

func (db *PostgresDB) WithTransactionOptions(ctx context.Context, opts *sql.TxOptions, fn func(tx *sqlx.Tx) error) error

WithTransactionOptions executes a function within a transaction with custom options.

type QueryBuilder

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

QueryBuilder helps build dynamic SQL queries safely.

func NewQueryBuilder

func NewQueryBuilder(baseQuery string) *QueryBuilder

NewQueryBuilder creates a new QueryBuilder.

func (*QueryBuilder) Build

func (qb *QueryBuilder) Build() (string, []interface{})

Build builds the final query and returns it with args.

func (*QueryBuilder) BuildCount

func (qb *QueryBuilder) BuildCount() (string, []interface{})

BuildCount builds a count query from the builder.

func (*QueryBuilder) Limit

func (qb *QueryBuilder) Limit(limit int) *QueryBuilder

Limit sets the LIMIT clause.

func (*QueryBuilder) Offset

func (qb *QueryBuilder) Offset(offset int) *QueryBuilder

Offset sets the OFFSET clause.

func (*QueryBuilder) OrderBy

func (qb *QueryBuilder) OrderBy(orderBy string) *QueryBuilder

OrderBy sets the ORDER BY clause.

func (*QueryBuilder) Paginate

func (qb *QueryBuilder) Paginate(p Pagination) *QueryBuilder

Paginate sets both LIMIT and OFFSET from pagination.

func (*QueryBuilder) Where

func (qb *QueryBuilder) Where(condition string, args ...interface{}) *QueryBuilder

Where adds a WHERE condition.

type Queryable

type Queryable interface {
	GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error
	SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error
	ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
	NamedExecContext(ctx context.Context, query string, arg interface{}) (sql.Result, error)
	QueryxContext(ctx context.Context, query string, args ...interface{}) (*sqlx.Rows, error)
}

Queryable interface for common query operations.

Jump to

Keyboard shortcuts

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