Help us shape the future of Go! Take the 2026 Go Developer Survey

dbcore

package
v1.11.9 Latest Latest
Warning

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

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

Documentation

Overview

Package dbcore provides PostgreSQL and SQLite clients, transactions, migrations, typed queries, ORM conveniences, and stable database error classification. Applications own schema design, SQL review, and recovery.

Index

Constants

This section is empty.

Variables

View Source
var ErrEphemeralCapacity = errors.New("dbcore/ephemeral: session capacity reached")

ErrEphemeralCapacity indicates that the process-local session bound was reached.

View Source
var ErrEphemeralResultTooLarge = errors.New("dbcore/ephemeral: materialized result is too large")

ErrEphemeralResultTooLarge indicates that a materialization exceeded its memory safety bound.

Functions

func AnalyzeQuery

func AnalyzeQuery(sql string) []string

AnalyzeQuery inspects SQL text and produces actionable performance suggestions.

func AutoMigrate

func AutoMigrate(ctx context.Context, database MigrationDatabase, migrations ...Migration) error

AutoMigrate validates and transactionally applies ordered migrations. A PostgreSQL advisory transaction lock and SQLite write transaction serialize concurrent application starts.

func AutoMigrateModel added in v1.11.9

func AutoMigrateModel(ctx context.Context, client *Client, model any) error

AutoMigrateModel creates a database table automatically for any struct model instance or pointer.

func ClassifyError

func ClassifyError(err error) error

ClassifyError maps SQLite and PostgreSQL failures without exposing raw driver text. Nil and sql.ErrNoRows are returned unchanged.

func GenerateFingerprint

func GenerateFingerprint(sql string) string

GenerateFingerprint sanitizes SQL by replacing literal values and parameters with placeholder tokens.

func GetCacheTTL

func GetCacheTTL(ctx context.Context) (time.Duration, bool)

GetCacheTTL returns the query-cache lifetime attached to ctx.

func GetQueryName

func GetQueryName(ctx context.Context) string

GetQueryName extracts the query name attached to the context, or returns "unnamed".

func IsErrorKind

func IsErrorKind(err error, kind ErrorKind) bool

IsErrorKind reports whether err contains a DatabaseError with kind.

func LogSlowQuery

func LogSlowQuery(ctx context.Context, cfg SlowQueryConfig, role, operation, sql string, duration time.Duration, argsCount int, err error)

LogSlowQuery logs a slow query event to slog without logging bind arguments (PII protection).

func Migrate

func Migrate(ctx context.Context, database MigrationDatabase, migrations []Migration) error

Migrate applies validated migrations in version order.

func MigrateEmbed

func MigrateEmbed(ctx context.Context, database MigrationDatabase, embedFS fs.FS, dir string) error

MigrateEmbed loads versioned SQL files from embedFS and applies them in order.

func PaginateSession

func PaginateSession(ctx context.Context, client *Client, sessionID string, page, limit int) ([]string, int, error)

PaginateSession queries an ephemeral session table with O(1) indexed page lookup.

func PaginateSessionTyped

func PaginateSessionTyped[T any](ctx context.Context, client *Client, sessionID string, page, limit int) ([]T, int, error)

PaginateSessionTyped queries an ephemeral session table and unmarshals row JSON into typed structs []T.

func QueryPaginated

func QueryPaginated[T any](ctx context.Context, client *Client, baseQuery string, page, limit int, args ...any) ([]T, int, error)

QueryPaginated executes a raw SQL query with limit/offset pagination and returns results with total row count.

func QueryRowTyped

func QueryRowTyped[T any](ctx context.Context, client *Client, query string, args ...any) (*T, error)

QueryRowTyped executes a raw SQL query and maps a single matching row into *T.

func QueryTyped

func QueryTyped[T any](ctx context.Context, client *Client, query string, args ...any) ([]T, error)

QueryTyped executes a raw SQL query and automatically maps matching rows into []T without manual scanning loops.

func WithCache

func WithCache(ctx context.Context, ttl time.Duration) context.Context

WithCache annotates ctx with a requested query-cache lifetime.

func WithQueryName

func WithQueryName(ctx context.Context, name string) context.Context

WithQueryName attaches a readable application query name to the context for dashboards and slow query logs.

Types

type Client

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

Client owns PostgreSQL primary/replica pools. For backwards compatibility, NewClient also accepts the explicit SQLite test DSNs ":memory:" and "file:".

func NewClient

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

NewClient opens the configured database. PostgreSQL is selected for postgres:// and postgresql:// DSNs. Explicit SQLite memory/file DSNs are retained for test compatibility; applications should prefer OpenSQLite.

