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 ¶
- Variables
- func AnalyzeQuery(sql string) []string
- func AutoMigrate(ctx context.Context, database MigrationDatabase, migrations ...Migration) error
- func AutoMigrateModel(ctx context.Context, client *Client, model any) error
- func ClassifyError(err error) error
- func GenerateFingerprint(sql string) string
- func GetCacheTTL(ctx context.Context) (time.Duration, bool)
- func GetQueryName(ctx context.Context) string
- func IsErrorKind(err error, kind ErrorKind) bool
- func LogSlowQuery(ctx context.Context, cfg SlowQueryConfig, role, operation, sql string, ...)
- func Migrate(ctx context.Context, database MigrationDatabase, migrations []Migration) error
- func MigrateEmbed(ctx context.Context, database MigrationDatabase, embedFS fs.FS, dir string) error
- func PaginateSession(ctx context.Context, client *Client, sessionID string, page, limit int) ([]string, int, error)
- func PaginateSessionTyped[T any](ctx context.Context, client *Client, sessionID string, page, limit int) ([]T, int, error)
- func QueryPaginated[T any](ctx context.Context, client *Client, baseQuery string, page, limit int, ...) ([]T, int, error)
- func QueryRowTyped[T any](ctx context.Context, client *Client, query string, args ...any) (*T, error)
- func QueryTyped[T any](ctx context.Context, client *Client, query string, args ...any) ([]T, error)
- func WithCache(ctx context.Context, ttl time.Duration) context.Context
- func WithQueryName(ctx context.Context, name string) context.Context
- type Client
- func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
- func (c *Client) Close() error
- func (c *Client) DB() *sql.DB
- func (c *Client) Dialect() string
- func (c *Client) Exec(ctx context.Context, query string, args ...any) (sql.Result, error)
- func (c *Client) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
- func (c *Client) ExecIdempotent(ctx context.Context, query string, args ...any) (sql.Result, error)
- func (c *Client) InTx(ctx context.Context, fn func(*sql.Tx) error) (err error)
- func (c *Client) ParallelQuery(ctx context.Context, tasks ...ParallelTask) error
- func (c *Client) PingContext(ctx context.Context) error
- func (c *Client) Query(ctx context.Context, query string, fn func(*sql.Rows) error, args ...any) error
- func (c *Client) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
- func (c *Client) QueryRow(ctx context.Context, query string, fn func(*sql.Row) error, args ...any) error
- func (c *Client) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
- func (c *Client) ReadDB() *sql.DB
- func (c *Client) Stats() map[string]any
- type Config
- type CursorResult
- type DatabaseError
- type EphemeralManager
- type EphemeralSession
- type ErrorKind
- type Migration
- type MigrationDatabase
- type ORM
- func (o *ORM[T]) AutoMigrate(ctx context.Context) error
- func (o *ORM[T]) Delete(ctx context.Context, entity *T) error
- func (o *ORM[T]) DeleteByID(ctx context.Context, id any) error
- func (o *ORM[T]) Find(ctx context.Context) ([]T, error)
- func (o *ORM[T]) FindByID(ctx context.Context, id any) (*T, error)
- func (o *ORM[T]) OrderBy(clause string) *ORM[T]
- func (o *ORM[T]) Paginate(ctx context.Context, page, limit int) ([]T, int, error)
- func (o *ORM[T]) Save(ctx context.Context, entity *T) error
- func (o *ORM[T]) Where(field string, val any) *ORM[T]
- type ParallelTask
- type Repository
- func (r *Repository[T]) Create(ctx context.Context, entity *T) error
- func (r *Repository[T]) Delete(ctx context.Context, id any) error
- func (r *Repository[T]) FindAll(ctx context.Context, whereClause string, args ...any) ([]T, error)
- func (r *Repository[T]) FindByID(ctx context.Context, id any) (*T, error)
- func (r *Repository[T]) Paginate(ctx context.Context, page, limit int) ([]T, int, error)
- func (r *Repository[T]) PaginateCursor(ctx context.Context, cursorColumn string, cursorVal any, limit int) (*CursorResult[T], error)
- func (r *Repository[T]) TableName() string
- func (r *Repository[T]) Update(ctx context.Context, id any, entity *T) error
- type SQLiteClient
- func (s *SQLiteClient) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
- func (s *SQLiteClient) Close() error
- func (s *SQLiteClient) DB() *sql.DB
- func (s *SQLiteClient) Dialect() string
- func (s *SQLiteClient) Exec(ctx context.Context, query string, args ...any) error
- func (s *SQLiteClient) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
- func (s *SQLiteClient) InTx(ctx context.Context, fn func(*sql.Tx) error) error
- func (s *SQLiteClient) PingContext(ctx context.Context) error
- func (s *SQLiteClient) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
- func (s *SQLiteClient) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
- func (s *SQLiteClient) Stats() sql.DBStats
- type SQLiteConfig
- type SlowQueryConfig
- type SlowQueryEvent
Constants ¶
This section is empty.
Variables ¶
var ErrEphemeralCapacity = errors.New("dbcore/ephemeral: session capacity reached")
ErrEphemeralCapacity indicates that the process-local session bound was reached.
var ErrEphemeralResultTooLarge = errors.New("dbcore/ephemeral: materialized result is too large")
ErrEphemeralResultTooLarge indicates that a materialization exceeded its memory safety bound.
Functions ¶
func AnalyzeQuery ¶
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
AutoMigrateModel creates a database table automatically for any struct model instance or pointer.
func ClassifyError ¶
ClassifyError maps SQLite and PostgreSQL failures without exposing raw driver text. Nil and sql.ErrNoRows are returned unchanged.
func GenerateFingerprint ¶
GenerateFingerprint sanitizes SQL by replacing literal values and parameters with placeholder tokens.
func GetCacheTTL ¶
GetCacheTTL returns the query-cache lifetime attached to ctx.
func GetQueryName ¶
GetQueryName extracts the query name attached to the context, or returns "unnamed".
func IsErrorKind ¶
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 ¶
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 ¶
QueryTyped executes a raw SQL query and automatically maps matching rows into []T without manual scanning loops.
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 ¶
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 ¶
NewPostgresClient opens and verifies real PostgreSQL primary and optional replica pools. It never falls back to an in-memory database.
func (*Client) ExecContext ¶
ExecContext implements context-aware SQL execution against the primary pool.
func (*Client) ExecIdempotent ¶
ExecIdempotent executes caller-defined idempotent SQL against the primary pool.
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 ¶
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 ¶
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 ¶
QueryRowContext returns one row from the read pool.
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 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 (*ORM[T]) AutoMigrate ¶
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]) DeleteByID ¶ added in v1.11.9
DeleteByID removes a record from the database by primary key ID.
func (*ORM[T]) Paginate ¶
Paginate executes a paginated query returning entities and total count in 1 call.
type ParallelTask ¶
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]) 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 ¶
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.
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) 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) Exec ¶
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) 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 ¶
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 ¶
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.