db

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package db provides GORM database connection management for serverless and HTTP services.

Index

Constants

This section is empty.

Variables

View Source
var ErrSQLitePragma = errors.New("sqlite: connection is missing a required pragma")

ErrSQLitePragma reports that a SQLite connection is missing a pragma the caller requires. VerifySQLitePragmas wraps it, naming the offending pragma, so errors.Is(err, ErrSQLitePragma) matches while the message stays specific.

Functions

func NewConnection

func NewConnection(cfg config.DatabaseConfig, opts ...Option) (*gorm.DB, error)

NewConnection creates a new GORM database connection based on the configuration. It supports "sqlite" and "postgres" drivers, and accepts any type that implements the DatabaseConfig interface.

Optional behaviors are opt-in via Option values (for example WithSkipDefaultTransaction, WithPrepareStmt); passing none preserves GORM's defaults, so existing callers are unaffected.

func SQLitePragmaInt added in v0.4.0

func SQLitePragmaInt(gdb *gorm.DB, name string) (int, error)

SQLitePragmaInt reads an integer-valued PRAGMA from gdb (for example busy_timeout or synchronous). The pragma name is a caller-controlled constant, not user input.

func SQLitePragmaString added in v0.4.0

func SQLitePragmaString(gdb *gorm.DB, name string) (string, error)

SQLitePragmaString reads a text-valued PRAGMA from gdb (for example journal_mode). The pragma name is a caller-controlled constant, not user input.

func VerifySQLitePragmas added in v0.4.0

func VerifySQLitePragmas(gdb *gorm.DB) error

VerifySQLitePragmas verifies the connection pragmas a concurrent SQLite workload relies on, returning ErrSQLitePragma (naming the pragma) on a hard failure.

A file database must be in WAL so readers do not block a writer; an in-memory database — which cannot use WAL — is exempt from that one requirement but, like any database, still needs a positive busy_timeout to absorb a brief write lock and a safe synchronous level so a committed write survives a crash. synchronous is required to be NORMAL(1) or FULL(2); OFF(0) is refused.

The check reads pragmas only, so it needs no dialector and makes no assumptions about how the connection was opened. Warnings a caller may want on top of the fatal checks — foreign_keys, DSN-only settings such as _txlock=immediate — are left to the caller, which knows its own schema.

Types

type Option added in v0.6.3

type Option func(*options)

Option configures an optional behavior applied to the gorm.Config a connection is opened with. Options are additive and evaluated in order; the empty set leaves GORM's defaults in place. Pass them to NewConnection.

func WithLogger added in v0.8.1

func WithLogger(l gormlogger.Interface) Option

WithLogger sets gorm.Config.Logger, the logger GORM reports statements and its own messages through. A nil logger (the default) leaves GORM's default logger, which writes colored text to stdout and inlines each statement's bound values into the logged SQL.

The logger is installed when the connection is opened, so GORM's open-time messages (for example a failure to initialize the database) are routed through it too, not only the statements that follow.

To log statements as structured records without bound values, pass a slog-backed logger with parameterized queries:

gormlogger.NewSlogLogger(slog.Default(), gormlogger.Config{
	SlowThreshold:        200 * time.Millisecond,
	LogLevel:             gormlogger.Warn,
	ParameterizedQueries: true,
})

With ParameterizedQueries set, the logged SQL keeps its placeholders and carries none of the values bound to them, with one exception inside GORM: Scan traces its statement through a recorder that filters bound values with the process-wide gormlogger.RecorderParamsFilter (a no-op by default) rather than with this logger. To withhold values from Scan as well, set that filter once at startup, before any connection is used:

gormlogger.RecorderParamsFilter = func(_ context.Context, sql string, _ ...any) (string, []any) {
	return sql, nil
}

func WithPrepareStmt added in v0.6.3

func WithPrepareStmt(prepare bool) Option

WithPrepareStmt toggles gorm.Config.PrepareStmt (disabled by default), GORM's prepared-statement cache. When enabled, GORM prepares each distinct statement once per connection and reuses it, avoiding re-parsing on repeated queries.

Caveat: do not enable this behind a connection pooler or proxy that multiplexes below the session level. PgBouncer in transaction or statement pooling mode cannot carry protocol-level prepared statements, and AWS RDS Proxy pins the client to a single backend connection for the life of a prepared statement, defeating the proxy's connection reuse. Enable it only for a direct (or session-pooled) connection.

func WithSkipDefaultTransaction added in v0.6.3

func WithSkipDefaultTransaction(skip bool) Option

WithSkipDefaultTransaction toggles gorm.Config.SkipDefaultTransaction (disabled by default).

GORM wraps every single Create/Update/Delete in an implicit transaction (BEGIN … COMMIT) unless this is enabled. Skipping that wrapper removes two round trips per write — a measurable win when the database is reached over a network hop — and single statements still commit atomically on their own. The only behavior it changes is the implicit all-or-nothing of a cascading Create that inserts a parent and its associations in one call: without the wrapping transaction, a failure part way through can leave the parent committed. Enable it when writes are single-row, or when multi-statement atomicity is managed explicitly (for example via gorm.DB.Transaction).

Jump to

Keyboard shortcuts

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