database

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Sep 26, 2025 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package database provides cross-database query building utilities

Package database provides performance tracking for database operations

Index

Constants

View Source
const (
	PostgreSQL = types.PostgreSQL
	Oracle     = types.Oracle
	MongoDB    = types.MongoDB
)

Re-export database vendor identifiers so existing callers using the database package continue to compile while the single source of truth lives in types.

Variables

This section is empty.

Functions

func GetSupportedDatabaseTypes

func GetSupportedDatabaseTypes() []string

GetSupportedDatabaseTypes returns a list of supported database types

func NewTrackedConnection added in v0.2.0

func NewTrackedConnection(conn database.Interface, log logger.Logger, cfg *config.DatabaseConfig) database.Interface

NewTrackedConnection returns a database.Interface that wraps conn and records query/operation metrics and logs. The wrapper delegates all calls to the provided conn, uses conn.DatabaseType() as the vendor identifier, and derives per-connection tracking settings from cfg via newTrackingSettings.

func ValidateDatabaseType

func ValidateDatabaseType(dbType string) error

ValidateDatabaseType reports an error when dbType is not among the supported database types.

Types

type BasicStatement added in v0.2.0

type BasicStatement struct {
	*sql.Stmt
}

BasicStatement wraps sql.Stmt to implement database.Statement

func (*BasicStatement) Close added in v0.2.0

func (s *BasicStatement) Close() error

func (*BasicStatement) Exec added in v0.2.0

func (s *BasicStatement) Exec(ctx context.Context, args ...any) (sql.Result, error)

func (*BasicStatement) Query added in v0.2.0

func (s *BasicStatement) Query(ctx context.Context, args ...any) (*sql.Rows, error)

func (*BasicStatement) QueryRow added in v0.2.0

func (s *BasicStatement) QueryRow(ctx context.Context, args ...any) types.Row

type Connector added in v0.9.0

type Connector func(*config.DatabaseConfig, logger.Logger) (Interface, error)

Connector creates database connections from configuration

type DbManager added in v0.9.0

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

DbManager manages database connections by string keys. It provides lazy initialization, LRU eviction, and cleanup for database connections. The manager is key-agnostic - it doesn't know about tenants, just manages named connections.

func NewDbManager added in v0.9.0

func NewDbManager(resourceSource TenantStore, log logger.Logger, opts DbManagerOptions, connector Connector) *DbManager

NewDbManager creates a new database manager

func (*DbManager) Close added in v0.9.0

func (m *DbManager) Close() error

Close closes all database connections and stops cleanup

func (*DbManager) Get added in v0.9.0

func (m *DbManager) Get(ctx context.Context, key string) (Interface, error)

Get returns a database connection for the given key. For single-tenant, use key "". For multi-tenant, use the tenant ID. Connections are created lazily and cached with LRU eviction.

func (*DbManager) Size added in v0.9.0

func (m *DbManager) Size() int

Size returns the number of active connections

func (*DbManager) StartCleanup added in v0.9.0

func (m *DbManager) StartCleanup(interval time.Duration)

StartCleanup starts the background cleanup routine for idle connections

func (*DbManager) Stats added in v0.9.0

func (m *DbManager) Stats() map[string]any

Stats returns statistics about the connection pool

func (*DbManager) StopCleanup added in v0.9.0

func (m *DbManager) StopCleanup()

StopCleanup stops the background cleanup routine

type DbManagerOptions added in v0.9.0

type DbManagerOptions struct {
	MaxSize int           // Maximum number of connections to keep (0 = no limit)
	IdleTTL time.Duration // Time after which idle connections are cleaned up (0 = no cleanup)
}

DbManagerOptions configures the DbManager

type Interface

type Interface = types.Interface

Interface defines the common database operations supported by the framework. This type alias maintains backward compatibility while the actual interfaces are now defined in the database/types package to avoid import cycles.

func NewConnection

func NewConnection(cfg *config.DatabaseConfig, log logger.Logger) (Interface, error)

