db

package
v0.1.60 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: Apache-2.0 Imports: 43 Imported by: 8

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultQueryTimeout = 30 * time.Second
View Source
var LogLevel string

LogLevel is the log level for gorm logger

Functions

func BindGoFlags

func BindGoFlags()

BindGoFlags binds database flags to the provided flag set

func DefaultGormConfig

func DefaultGormConfig() *gormDriver.Config

DefaultGormConfig returns the default GORM configuration

func Delete

func Delete(ctx dbContext.Context, model Table) error

Delete performs a soft delete on the given model

func EnsurePerformanceDiagnostics added in v0.1.23

func EnsurePerformanceDiagnostics(ctx context.Context, dsn string) error

EnsurePerformanceDiagnostics validates server-level settings before installing pg_stat_statements in the selected database. Server settings are checked first so an externally managed instance fails without partial DDL.

func FreePort added in v0.1.7

func FreePort() (int, error)

FreePort binds :0 to discover a free TCP port. Public so callers can reuse it for adjacent services (e.g. postgrest) that need an unclaimed port.

func InitDB

func InitDB(config api.Config) (*dbContext.Context, error)

InitDB creates a context with database connections Note: Does NOT check for migrations - consumers should verify migrations separately

func NewDB

func NewDB(connection string) (*sql.DB, error)

NewDB creates a new sql.DB connection with a bounded pool. Callers that need different bounds apply their own PoolConfig to the returned handle.

func NewGorm

func NewGorm(connection string, config *gorm.Config) (*gorm.DB, error)

NewGorm creates a GORM connection for a PostgreSQL, SQLite or SQL Server DSN.

func NewPgxPool

func NewPgxPool(connection string) (*pgxpool.Pool, error)

NewPgxPool creates a new pgx connection pool with OpenTelemetry tracing

func NewSQLStatementPlugin added in v0.1.49

func NewSQLStatementPlugin() gorm.Plugin

NewSQLStatementPlugin returns a gorm plugin that publishes each statement the handle runs (connection.PublishSQL) as the context's own database's (connection.OwnDatabase). A handle nobody observes pays one lookup per statement.

func NewServerTimingPlugin added in v0.1.29

func NewServerTimingPlugin() gorm.Plugin

NewServerTimingPlugin returns a gorm plugin that records an "sql" metric with queries and rows_returned counters for every statement whose context carries an rpchttp.Timings accumulator.

func Now

func Now() clause.Expr

Now returns a SQL expression for the current timestamp

func ScaledTestingParameters added in v0.1.60

func ScaledTestingParameters(limits HostLimits, ramDiskBytes uint64) map[string]string

ScaledTestingParameters sizes a fast-testing server to limits. ramDiskBytes is the size of the RAM-backed filesystem holding the cluster, or zero when it is on disk; WAL kept until the next checkpoint occupies memory there.

func ScanRows added in v0.1.13

func ScanRows[T ~map[string]any](rows *sql.Rows) ([]T, error)

ScanRows scans all rows of a *sql.Rows into a slice of map-like records, keyed by column name. Ported from duty/db so SQL data providers can return generic rows without a typed model.

func SetupDB

func SetupDB(connectionString string, logName string) (gormDB *gormDriver.DB, pgxPool *pgxpool.Pool, err error)

SetupDB creates database connections (gorm.DB and pgxpool.Pool) Note: This does NOT run migrations - consumers should handle migrations separately

func StartEmbedded added in v0.1.7

func StartEmbedded(cfg EmbeddedConfig) (string, func() error, error)

StartEmbedded launches PostgreSQL under cfg.DataDir. Reused servers and servers configured with KeepRunning are never stopped by the returned closer.

Types

type EmbeddedConfig added in v0.1.7

