sqldb

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: May 19, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package sqldb provides the core foundation for SQL database interactions within the mmo-game architecture.

It includes functionality for:

  • Connection management (pooling, health checks) via Configurable DSN parameters
  • Transaction management (Begin, Commit, Rollback, context propagation)
  • Prepared statement registry for performance optimization
  • High-performance connection pool configuration presets

The package is designed to work with the "database/sql" standard library and provides a "DBClient" wrapper to extend functionality with project-specific patterns.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConfigureDefaultPool

func ConfigureDefaultPool(db *sql.DB)

ConfigureDefaultPool applies default pool configuration

func ConfigureHighConcurrencyPool

func ConfigureHighConcurrencyPool(db *sql.DB)

ConfigureHighConcurrencyPool applies high-concurrency pool configuration

func ConfigurePool

func ConfigurePool(db *sql.DB, opts ...PoolOption)

ConfigurePool applies pool options to a database connection

func Connect

func Connect(connURL *url.URL) (*sql.DB, error)

Connect establishes a connection to a sql.DB using the given DSN URL.

func FxModule

func FxModule(driverType DriverType, options ...ConnectionDSNOption) fx.Option

func InjectTx

func InjectTx(ctx context.Context, tx *sql.Tx) context.Context

InjectTx injects SQL transaction into context If transaction already exists in context, returns context as-is (allows nested transactions)

func MustConnectWithDSN

func MustConnectWithDSN(dsn *url.URL) *sql.DB

MustConnectWithDSN ensures a connection to a *sql.DB with the given dsn url, else it panics.

func MustGenerateDSN

func MustGenerateDSN(driverType DriverType, options ...ConnectionDSNOption) *url.URL

MustGenerateDSN generates a DSN URL or panics if an error occurs. This is useful for initialization code where errors should be fatal.

func NewDSN

func NewDSN(driverType DriverType, options ...ConnectionDSNOption) (*url.URL, error)

NewDSN generates a DSN (Data Source Name) URL for database connections.

By default, it reads connection parameters from environment variables:

  • DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASSWORD, DB_SSL

These defaults can be overridden by passing specific ConnectionDSNOption functions.

Example:

dsn, err := NewDSN(
    DriverTypePostgres,
    WithConnHost("localhost"),
    WithConnPort("5432"),
)

func NewErrEmptyDBConnection

func NewErrEmptyDBConnection() error

func NewTransactioner

func NewTransactioner(db *sql.DB) persistence.Transactioner

NewTransactioner creates a new SQL transactioner

Types

type Client

type Client interface {
	DatabaseProvider
	io.Closer
	Pinger
	ContextAwarePinger
}

Client defines the contract of a client to interact with a sql database.

type ConnectionDSNOption

type ConnectionDSNOption func(dsn) error

ConnectionDSNOption defines the contract for the options being applied to the DSN.

func WithConnDBName

func WithConnDBName(dbName string) ConnectionDSNOption

WithConnDBName sets the database name in the DSN.

func WithConnHost

func WithConnHost(host string) ConnectionDSNOption

WithConnHost sets the database host in the DSN.

func WithConnPort

func WithConnPort(port string) ConnectionDSNOption

WithConnPort sets the database port in the DSN.

func WithConnPwd

func WithConnPwd(pwd string) ConnectionDSNOption

WithConnPwd sets the database password in the DSN.

func WithConnSSLMode

func WithConnSSLMode(sslMode string) ConnectionDSNOption

WithConnSSLMode sets the SSL mode in the DSN (e.g., "disable", "require", "verify-full").

func WithConnSearchPath

func WithConnSearchPath(searchPath string) ConnectionDSNOption

WithConnSearchPath sets the PostgreSQL search_path in the DSN. This is useful for multi-schema databases where you want to set a default schema.

func WithConnUser

func WithConnUser(user string) ConnectionDSNOption

WithConnUser sets the database user in the DSN.

func WithDSNConnFromEnv

func WithDSNConnFromEnv() ConnectionDSNOption

WithDSNConnFromEnv loads all DSN parameters from environment variables. This is the default option applied when calling NewDSN.

Environment variables read:

  • DB_HOST: Database host
  • DB_PORT: Database port
  • DB_NAME: Database name
  • DB_USER: Database user
  • DB_PASSWORD: Database password
  • DB_SSL: SSL mode

type ConnectionOption

type ConnectionOption func(db *sql.DB) error

ConnectionOption defines the contract for options applied to a sql.DB.

func WithDBSchema

func WithDBSchema(schema string) ConnectionOption

WithDBSchema sets the database schema search path for PostgreSQL. The schema is added to the search path along with 'public'. If schema is empty or whitespace, this option does nothing.

func WithDBSchemaFromEnv

func WithDBSchemaFromEnv() ConnectionOption

WithDBSchemaFromEnv sets the database schema by reading the DB_SCHEMA environment variable.

func WithMaxIdleConns

func WithMaxIdleConns(limit int) ConnectionOption