NewConnection creates a tracked database connection for the provided configuration. It returns an error when cfg is nil, cfg.Type is unsupported (supported: "postgresql", "oracle"), or driver initialization fails.

type QueryBuilder

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

QueryBuilder provides vendor-specific SQL query building

func NewQueryBuilder

func NewQueryBuilder(vendor string) *QueryBuilder

NewQueryBuilder creates a new query builder for the specified database vendor

func (*QueryBuilder) BuildBooleanValue

func (qb *QueryBuilder) BuildBooleanValue(value bool) any

BuildBooleanValue converts Go boolean to vendor-specific boolean representation

func (*QueryBuilder) BuildCaseInsensitiveLike

func (qb *QueryBuilder) BuildCaseInsensitiveLike(column, value string) squirrel.Sqlizer

BuildCaseInsensitiveLike creates a case-insensitive LIKE condition based on vendor

func (*QueryBuilder) BuildCurrentTimestamp

func (qb *QueryBuilder) BuildCurrentTimestamp() string

BuildCurrentTimestamp returns the current timestamp function for the vendor

func (*QueryBuilder) BuildLimitOffset

func (qb *QueryBuilder) BuildLimitOffset(query squirrel.SelectBuilder, limit, offset int) squirrel.SelectBuilder

BuildLimitOffset creates LIMIT/OFFSET clause based on vendor

func (*QueryBuilder) BuildUUIDGeneration

func (qb *QueryBuilder) BuildUUIDGeneration() string

BuildUUIDGeneration returns the UUID generation function for the vendor

func (*QueryBuilder) BuildUpsert

func (qb *QueryBuilder) BuildUpsert(table string, conflictColumns []string, insertColumns, updateColumns map[string]any) (query string, args []any, err error)

BuildUpsert creates an UPSERT/MERGE query based on vendor

func (*QueryBuilder) Delete

func (qb *QueryBuilder) Delete(table string) squirrel.DeleteBuilder

Delete creates a new DELETE query builder

func (*QueryBuilder) EscapeIdentifier

func (qb *QueryBuilder) EscapeIdentifier(identifier string) string

EscapeIdentifier escapes database identifiers (table names, column names) for the vendor

func (*QueryBuilder) Insert

func (qb *QueryBuilder) Insert(table string) squirrel.InsertBuilder

Insert creates a new INSERT query builder

func (*QueryBuilder) InsertWithColumns added in v0.3.0

func (qb *QueryBuilder) InsertWithColumns(table string, columns ...string) squirrel.InsertBuilder

InsertWithColumns creates an INSERT builder and applies vendor-specific quoting to the provided column list (e.g., quotes reserved words on Oracle).

func (*QueryBuilder) Select

func (qb *QueryBuilder) Select(columns ...string) squirrel.SelectBuilder

Select creates a new SELECT query builder

func (*QueryBuilder) Update

func (qb *QueryBuilder) Update(table string) squirrel.UpdateBuilder

Update creates a new UPDATE query builder

func (*QueryBuilder) Vendor

func (qb *QueryBuilder) Vendor() string

Vendor returns the database vendor

type QueryBuilderInterface added in v0.8.1

type QueryBuilderInterface = types.QueryBuilderInterface

QueryBuilderInterface defines the interface for vendor-specific SQL query building. This type alias maintains backward compatibility while enabling dependency injection.

type Statement added in v0.8.0

type Statement = types.Statement

Statement defines the interface for prepared statements. This type alias maintains backward compatibility.

type TenantStore added in v0.9.0

type TenantStore interface {
	// DBConfig returns the database configuration for the given key.
	// For single-tenant apps, key will be "". For multi-tenant, key will be the tenant ID.
	DBConfig(ctx context.Context, key string) (*config.DatabaseConfig, error)
}

TenantStore provides per-key database configurations. This interface abstracts where tenant-specific database configs come from.

type TrackedConnection added in v0.2.0

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

TrackedConnection wraps database.Interface to provide performance tracking

func (*TrackedConnection) Begin added in v0.2.0

