database

package
v0.0.0-...-d80aada Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2025 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package database provides database access layer.

WHY: Separate database package because: 1. Database concerns (pooling, transactions) are orthogonal to business logic 2. sqlc generated code needs a stable home independent of domain changes 3. Connection lifecycle management requires centralized control 4. Testing requires ability to swap real database for test fixtures

Package database provides database connection and management functionality. Uses pgx as PostgreSQL driver with pgvector extension support.

WHY: pgx chosen over database/sql because: 1. Native PostgreSQL protocol implementation is 3x faster 2. Built-in connection pooling with better control 3. Native support for PostgreSQL-specific types (arrays, JSONB) 4. pgvector extension requires custom type handling

Package database code generation directives

Index

Constants

View Source
const (
	// MaxInt32 safe conversion limit
	MaxInt32 = 2147483647

	// DefaultBatchSize for batch operations
	DefaultBatchSize = 100

	// MaxMemoriesPerQuery to prevent overload
	MaxMemoriesPerQuery = 1000

	// MinMemoriesForConsolidation threshold
	MinMemoriesForConsolidation = 50
)

Database constants

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

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

Client provides unified database access.

WHY: Client wrapper pattern because: 1. sqlc.Queries alone doesn't manage connection lifecycle 2. Transaction coordination requires access to underlying pool 3. Metrics and logging need centralized interception point 4. Future sharding/read replicas need abstraction layer

func NewClient

func NewClient(ctx context.Context, config *Config) (*Client, error)

NewClient creates a new database client with connection pool

func (*Client) Close

func (c *Client) Close()

Close closes the database connection pool Note: pgxpool.Pool.Close() doesn't return an error in pgx v5

func (*Client) DB

func (c *Client) DB() *DB

DB returns the underlying database connection pool

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) error

Ping checks database connection

func (*Client) Pool

func (c *Client) Pool() *pgxpool.Pool

Pool returns the connection pool

func (*Client) Queries

func (c *Client) Queries() sqlc.Querier

Queries returns the sqlc query interface

func (*Client) RunMigrations

func (c *Client) RunMigrations() error

RunMigrations executes database migrations

func (*Client) WithTx

func (c *Client) WithTx(ctx context.Context, fn func(sqlc.Querier) error) error

WithTx executes a function within a transaction Automatically handles commit and rollback

type Config

type Config struct {
	// DSN is the database connection string
	DSN string
	// MaxConns limits concurrent database connections
	MaxConns int32
	// MinConns maintains minimum idle connections
	MinConns int32
	// MaxConnLifetime prevents connection staleness
	MaxConnLifetime time.Duration
	// MaxConnIdleTime closes idle connections
	MaxConnIdleTime time.Duration
	// HealthCheckPeriod defines how often to verify connections
	HealthCheckPeriod time.Duration
}

Config defines database connection parameters

type DB

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

DB wraps the database connection pool.

WHY: Wrapper pattern because: 1. Abstracts pgx-specific details from business logic 2. Centralizes connection lifecycle management 3. Provides hook points for metrics and logging 4. Enables mock implementations for testing

func NewDB

func NewDB(ctx context.Context, config *Config, opts ...DBOption) (*DB, error)

NewDB creates a new database connection pool. Automatically configures pool parameters and validates connectivity.

WHY: Constructor validates immediately because: 1. Fail fast on configuration errors 2. Prevents runtime connection failures 3. Database is required dependency - no graceful degradation

func (*DB) Acquire

func (db *DB) Acquire(ctx context.Context) (*pgxpool.Conn, error)

Acquire obtains a database connection from the pool. Must be released after use to avoid connection leaks

func (*DB) Begin

func (db *DB) Begin(ctx context.Context) (pgx.Tx, error)

Begin starts a new database transaction

func (*DB) BeginTx

func (db *DB) BeginTx(ctx context.Context, txOptions pgx.TxOptions) (pgx.Tx, error)

BeginTx starts a transaction with custom options

func (*DB) Close

func (db *DB) Close()

Close gracefully shuts down the connection pool

func (*DB) Exec

func (db *DB) Exec(ctx context.Context, sql string, args ...any) (pgx.Rows, error)

Exec executes a query without returning results

func (*DB) Ping

func (db *DB) Ping(ctx context.Context) error

Ping verifies database connectivity

func (*DB) Pool

func (db *DB) Pool() *pgxpool.Pool

Pool returns the underlying connection pool. Use only when direct pool access is required

func (*DB) Query

func (db *DB) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)

Query executes a query and returns the result set

func (*DB) QueryRow

func (db *DB) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row

QueryRow executes a query and returns a single row

func (*DB) RunMigration

func (db *DB) RunMigration(ctx context.Context, migration string) error

RunMigration executes a database migration. Runs the specified SQL script within a transaction

func (*DB) RunMigrations

func (db *DB) RunMigrations() error

RunMigrations runs database migrations using golang-migrate

func (*DB) Stats

func (db *DB) Stats() *pgxpool.Stat

Stats returns connection pool statistics

func (*DB) WithTx

func (db *DB) WithTx(ctx context.Context, fn func(pgx.Tx) error) error

WithTx executes a function within a transaction. Automatically handles commit and rollback.

WHY: Transaction helper because: 1. Ensures transactions are always closed 2. Consistent error handling pattern 3. Panic recovery prevents connection leaks 4. Reduces boilerplate in business logic

type DBOption

type DBOption func(*DB)

DBOption configures a DB instance

func WithLogger

func WithLogger(log logger.Logger) DBOption

WithLogger sets a custom logger for the database

Directories

Path Synopsis
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.

Jump to

Keyboard shortcuts

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