type EmbeddedConfig struct {
	// DataDir is the root for the data, runtime, and bin subdirectories.
	// The caller owns this choice; StartEmbedded does not pick a default path.
	DataDir string
	// BinariesDir holds the extracted PostgreSQL binaries, one subdirectory per
	// version. Defaults to DataDir/bin; set it to keep binaries on persistent
	// disk when DataDir is RAM-backed.
	BinariesDir string
	// RAMDiskBytes is the size of the RAM-backed filesystem DataDir lives on,
	// or zero when it is on disk. FastTesting caps WAL to a quarter of it.
	RAMDiskBytes uint64
	// Database created on first start. Defaults to "postgres" when blank.
	Database string
	// Port to bind. Zero picks a free port via FreePort().
	Port uint32
	// Username / Password. Default to "postgres"/"postgres" — fine for the
	// localhost-only instances this helper is meant for.
	Username, Password string
	// Logger receives the embedded-postgres / pg_ctl diagnostic output. Defaults
	// to os.Stderr (the library default is os.Stdout, which would corrupt callers
	// that write binary or structured data to stdout).
	Logger io.Writer
	// PerformanceDiagnostics preloads pg_stat_statements, enables I/O timing,
	// installs the extension, and fails startup if any part is unavailable.
	PerformanceDiagnostics bool
	// KeepRunning leaves a server started by this call running when stop is
	// invoked. Reused servers are always left running.
	KeepRunning bool
	// FastTesting trades durability for speed and sizes the server to the host
	// (see ScaledTestingParameters). It is only suitable for disposable local
	// test data.
	FastTesting bool
}

EmbeddedConfig configures StartEmbedded.

type HostLimits added in v0.1.60

type HostLimits struct {
	// CPUs is runtime.GOMAXPROCS(0), which follows the cgroup CPU quota.
	CPUs int
	// MemoryBytes is the smaller of the host's memory and the cgroup limit.
	MemoryBytes uint64
	// CI marks a dedicated runner (CI=true), which may give PostgreSQL a larger
	// share of memory than a shared workstation.
	CI bool
}

HostLimits is the CPU and memory budget a disposable test PostgreSQL server sizes itself to.

func DetectHostLimits added in v0.1.60

func DetectHostLimits() (HostLimits, error)

DetectHostLimits reads the CPU, memory and CI limits of the current process. Memory that cannot be read is an error naming the source, never a default.

type PoolConfig added in v0.1.23

type PoolConfig struct {
	MaxOpenConns    int
	MaxIdleConns    int
	ConnMaxIdleTime time.Duration
	ConnMaxLifetime time.Duration
}

PoolConfig bounds a database/sql pool. The zero value is deliberately not useful: an unbounded pool turns a burst of goroutines into a burst of backends contending for the same rows, and database/sql's default ceiling of two idle connections then reconnects for every one of them.

func DefaultPoolConfig added in v0.1.23

func DefaultPoolConfig() PoolConfig

DefaultPoolConfig mirrors the floor NewPgxPool already enforces. Idle equals open so a bursty workload reuses connections rather than reconnecting, and the lifetime cap keeps a long-lived process from pinning server-side state.

func (PoolConfig) Apply added in v0.1.23

func (c PoolConfig) Apply(db *sql.DB)

type RowScanner added in v0.1.15

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

RowScanner scans the current database/sql row into a JSON-friendly map while retaining only one decoded row in memory.

func NewRowScanner added in v0.1.15

func NewRowScanner(rows *sql.Rows) (*RowScanner, error)

func (*RowScanner) Err added in v0.1.15

func (s *RowScanner) Err() error

func (*RowScanner) Next added in v0.1.15

func (s *RowScanner) Next() bool

func (*RowScanner) Row added in v0.1.15

func (s *RowScanner) Row() map[string]any

type Table

type Table interface {
	TableName() string
}

Table interface for models with TableName

Directories

Path Synopsis
Compressed columns: a column stored as a zstd blob of its text, and the rs_inflate SQL function every connection reads it back through.
Compressed columns: a column stored as a zstd blob of its text, and the rs_inflate SQL function every connection reads it back through.

Jump to

Keyboard shortcuts

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