func (tc *TrackedConnection) Begin(ctx context.Context) (database.Tx, error)

Begin starts a transaction with tracking wrapper

func (*TrackedConnection) BeginTx added in v0.2.0

func (tc *TrackedConnection) BeginTx(ctx context.Context, opts *sql.TxOptions) (database.Tx, error)

BeginTx starts a transaction with options and tracking wrapper

func (*TrackedConnection) Close added in v0.2.0

func (tc *TrackedConnection) Close() error

Close closes the database connection (no tracking needed)

func (*TrackedConnection) CreateMigrationTable added in v0.2.0

func (tc *TrackedConnection) CreateMigrationTable(ctx context.Context) error

CreateMigrationTable creates the migration table if it doesn't exist with tracking

func (*TrackedConnection) DatabaseType added in v0.2.0

func (tc *TrackedConnection) DatabaseType() string

DatabaseType returns the database type (no tracking needed)

func (*TrackedConnection) Exec added in v0.2.0

func (tc *TrackedConnection) Exec(ctx context.Context, query string, args ...any) (sql.Result, error)

Exec executes a query without returning any rows with tracking

func (*TrackedConnection) GetMigrationTable added in v0.2.0

func (tc *TrackedConnection) GetMigrationTable() string

GetMigrationTable returns the migration table name (no tracking needed)

func (*TrackedConnection) Health added in v0.2.0

func (tc *TrackedConnection) Health(ctx context.Context) error

Health checks database connectivity (no tracking needed)

func (*TrackedConnection) Prepare added in v0.2.0

func (tc *TrackedConnection) Prepare(ctx context.Context, query string) (database.Statement, error)

Prepare creates a prepared statement with tracking

func (*TrackedConnection) Query added in v0.2.0

func (tc *TrackedConnection) Query(ctx context.Context, query string, args ...any) (*sql.Rows, error)

Query executes a query that returns rows with tracking

func (*TrackedConnection) QueryRow added in v0.2.0

func (tc *TrackedConnection) QueryRow(ctx context.Context, query string, args ...any) types.Row

QueryRow executes a query that returns at most one row with tracking

func (*TrackedConnection) Stats added in v0.2.0

func (tc *TrackedConnection) Stats() (map[string]any, error)

Stats returns database connection statistics (no tracking needed)

type TrackedDB

type TrackedDB struct {
	*sql.DB
	// contains filtered or unexported fields
}

TrackedDB wraps sql.DB to provide request-scoped performance tracking

func NewTrackedDB

func NewTrackedDB(db *sql.DB, log logger.Logger, vendor string, cfg *config.DatabaseConfig) *TrackedDB

NewTrackedDB creates a TrackedDB that wraps the provided *sql.DB to record query and execution metrics (durations, truncated queries, optional parameter logging). It uses log for emitting structured logs, vendor to identify the database type, and derives per-connection tracking settings from cfg (when non-nil) to override defaults.

func (*TrackedDB) ExecContext

func (db *TrackedDB) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)

ExecContext executes a query without returning rows and tracks performance

func (*TrackedDB) PrepareContext

func (db *TrackedDB) PrepareContext(ctx context.Context, query string) (database.Statement, error)

PrepareContext prepares a statement with context and tracks performance

func (*TrackedDB) QueryContext

func (db *TrackedDB) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)

QueryContext executes a query with context and tracks performance

func (*TrackedDB) QueryRowContext

func (db *TrackedDB) QueryRowContext(ctx context.Context, query string, args ...any) types.Row

QueryRowContext executes a single row query with context and tracks performance

type TrackedStatement added in v0.2.0

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

TrackedStatement wraps database.Statement to provide performance tracking

func (*TrackedStatement) Close added in v0.2.0

func (ts *TrackedStatement) Close() error

Close closes the prepared statement (no tracking needed)

func (*TrackedStatement) Exec added in v0.2.0

func (ts *TrackedStatement) Exec(ctx context.Context, args ...any) (sql.Result, error)

Exec executes a prepared statement with tracking

func (*TrackedStatement) Query added in v0.2.0