func NewPostgresClient

func NewPostgresClient(ctx context.Context, cfg Config) (*Client, error)

NewPostgresClient opens and verifies real PostgreSQL primary and optional replica pools. It never falls back to an in-memory database.

func (*Client) BeginTx

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

BeginTx begins a transaction on the primary pool.

func (*Client) Close

func (c *Client) Close() error

Close releases owned database pools once.

func (*Client) DB

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

DB returns the primary read-write database pool.

func (*Client) Dialect

func (c *Client) Dialect() string

Dialect returns the configured SQL dialect.

func (*Client) Exec

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

Exec executes a write statement against the primary pool.

func (*Client) ExecContext

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

ExecContext implements context-aware SQL execution against the primary pool.

func (*Client) ExecIdempotent

func (c *Client) ExecIdempotent(ctx context.Context, query string, args ...any) (sql.Result, error)

ExecIdempotent executes caller-defined idempotent SQL against the primary pool.

func (*Client) InTx

func (c *Client) InTx(ctx context.Context, fn func(*sql.Tx) error) (err error)

InTx commits fn on success and rolls back on failure.

func (*Client) ParallelQuery

func (c *Client) ParallelQuery(ctx context.Context, tasks ...ParallelTask) error

ParallelQuery executes independent queries concurrently and returns an observed error.

func (*Client) PingContext

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

PingContext verifies primary database connectivity.

func (*Client) Query

func (c *Client) Query(ctx context.Context, query string, fn func(*sql.Rows) error, args ...any) error

Query executes a read query, invokes fn, and closes the returned rows.

func (*Client) QueryContext

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

QueryContext implements context-aware querying against the read pool.

func (*Client) QueryRow

func (c *Client) QueryRow(ctx context.Context, query string, fn func(*sql.Row) error, args ...any) error

QueryRow executes one read query and passes its row to fn.

func (*Client) QueryRowContext

func (c *Client) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row

QueryRowContext returns one row from the read pool.

func (*Client) ReadDB

func (c *Client) ReadDB() *sql.DB

ReadDB returns the read pool, which may be the primary when no replica exists.

func (*Client) Stats

func (c *Client) Stats() map[string]any

Stats returns redacted primary and replica pool health and utilization.

type Config

type Config struct {
	RWDSN                    string
	RODSN                    string
	PgBouncerTransactionMode bool
	MaxOpenConnections       int
	MaxIdleConnections       int
	ConnectionMaxLifetime    time.Duration
	ConnectionMaxIdleTime    time.Duration
	PingTimeout              time.Duration
	SlowQuery                SlowQueryConfig
}

Config defines PostgreSQL primary/replica connection and pool parameters. RWDSN is required. RODSN is optional; reads use the primary when it is empty.

type CursorResult

type CursorResult[T any] struct {
	Items      []T    `json:"items"`
	NextCursor string `json:"next_cursor"`
	HasMore    bool   `json:"has_more"`
	Limit      int    `json:"limit"`
}

CursorResult represents cursor-based pagination results for O(1) high-performance query execution.

type DatabaseError

type DatabaseError struct {
	Kind ErrorKind
	// contains filtered or unexported fields
}

DatabaseError provides a stable category while retaining the driver error.

func (*DatabaseError) Error

func (e *DatabaseError) Error() string

Error returns the stable database error message.

func (*DatabaseError) Unwrap

func (e *DatabaseError) Unwrap() error

Unwrap returns the driver or standard-library cause.

type EphemeralManager

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

EphemeralManager tracks bounded process-local materialization sessions.

type EphemeralSession

type EphemeralSession struct {
	SessionID string    `json:"session_id"`
	TableName string    `json:"table_name"`
	TotalRows int       `json:"total_rows"`
	ExpiresAt time.Time `json:"expires_at"`
}

EphemeralSession holds metadata for a materialized pagination temporary table.

func MaterializeHistoryPagination

func MaterializeHistoryPagination(ctx context.Context, client *Client, historyQuery string, ttl time.Duration, args ...any) (*EphemeralSession, error)

MaterializeHistoryPagination creates an immutable snapshot table tailored for historical data tables (audit logs, historical sales, past reports).

func MaterializePagination

func MaterializePagination(ctx context.Context, client *Client, query string, ttl time.Duration, args ...any) (*EphemeralSession, error)

MaterializePagination executes a query, creates a temporary session table gpp_tmp_page_<session_id>, populates it, and returns an EphemeralSession.

type ErrorKind

type ErrorKind string