WithMaxIdleConns sets the maximum number of idle connections in the pool. If limit is <= 0, it is ignored.

func WithMaxOpenLimit

func WithMaxOpenLimit(limit int) ConnectionOption

WithMaxOpenLimit sets the maximum number of open connections to the database. If limit is <= 0, it is ignored.

type ContextAwarePinger

type ContextAwarePinger interface {
	PingContext(context.Context) error
}

ContextAwarePinger defines the contract to ping a database with the given context (helpful for healthchecking purposes).

type DBClient

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

DBClient wraps a *sql.DB and provides additional functionality

func NewDBClient

func NewDBClient(db *sql.DB) *DBClient

NewDBClient creates a new DBClient from a *sql.DB

func (*DBClient) Begin

func (c *DBClient) Begin(ctx context.Context) (*sql.Tx, error)

Begin starts a new transaction with default options.

func (*DBClient) BeginTx

func (c *DBClient) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)

BeginTx starts a new transaction with the given options.

func (*DBClient) Close

func (c *DBClient) Close() error

Close closes the database connection.

func (*DBClient) DB

func (c *DBClient) DB() *sql.DB

DB returns the underlying *sql.DB

func (*DBClient) Exec

func (c *DBClient) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

Exec executes a query without returning rows

func (*DBClient) Ping

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

Ping verifies the connection is alive

func (*DBClient) Query

func (c *DBClient) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

Query executes a query that returns rows

func (*DBClient) QueryRow

func (c *DBClient) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row

QueryRow executes a query that returns at most one row

type DatabaseProvider

type DatabaseProvider interface {
	Database() (*sql.DB, error)
}

DatabaseProvider defines the contract to retrieve the sql.DB handle.

type DriverType

type DriverType string

DriverType defines the kind of database.

const (
	// DriverTypePostgres defines postgres as the driver type being used to connect to the database.
	DriverTypePostgres DriverType = "postgres"
)

type Pinger

type Pinger interface {
	Ping() error
}

Pinger defines the contract to ping a database (helpful for healthchecking purposes).

type PoolOption

type PoolOption func(*sql.DB)

PoolOption defines a functional option for configuring connection pool

func DefaultPoolOptions

func DefaultPoolOptions() []PoolOption

DefaultPoolOptions returns recommended defaults for production

func HighConcurrencyPoolOptions

func HighConcurrencyPoolOptions() []PoolOption

HighConcurrencyPoolOptions returns settings optimized for high-concurrency workloads (MMO servers)

func WithPoolConnMaxIdleTime

func WithPoolConnMaxIdleTime(d time.Duration) PoolOption

WithPoolConnMaxIdleTime sets the maximum amount of time a connection may be idle. Expired connections may be closed lazily before reuse. If d <= 0, connections are not closed due to a connection's idle time.

func WithPoolConnMaxLifetime

func WithPoolConnMaxLifetime(d time.Duration) PoolOption

WithPoolConnMaxLifetime sets the maximum amount of time a connection may be reused. Expired connections may be closed lazily before reuse. If d <= 0, connections are not closed due to a connection's age.

func WithPoolMaxIdleConns

func WithPoolMaxIdleConns(n int) PoolOption

WithPoolMaxIdleConns sets the maximum number of connections in the idle connection pool. If n <= 0, no idle connections are retained.

func WithPoolMaxOpenConns

func WithPoolMaxOpenConns(n int) PoolOption

WithPoolMaxOpenConns sets the maximum number of open connections to the database. If n <= 0, then there is no limit on the number of open connections.

type Querier

type Querier interface {
	PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
	QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
	ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
}

Querier interface that both *sql.DB and *sql.Tx implement This allows repositories to work with either the main DB or a transaction

func GetTx

func GetTx(ctx context.Context, db *sql.DB) Querier

GetTx returns the appropriate querier from context Returns transaction if in txCtx, otherwise returns the regular DB This is the key helper that repositories use to automatically participate in transactions

type Registry

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

Registry manages prepared statements for performance

func NewRegistry

func NewRegistry(db *sql.DB) *Registry

NewRegistry creates a new statement registry

func (*Registry) Close

func (r *Registry) Close() error

Close closes all prepared statements

func (*Registry) Count

func (r *Registry) Count() int

Count returns the number of registered statements

func (*Registry) Get

func (r *Registry) Get(id StatementID) (*sql.Stmt, error)

Get retrieves a prepared statement by ID

func (*Registry) MustGet

func (r *Registry) MustGet(id StatementID) *sql.Stmt

MustGet retrieves a statement and panics if not found

func (*Registry) MustRegister

func (r *Registry) MustRegister(ctx context.Context, id StatementID, query string)

MustRegister registers a statement and panics on error (useful for init)

func (*Registry) Register

func (r *Registry) Register(ctx context.Context, id StatementID, query string) error

Register prepares and caches a statement

type StatementID

type StatementID string

StatementID uniquely identifies a prepared statement

Jump to

Keyboard shortcuts

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