func (ts *TrackedStatement) Query(ctx context.Context, args ...any) (*sql.Rows, error)

Query executes a prepared query with tracking

func (*TrackedStatement) QueryRow added in v0.2.0

func (ts *TrackedStatement) QueryRow(ctx context.Context, args ...any) types.Row

QueryRow executes a prepared query that returns a single row with tracking

type TrackedStmt

type TrackedStmt struct {
	database.Statement
	// contains filtered or unexported fields
}

TrackedStmt wraps database.Statement to provide performance tracking for prepared statements

func (*TrackedStmt) Exec added in v0.2.0

func (s *TrackedStmt) Exec(ctx context.Context, args ...any) (sql.Result, error)

Exec executes a prepared statement with context and tracks performance

func (*TrackedStmt) Query added in v0.2.0

func (s *TrackedStmt) Query(ctx context.Context, args ...any) (*sql.Rows, error)

Query executes a prepared query with context and tracks performance

func (*TrackedStmt) QueryRow added in v0.2.0

func (s *TrackedStmt) QueryRow(ctx context.Context, args ...any) types.Row

QueryRow executes a prepared single row query with context and tracks performance

type TrackedTransaction added in v0.2.0

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

TrackedTransaction wraps database.Tx to provide performance tracking

func (*TrackedTransaction) Commit added in v0.2.0

func (tt *TrackedTransaction) Commit() error

Commit commits the transaction (no tracking needed)

func (*TrackedTransaction) Exec added in v0.2.0

func (tt *TrackedTransaction) Exec(ctx context.Context, query string, args ...any) (sql.Result, error)

Exec executes a query without returning rows within the transaction with tracking

func (*TrackedTransaction) Prepare added in v0.2.0

func (tt *TrackedTransaction) Prepare(ctx context.Context, query string) (database.Statement, error)

Prepare creates a prepared statement within the transaction with tracking

func (*TrackedTransaction) Query added in v0.2.0

func (tt *TrackedTransaction) Query(ctx context.Context, query string, args ...any) (*sql.Rows, error)

Query executes a query within the transaction with tracking

func (*TrackedTransaction) QueryRow added in v0.2.0

func (tt *TrackedTransaction) QueryRow(ctx context.Context, query string, args ...any) types.Row

QueryRow executes a query that returns a single row within the transaction with tracking

func (*TrackedTransaction) Rollback added in v0.2.0

func (tt *TrackedTransaction) Rollback() error

Rollback rolls back the transaction (no tracking needed)

type TrackedTx

type TrackedTx struct {
	*sql.Tx
	// contains filtered or unexported fields
}

TrackedTx wraps sql.Tx to provide performance tracking for transactions

func (*TrackedTx) ExecContext

func (tx *TrackedTx) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)

ExecContext executes a query within a transaction and tracks performance

func (*TrackedTx) QueryContext

func (tx *TrackedTx) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)

QueryContext executes a query within a transaction with context and tracks performance

func (*TrackedTx) QueryRowContext

func (tx *TrackedTx) QueryRowContext(ctx context.Context, query string, args ...any) types.Row

QueryRowContext executes a single row query within a transaction and tracks performance

type TrackingContext added in v0.5.0

type TrackingContext struct {
	Logger   logger.Logger
	Vendor   string
	Settings trackingSettings
}

TrackingContext groups tracking-related parameters to reduce function parameter count

type Tx added in v0.8.0

type Tx = types.Tx

Tx defines the interface for database transactions. This type alias maintains backward compatibility.

Directories

Path Synopsis
internal
builder
Package builder provides cross-database query building utilities.
Package builder provides cross-database query building utilities.
mocks
Package mocks provides shared mock implementations for testing database components.
Package mocks provides shared mock implementations for testing database components.
tracking
Package tracking provides performance tracking for database operations.
Package tracking provides performance tracking for database operations.
Package types contains the core database interface definitions for go-bricks.
Package types contains the core database interface definitions for go-bricks.

Jump to

Keyboard shortcuts

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