ErrorKind is a stable category for database failures.

const (
	// ErrorUniqueConstraint indicates a uniqueness violation.
	ErrorUniqueConstraint ErrorKind = "unique_constraint"
	// ErrorForeignKeyConstraint indicates a foreign-key violation.
	ErrorForeignKeyConstraint ErrorKind = "foreign_key_constraint"
	// ErrorNotNullConstraint indicates a required-column violation.
	ErrorNotNullConstraint ErrorKind = "not_null_constraint"
	// ErrorCheckConstraint indicates a check-constraint violation.
	ErrorCheckConstraint ErrorKind = "check_constraint"
	// ErrorBusy indicates database lock or busy contention.
	ErrorBusy ErrorKind = "busy_or_locked"
	// ErrorCanceled indicates cancellation or deadline expiry.
	ErrorCanceled ErrorKind = "query_canceled"
	// ErrorUnknown indicates an unclassified database failure.
	ErrorUnknown ErrorKind = "unknown"
)

type Migration

type Migration struct {
	ID      string
	Version int
	Name    string
	SQL     string
	UpSQL   string
	DownSQL string
}

Migration is one immutable, checksummed schema transition.

type MigrationDatabase

type MigrationDatabase interface {
	BeginTx(context.Context, *sql.TxOptions) (*sql.Tx, error)
	Dialect() string
}

MigrationDatabase is the minimal database/sql seam required by migrations.

type ORM

type ORM[T any] struct {
	// contains filtered or unexported fields
}

ORM provides a zero-SQL high-performance object-relational mapping engine.

func NewORM

func NewORM[T any](client *Client, tableName ...string) *ORM[T]

NewORM initializes an ORM instance for type T.

func (*ORM[T]) AutoMigrate

func (o *ORM[T]) AutoMigrate(ctx context.Context) error

AutoMigrate creates the database table automatically if it does not exist based on struct fields. Supports full SQL type mapping: SMALLINT, INTEGER, BIGINT, REAL, DOUBLE PRECISION, BOOLEAN, TIMESTAMP, TEXT.

func (*ORM[T]) Delete

func (o *ORM[T]) Delete(ctx context.Context, entity *T) error

Delete removes an entity from the database by primary key.

func (*ORM[T]) DeleteByID added in v1.11.9

func (o *ORM[T]) DeleteByID(ctx context.Context, id any) error

DeleteByID removes a record from the database by primary key ID.

func (*ORM[T]) Find

func (o *ORM[T]) Find(ctx context.Context) ([]T, error)

Find executes the ORM query and returns a slice of matching entities.

func (*ORM[T]) FindByID

func (o *ORM[T]) FindByID(ctx context.Context, id any) (*T, error)

FindByID retrieves an entity by primary key ID.

func (*ORM[T]) OrderBy

func (o *ORM[T]) OrderBy(clause string) *ORM[T]

OrderBy sets the query sort order.

func (*ORM[T]) Paginate

func (o *ORM[T]) Paginate(ctx context.Context, page, limit int) ([]T, int, error)

Paginate executes a paginated query returning entities and total count in 1 call.

func (*ORM[T]) Save

func (o *ORM[T]) Save(ctx context.Context, entity *T) error

Save inserts a new record or updates an existing record based on primary key.

func (*ORM[T]) Where

func (o *ORM[T]) Where(field string, val any) *ORM[T]

Where adds a parameterized filter condition (100% SQL Injection Proof).

type ParallelTask

type ParallelTask struct {
	QueryName string
	SQL       string
	Args      []any
}

ParallelTask describes one named SQL query for ParallelQuery.

type Repository

type Repository[T any] struct {
	// contains filtered or unexported fields
}

Repository provides type-safe generic CRUD operations for database tables.

func NewRepository

func NewRepository[T any](client *Client, tableName string) *Repository[T]

NewRepository creates a new generic Repository instance.

func (*Repository[T]) Create

func (r *Repository[T]) Create(ctx context.Context, entity *T) error

Create inserts a new record entity into the table.

func (*Repository[T]) Delete

func (r *Repository[T]) Delete(ctx context.Context, id any) error

Delete removes a record by primary key ID.

func (*Repository[T]) FindAll

func (r *Repository[T]) FindAll(ctx context.Context, whereClause string, args ...any) ([]T, error)

FindAll retrieves records matching a custom WHERE condition.

func (*Repository[T]) FindByID

func (r *Repository[T]) FindByID(ctx context.Context, id any) (*T, error)

FindByID retrieves a record by primary key ID.

func (*Repository[T]) Paginate

