Documentation
¶
Overview ¶
Package database provides database connection and operations.
Index ¶
- Variables
- func IsDuplicateKeyError(err error) bool
- func IsForeignKeyError(err error) bool
- func IsNotFoundError(err error) bool
- func WrapError(err error, operation string) error
- type ConnectionStats
- type DBStats
- type HealthStatus
- type PaginatedResult
- type Pagination
- type PostgresDB
- func (db *PostgresDB) Close() error
- func (db *PostgresDB) EnsureQueryable(tx *sqlx.Tx) Queryable
- func (db *PostgresDB) GetStats() DBStats
- func (db *PostgresDB) Health(ctx context.Context) error
- func (db *PostgresDB) HealthCheck(ctx context.Context) (*HealthStatus, error)
- func (db *PostgresDB) RollbackMigration(ctx context.Context) error
- func (db *PostgresDB) RunMigrations(ctx context.Context) error
- func (db *PostgresDB) Stats() sql.DBStats
- func (db *PostgresDB) WithTransaction(ctx context.Context, fn func(tx *sqlx.Tx) error) error
- func (db *PostgresDB) WithTransactionOptions(ctx context.Context, opts *sql.TxOptions, fn func(tx *sqlx.Tx) error) error
- type QueryBuilder
- func (qb *QueryBuilder) Build() (string, []interface{})
- func (qb *QueryBuilder) BuildCount() (string, []interface{})
- func (qb *QueryBuilder) Limit(limit int) *QueryBuilder
- func (qb *QueryBuilder) Offset(offset int) *QueryBuilder
- func (qb *QueryBuilder) OrderBy(orderBy string) *QueryBuilder
- func (qb *QueryBuilder) Paginate(p Pagination) *QueryBuilder
- func (qb *QueryBuilder) Where(condition string, args ...interface{}) *QueryBuilder
- type Queryable
Constants ¶
This section is empty.
Variables ¶
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 ¶
IsDuplicateKeyError checks if an error is a duplicate key error.
func IsForeignKeyError ¶
IsForeignKeyError checks if an error is a foreign key error.
func IsNotFoundError ¶
IsNotFoundError checks if an error is a "not found" error.
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 ¶
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 ¶
WithTransaction executes a function within a transaction.
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.