func (r *Repository[T]) Paginate(ctx context.Context, page, limit int) ([]T, int, error)

Paginate retrieves a paginated window of records along with total count.

func (*Repository[T]) PaginateCursor

func (r *Repository[T]) PaginateCursor(ctx context.Context, cursorColumn string, cursorVal any, limit int) (*CursorResult[T], error)

PaginateCursor performs high-efficiency O(1) cursor pagination (e.g. WHERE id > cursor ORDER BY id ASC LIMIT limit + 1).

func (*Repository[T]) TableName

func (r *Repository[T]) TableName() string

TableName returns the configured table name for the repository.

func (*Repository[T]) Update

func (r *Repository[T]) Update(ctx context.Context, id any, entity *T) error

Update updates an existing record matching ID.

type SQLiteClient

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

SQLiteClient owns a real database/sql SQLite pool.

func NewSQLiteClient

func NewSQLiteClient(dbPath string) (*SQLiteClient, error)

NewSQLiteClient preserves the historical constructor with deterministic defaults. New code should use OpenSQLite for explicit configuration.

func OpenSQLite

func OpenSQLite(ctx context.Context, cfg SQLiteConfig) (*SQLiteClient, error)

OpenSQLite validates, opens, configures, and pings a pure-Go SQLite database.

func (*SQLiteClient) BeginTx

func (s *SQLiteClient) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)

BeginTx begins a SQLite transaction.

func (*SQLiteClient) Close

func (s *SQLiteClient) Close() error

Close releases the SQLite database pool.

func (*SQLiteClient) DB

func (s *SQLiteClient) DB() *sql.DB

DB returns the underlying SQLite database pool.

func (*SQLiteClient) Dialect

func (s *SQLiteClient) Dialect() string

Dialect returns sqlite.

func (*SQLiteClient) Exec

func (s *SQLiteClient) Exec(ctx context.Context, query string, args ...any) error

Exec preserves the legacy error-only signature while executing real SQL.

func (*SQLiteClient) ExecContext

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

ExecContext executes a write statement and classifies failures.

func (*SQLiteClient) InTx

func (s *SQLiteClient) InTx(ctx context.Context, fn func(*sql.Tx) error) error

InTx commits fn on success and rolls back on failure.

func (*SQLiteClient) PingContext

func (s *SQLiteClient) PingContext(ctx context.Context) error

PingContext verifies SQLite connectivity.

func (*SQLiteClient) QueryContext

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

QueryContext executes a query and classifies startup failures.

func (*SQLiteClient) QueryRowContext

func (s *SQLiteClient) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row

QueryRowContext returns one SQLite query row.

func (*SQLiteClient) Stats

func (s *SQLiteClient) Stats() sql.DBStats

Stats returns SQLite pool statistics.

type SQLiteConfig

type SQLiteConfig struct {
	Path                  string
	DSN                   string
	DirectoryMode         os.FileMode
	BusyTimeout           time.Duration
	ForeignKeys           *bool
	MaxOpenConnections    int
	MaxIdleConnections    int
	ConnectionMaxLifetime time.Duration
	ConnectionMaxIdleTime time.Duration
	ReadOnly              bool
	InMemory              bool
	PingTimeout           time.Duration
	SlowQuery             SlowQueryConfig
}

SQLiteConfig is validated before the database is opened. Path and DSN are mutually exclusive. InMemory must be explicitly selected for a memory DB.

type SlowQueryConfig

type SlowQueryConfig struct {
	Threshold    time.Duration
	MaxSQLLength int
	OmitSQL      bool
}

SlowQueryConfig configures slow query thresholds, logging, and rules advisor settings.

func DefaultSlowQueryConfig

func DefaultSlowQueryConfig() SlowQueryConfig

DefaultSlowQueryConfig returns standard slow query logging parameters.

type SlowQueryEvent

type SlowQueryEvent struct {
	Role        string   `json:"role"`
	Operation   string   `json:"operation"`
	QueryName   string   `json:"query_name"`
	DurationMS  int64    `json:"duration_ms"`
	ThresholdMS int64    `json:"threshold_ms"`
	Fingerprint string   `json:"fingerprint"`
	ArgsCount   int      `json:"args_count"`
	SQL         string   `json:"sql,omitempty"`
	Suggestions []string `json:"suggestions"`
	Error       string   `json:"error,omitempty"`
}

SlowQueryEvent represents a structured log event generated when a query exceeds the configured duration threshold.

Directories

Path Synopsis
Package seed provides development and test data generation.
Package seed provides development and test data generation.

Jump to

Keyboard shortcuts

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