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

db

package
v1.21.20 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: Apache-2.0 Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultMaxIdleConns = 2

DefaultMaxIdleConns is the default number of idle connections to maintain in the pool

Variables

This section is empty.

Functions

func EnsureHealthyConnection

func EnsureHealthyConnection(ctx context.Context, db *sql.DB) (*sql.Conn, error)

EnsureHealthyConnection gets a dedicated connection from the pool and validates it. The caller is responsible for closing the returned connection when done. This is useful when you need guaranteed connection health for a specific operation. SEM@b6e227d0511f3e7d38d29e5059408fe7b2cd56eb: fetch a dedicated DB connection and validate it with a ping (reads DB)

func IsConnectionError

func IsConnectionError(err error) bool

IsConnectionError is a convenience function that checks specifically for connection errors. This is equivalent to IsRetryableError — both check for transient conditions. Kept for backward compatibility. SEM@0f58823d7b00057541d6c3e806539e674d5773f4: classify a database error as a transient connection failure; alias for IsRetryableError (pure)

func IsPermanentConnectError

func IsPermanentConnectError(err error) bool

IsPermanentConnectError reports whether a connect error can never succeed on retry. SEM@ab6a7ff21a80d96c9f7c490184f44a06dc5607b9: classify a database connect error as non-retryable (pure)

func IsPermissionError

func IsPermissionError(err error) bool

IsPermissionError checks if an error indicates a database permission or privilege failure. These errors are not transient and indicate server misconfiguration. SEM@0f58823d7b00057541d6c3e806539e674d5773f4: classify a database error as a fatal permission or privilege failure, not eligible for retry (pure)

func IsRetryableError

func IsRetryableError(err error) bool

IsRetryableError determines if an error should trigger a retry. Delegates to dberrors.Classify for driver-specific error detection. SEM@0f58823d7b00057541d6c3e806539e674d5773f4: classify a database error as transient and eligible for retry (pure)

func ParseRedisURL

func ParseRedisURL(rawURL string) (host, port, password string, db int, err error)

ParseRedisURL parses a Redis connection URL and returns connection parameters. Supported URL format: redis://[:password@]host:port[/db] SEM@fe6575f1c15d84b67ee9853a0e59055c1ebe44b6: parse a Redis connection URL and return host, port, password, and database index (pure)

func RefreshConnectionPool

func RefreshConnectionPool(db *sql.DB) error

RefreshConnectionPool closes idle connections and validates the pool with fresh connections. This should be called before long-running batch operations to ensure all connections are healthy. It works by temporarily setting MaxIdleConns to 0 (forcing closure of idle connections), then restoring the original value and warming the pool with multiple pings. SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: evict idle DB connections and warm the pool with fresh validated connections (reads DB)

func SetGlobalManager

func SetGlobalManager(m *Manager)

SetGlobalManager sets the global database manager singleton. This should be called once during application startup after the manager is fully initialized. SEM@3080aafd268e1adeeb4b0e7b35049f3b5e926c7c: register the database manager singleton for process-wide access (mutates shared state)

func WithRetryableGormRead

func WithRetryableGormRead(ctx context.Context, cfg RetryConfig, fn func() error) error

WithRetryableGormRead retries a read against transient database errors WITHOUT opening a transaction.

WithRetryableGormTransaction is the wrong tool for a single-statement lookup: it begins a SERIALIZABLE transaction, which on Autonomous Database costs extra round trips for a read that needs no isolation guarantee at all. But leaving such reads entirely unretried is also wrong — dberrors.Classify tags ORA-03113/12519/12520/12537 as transient precisely because ADB raises them during autoscale, and with nothing retrying them a handler maps a momentary listener hiccup to a 500 (#616 note 6).

Same backoff and retry classification as the transactional variant; only the transaction is dropped. Use it for idempotent reads only — the closure may run more than once. SEM@bfe3f043180e288dc7f18690340fbdd493d5813c: run a read closure, retrying transient database errors with jittered backoff and no transaction (reads DB)

func WithRetryableGormTransaction

func WithRetryableGormTransaction(ctx context.Context, gormDB *gorm.DB, cfg RetryConfig, fn func(tx *gorm.DB) error, opts ...*sql.TxOptions) error

WithRetryableGormTransaction executes a function within a GORM transaction with retry logic. It automatically retries on connection errors and other transient failures. The transaction is managed by GORM (auto-commit on nil return, auto-rollback on error).

The caller MUST pass a ROOT *gorm.DB, never an in-progress transaction handle. GORM's Transaction only forwards txOpts (the SERIALIZABLE isolation) to BeginTx when the handle is a root pool; if handed an in-progress tx it silently opens a SavePoint and DROPS the isolation level — reintroducing the weak-isolation Oracle bug this wrapper exists to prevent, with no error to signal it.

fn may run more than once: on a serialization failure (40001 / ORA-08177) the whole closure is retried. fn must therefore be idempotent — keep any non-idempotent side effect (outbound calls, one-time-token consumption) out of the closure, or guard it so a replay is harmless. SEM@b7302144e81a755cfb12d83c8a03782feffcd848: execute a function in a serializable GORM transaction, retrying transient errors with jittered backoff (mutates DB)

func WithRetryableTransaction

func WithRetryableTransaction(ctx context.Context, db *sql.DB, cfg RetryConfig, fn func(*sql.Tx) error, opts ...*sql.TxOptions) error

WithRetryableTransaction executes a function within a transaction with retry logic. It automatically retries on connection errors and other transient failures. The transaction is rolled back on error and committed on success. SEM@b7302144e81a755cfb12d83c8a03782feffcd848: execute a function in a serializable SQL transaction, retrying transient errors with jittered backoff (mutates DB)

Types

type DatabaseType

type DatabaseType string

DatabaseType represents the type of database SEM@a251f60c11fe9831021be2539ff7d746fbd65b2c: string type enumerating supported database backends (pure)

const (
	DatabaseTypePostgres  DatabaseType = "postgres"
	DatabaseTypeOracle    DatabaseType = "oracle"
	DatabaseTypeMySQL     DatabaseType = "mysql"
	DatabaseTypeSQLServer DatabaseType = "sqlserver"
	DatabaseTypeSQLite    DatabaseType = "sqlite"
)

type GormConfig

type GormConfig struct {
	Type DatabaseType // Database type (extracted from URL scheme)

	// Unified connection parameters (extracted from DATABASE_URL)
	Host     string // Database host
	Port     string // Database port
	User     string // Database username
	Password string
	Database string // Database name
	SSLMode  string // SSL mode (PostgreSQL: disable/require/prefer)

	// SQLite-specific
	SQLitePath string // File path or sqliteMemoryPath for in-memory database

	// Oracle-specific (cannot be encoded in URL)
	OracleConnectString  string // TNS-style connect string (host:port/service)
	OracleWalletLocation string // Path to Oracle wallet for mTLS (env: TMI_ORACLE_WALLET_LOCATION)

	// Connection pool configuration
	MaxOpenConns    int // Maximum number of open connections to the database (default: 10)
	MaxIdleConns    int // Maximum number of idle connections in the pool (default: 2)
	ConnMaxLifetime int // Maximum time in seconds a connection can be reused (default: 240 = 4 minutes)
	ConnMaxIdleTime int // Maximum time in seconds a connection can be idle (default: 30)
}

GormConfig holds the configuration for GORM database connection. The primary configuration method is via DATABASE_URL which contains all connection parameters. The URL is parsed and values are stored in the unified fields below. SEM@fe6575f1c15d84b67ee9853a0e59055c1ebe44b6: configuration struct for a GORM database connection parsed from a URL (pure)

func ParseDatabaseURL

func ParseDatabaseURL(rawURL string) (*GormConfig, error)

ParseDatabaseURL parses a database connection URL and returns a GormConfig. Supported URL formats:

  • postgres://user:password@host:port/database?sslmode=require
  • mysql://user:password@host:port/database
  • sqlserver://user:password@host:port?database=dbname
  • sqlite:///path/to/file.db or sqlite://:memory:
  • oracle://user:password@host:port/service_name

SEM@fe6575f1c15d84b67ee9853a0e59055c1ebe44b6: parse a multi-dialect database URL into a GormConfig (pure)

type GormDB

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

GormDB represents a GORM database connection that works with PostgreSQL, Oracle, MySQL, SQL Server, and SQLite SEM@a251f60c11fe9831021be2539ff7d746fbd65b2c: GORM database connection wrapper supporting multiple SQL backends (pure)

func NewGormDB

func NewGormDB(cfg GormConfig) (*GormDB, error)

NewGormDB creates a new GORM database connection based on configuration SEM@95321b8cbecc7eacfa25d00f151d85b891b7234a: connect to a database via GORM with pooling, statement cache, tracing, and UTC timezone

func (*GormDB) AutoMigrate

func (g *GormDB) AutoMigrate(models ...any) error

AutoMigrate runs GORM auto-migration for the given models. SEM@ba7ef88caa84239c54ef87465cd9a14f01f61e3d: apply additive schema migrations for all registered models (mutates shared state)

func (*GormDB) Close

func (g *GormDB) Close() error

Close closes the database connection SEM@95321b8cbecc7eacfa25d00f151d85b891b7234a: close the underlying database connection pool, returning a redacted error (mutates shared state)

func (*GormDB) DB

func (g *GormDB) DB() *gorm.DB

DB returns the GORM database instance SEM@a251f60c11fe9831021be2539ff7d746fbd65b2c: return the raw GORM database instance (pure)

func (*GormDB) DatabaseType

func (g *GormDB) DatabaseType() DatabaseType

DatabaseType returns the type of database (postgres or oracle) SEM@a251f60c11fe9831021be2539ff7d746fbd65b2c: return the configured database backend type for this connection (pure)

func (*GormDB) LogStats

func (g *GormDB) LogStats()

LogStats logs statistics about the database connection pool SEM@95321b8cbecc7eacfa25d00f151d85b891b7234a: log database connection pool statistics at debug level

func (*GormDB) Ping

func (g *GormDB) Ping(ctx context.Context) error

Ping checks if the database connection is alive SEM@95321b8cbecc7eacfa25d00f151d85b891b7234a: validate the database connection is alive, returning the raw driver error (reads DB)

type HealthCheckResult

type HealthCheckResult struct {
	Healthy       bool
	Message       string
	Details       map[string]any
	Errors        []string
	Warnings      []string
	PerformanceMs int64
}

HealthCheckResult contains the results of a health check SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: aggregated Redis health check outcome with errors, warnings, details, and latency (pure)

type HealthMonitor

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

HealthMonitor provides background connection pool health monitoring SEM@b6e227d0511f3e7d38d29e5059408fe7b2cd56eb: background monitor that periodically pings the DB connection pool and refreshes stale connections (mutates shared state)

func NewHealthMonitor

func NewHealthMonitor(db *sql.DB, interval time.Duration) *HealthMonitor

NewHealthMonitor creates a new health monitor for the given database connection pool SEM@b6e227d0511f3e7d38d29e5059408fe7b2cd56eb: build a health monitor for a database connection pool at a given interval (pure)

func StartHealthMonitor

func StartHealthMonitor(ctx context.Context, db *sql.DB, interval time.Duration) *HealthMonitor

StartHealthMonitor is a convenience function that starts a health monitor with the given interval and returns the monitor for later stopping. Recommended interval for Heroku: 25 seconds (under Heroku's ~30s idle timeout) SEM@b6e227d0511f3e7d38d29e5059408fe7b2cd56eb: build and start a DB connection pool health monitor, returning it for later stopping

func (*HealthMonitor) Start

func (h *HealthMonitor) Start(ctx context.Context)

Start begins the background health monitoring goroutine. It periodically pings the database to keep connections warm and detect issues early. If a ping fails, it refreshes the connection pool to clear stale connections. SEM@b6e227d0511f3e7d38d29e5059408fe7b2cd56eb: start the background health-check goroutine for the connection pool (mutates shared state)

func (*HealthMonitor) Stop

func (h *HealthMonitor) Stop()

Stop stops the health monitor SEM@b6e227d0511f3e7d38d29e5059408fe7b2cd56eb: stop the background health-check goroutine (mutates shared state)

type Manager

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

Manager handles database connections SEM@b4b216a8ad19c2ca17d1d9e7466281e90c7b2f41: container holding GORM and Redis database connections with a mutex

func GetGlobalManager

func GetGlobalManager() *Manager

GetGlobalManager returns the global database manager singleton. Returns nil if SetGlobalManager has not been called. SEM@3080aafd268e1adeeb4b0e7b35049f3b5e926c7c: fetch the process-wide database manager singleton (reads shared state)

func NewManager

func NewManager() *Manager

NewManager creates a new database manager SEM@d885c7955d5a30affb8ddde84ee1cf757aab2a6b: build an empty database manager with no initialized connections (pure)

func NewMockManager

func NewMockManager() *Manager

NewMockManager creates a new mock Manager SEM@b4b216a8ad19c2ca17d1d9e7466281e90c7b2f41: build a Manager wired to a nil-client Redis stub for use in tests (pure)

func (*Manager) Close

func (m *Manager) Close() error

Close closes all database connections SEM@b4b216a8ad19c2ca17d1d9e7466281e90c7b2f41: close all held database connections, collecting and returning any errors (mutates shared state)

func (*Manager) Gorm

func (m *Manager) Gorm() *GormDB

Gorm returns the GORM database connection SEM@a251f60c11fe9831021be2539ff7d746fbd65b2c: return the initialized GORM connection, or nil if not yet connected (reads shared state)

func (*Manager) InitGorm

func (m *Manager) InitGorm(cfg GormConfig) error

InitGorm initializes the GORM database connection (supports PostgreSQL, Oracle, MySQL, SQL Server, SQLite) SEM@a251f60c11fe9831021be2539ff7d746fbd65b2c: connect GORM to the configured relational database, failing if already initialized (mutates shared state)

func (*Manager) InitRedis

func (m *Manager) InitRedis(cfg RedisConfig) error

InitRedis initializes the Redis connection SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: connect to Redis using the supplied config, failing if already initialized (mutates shared state)

func (*Manager) LogConnectionStats

func (m *Manager) LogConnectionStats(ctx context.Context)

LogConnectionStats logs statistics about all database connections SEM@b4b216a8ad19c2ca17d1d9e7466281e90c7b2f41: log pool and connection statistics for all active database backends

func (*Manager) Ping

func (m *Manager) Ping(ctx context.Context) error

Ping checks if all database connections are alive SEM@b4b216a8ad19c2ca17d1d9e7466281e90c7b2f41: health-check all initialized database connections and return aggregated errors

func (*Manager) Redis

func (m *Manager) Redis() *RedisDB

Redis returns the Redis connection SEM@d885c7955d5a30affb8ddde84ee1cf757aab2a6b: return the initialized Redis connection, or nil if not yet connected (reads shared state)

type MockManager

type MockManager struct {
}

MockManager is a mock implementation of Manager for testing SEM@78f72a392d13a20f1af466d8da33c878dc7b1518: stub DB Manager for tests that need a Manager without real connections (pure)

type MockRedisDB

type MockRedisDB struct{}

MockRedisDB is a mock implementation of RedisDB for testing SEM@0e6a42f2959c3aaa51e638008b4fe60d8e43ab23: no-op RedisDB stub for tests that require a Redis interface (pure)

func NewMockRedisDB

func NewMockRedisDB() *MockRedisDB

NewMockRedisDB creates a new mock RedisDB SEM@0e6a42f2959c3aaa51e638008b4fe60d8e43ab23: build a no-op MockRedisDB instance for use in tests (pure)

func (*MockRedisDB) Close

func (db *MockRedisDB) Close() error

Close is a mock implementation that does nothing SEM@b4b216a8ad19c2ca17d1d9e7466281e90c7b2f41: satisfy the RedisDB Close interface with a no-op (pure)

func (*MockRedisDB) Del

func (db *MockRedisDB) Del(ctx context.Context, key string) error

Del is a mock implementation that always succeeds SEM@0e6a42f2959c3aaa51e638008b4fe60d8e43ab23: satisfy the RedisDB Del interface with a no-op (pure)

func (*MockRedisDB) Expire

func (db *MockRedisDB) Expire(ctx context.Context, key string, expiration time.Duration) error

Expire is a mock implementation that always succeeds SEM@0e6a42f2959c3aaa51e638008b4fe60d8e43ab23: satisfy the RedisDB Expire interface with a no-op (pure)

func (*MockRedisDB) Get

func (db *MockRedisDB) Get(ctx context.Context, key string) (string, error)

Get is a mock implementation that returns an empty string SEM@0e6a42f2959c3aaa51e638008b4fe60d8e43ab23: satisfy the RedisDB Get interface, returning an empty string (pure)

func (*MockRedisDB) HDel

func (db *MockRedisDB) HDel(ctx context.Context, key string, fields ...string) error

HDel is a mock implementation that always succeeds SEM@0e6a42f2959c3aaa51e638008b4fe60d8e43ab23: satisfy the RedisDB HDel interface with a no-op (pure)

func (*MockRedisDB) HGet

func (db *MockRedisDB) HGet(ctx context.Context, key, field string) (string, error)

HGet is a mock implementation that returns an empty string SEM@0e6a42f2959c3aaa51e638008b4fe60d8e43ab23: satisfy the RedisDB HGet interface, returning an empty string (pure)

func (*MockRedisDB) HGetAll

func (db *MockRedisDB) HGetAll(ctx context.Context, key string) (map[string]string, error)

HGetAll is a mock implementation that returns an empty map SEM@0e6a42f2959c3aaa51e638008b4fe60d8e43ab23: satisfy the RedisDB HGetAll interface, returning an empty map (pure)

func (*MockRedisDB) HSet

func (db *MockRedisDB) HSet(ctx context.Context, key, field string, value any) error

HSet is a mock implementation that always succeeds SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: satisfy the RedisDB HSet interface with a no-op (pure)

func (*MockRedisDB) Ping

func (db *MockRedisDB) Ping(ctx context.Context) error

Ping is a mock implementation that always succeeds SEM@b4b216a8ad19c2ca17d1d9e7466281e90c7b2f41: satisfy the RedisDB Ping interface, always succeeding (pure)

func (*MockRedisDB) Set

func (db *MockRedisDB) Set(ctx context.Context, key string, value any, expiration time.Duration) error

Set is a mock implementation that always succeeds SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: satisfy the RedisDB Set interface with a no-op (pure)

type OracleNamingStrategy

type OracleNamingStrategy struct {
	schema.NamingStrategy
}

OracleNamingStrategy converts all identifiers to uppercase for Oracle compatibility. Oracle folds unquoted identifiers to uppercase, so using uppercase names ensures that queries work correctly even when identifiers aren't quoted. SEM@0953d9ec7f7a4717796566e1b4379a976404b07e: GORM naming strategy that uppercases all identifiers for Oracle compatibility (pure)

func (*OracleNamingStrategy) CheckerName

func (ns *OracleNamingStrategy) CheckerName(table, column string) string

CheckerName converts checker constraint name to uppercase for Oracle SEM@0953d9ec7f7a4717796566e1b4379a976404b07e: convert a check constraint name to uppercase for Oracle (pure)

func (*OracleNamingStrategy) ColumnName

func (ns *OracleNamingStrategy) ColumnName(table, column string) string

ColumnName converts column name to uppercase for Oracle SEM@0953d9ec7f7a4717796566e1b4379a976404b07e: convert a column name to uppercase for Oracle (pure)

func (*OracleNamingStrategy) IndexName

func (ns *OracleNamingStrategy) IndexName(table, column string) string

IndexName converts index name to uppercase for Oracle SEM@0953d9ec7f7a4717796566e1b4379a976404b07e: convert an index name to uppercase for Oracle (pure)

func (*OracleNamingStrategy) JoinTableName

func (ns *OracleNamingStrategy) JoinTableName(joinTable string) string

JoinTableName converts join table name to uppercase for Oracle SEM@0953d9ec7f7a4717796566e1b4379a976404b07e: convert a join table name to uppercase for Oracle (pure)

func (*OracleNamingStrategy) RelationshipFKName

func (ns *OracleNamingStrategy) RelationshipFKName(rel schema.Relationship) string

RelationshipFKName converts foreign key name to uppercase for Oracle SEM@0953d9ec7f7a4717796566e1b4379a976404b07e: convert a foreign key constraint name to uppercase for Oracle (pure)

func (*OracleNamingStrategy) TableName

func (ns *OracleNamingStrategy) TableName(table string) string

TableName converts table name to uppercase for Oracle SEM@a251f60c11fe9831021be2539ff7d746fbd65b2c: convert a table name to uppercase for Oracle (pure)

func (*OracleNamingStrategy) UniqueName

func (ns *OracleNamingStrategy) UniqueName(table, column string) string

UniqueName converts unique constraint name to uppercase for Oracle SEM@0953d9ec7f7a4717796566e1b4379a976404b07e: convert a unique constraint name to uppercase for Oracle (pure)

type PatternDoc

type PatternDoc struct {
	Name        string
	Pattern     string
	DataType    string
	MaxTTL      time.Duration
	Description string
}

PatternDoc represents documentation for a key pattern SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: human-readable documentation entry for a Redis key namespace pattern (pure)

type RedisConfig

type RedisConfig struct {
	Host     string
	Port     string
	Password string
	// PasswordFunc, when set, supplies the password on every (re)connect and
	// takes precedence over Password, so a rotated password is picked up.
	PasswordFunc func(ctx context.Context) (string, error)
	DB           int
	TLSEnabled   bool   // connect with TLS, verifying the server against TLSCAFile only
	TLSCAFile    string // PEM CA file; required when TLSEnabled
}

RedisConfig holds the configuration for Redis connection SEM@32eda6c88eee02283fa8feb03bb2d42252451618: Redis connection settings: address, password source, database, and CA-pinned TLS

type RedisDB

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

RedisDB represents a Redis database connection SEM@3b4ebaddebcae67845b4c86613b8031f614a4bcc: Redis client wrapper with optional at-rest encryption support

func NewRedisDB

func NewRedisDB(cfg RedisConfig) (*RedisDB, error)

NewRedisDB creates a new Redis database connection SEM@e50244f: connect to Redis (optionally TLS) with OpenTelemetry instrumentation and verify liveness

func (*RedisDB) Close

func (db *RedisDB) Close() error

Close closes the Redis connection SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: close the Redis client connection

func (*RedisDB) Del

func (db *RedisDB) Del(ctx context.Context, key string) error

Del deletes a key SEM@d885c7955d5a30affb8ddde84ee1cf757aab2a6b: delete a key from Redis

func (*RedisDB) Expire

func (db *RedisDB) Expire(ctx context.Context, key string, expiration time.Duration) error

Expire sets an expiration on a key SEM@d885c7955d5a30affb8ddde84ee1cf757aab2a6b: set a TTL expiration on a Redis key

func (*RedisDB) Get

func (db *RedisDB) Get(ctx context.Context, key string) (string, error)

Get gets a value by key. If an encryptor is configured and the stored value has the ENC: prefix, it is decrypted before being returned. Plaintext values pass through unchanged. SEM@3b4ebaddebcae67845b4c86613b8031f614a4bcc: fetch a value from Redis, decrypting it if stored encrypted

func (*RedisDB) GetClient

func (db *RedisDB) GetClient() *redis.Client

GetClient returns the Redis client SEM@d885c7955d5a30affb8ddde84ee1cf757aab2a6b: return the underlying Redis client (pure)

func (*RedisDB) HDel

func (db *RedisDB) HDel(ctx context.Context, key string, fields ...string) error

HDel deletes a hash field SEM@d885c7955d5a30affb8ddde84ee1cf757aab2a6b: delete one or more hash fields from Redis

func (*RedisDB) HGet

func (db *RedisDB) HGet(ctx context.Context, key, field string) (string, error)

HGet gets a hash field. If an encryptor is configured and the stored value has the ENC: prefix, it is decrypted before being returned. Plaintext values pass through unchanged. SEM@3b4ebaddebcae67845b4c86613b8031f614a4bcc: fetch a single hash field from Redis, decrypting it if stored encrypted

func (*RedisDB) HGetAll

func (db *RedisDB) HGetAll(ctx context.Context, key string) (map[string]string, error)

HGetAll gets all fields in a hash. If an encryptor is configured, any field values with the ENC: prefix are decrypted before being returned. Plaintext values pass through unchanged. SEM@3b4ebaddebcae67845b4c86613b8031f614a4bcc: fetch all hash fields from Redis, decrypting any encrypted values

func (*RedisDB) HSet

func (db *RedisDB) HSet(ctx context.Context, key, field string, value any) error

HSet sets a hash field. If an encryptor is configured and the key matches a sensitive pattern, the field value is encrypted before writing to Redis. SEM@678dbf33e51f2c734b5011e019d5f2bff6837612: store a Redis hash field, encrypting sensitive values at rest

func (*RedisDB) LogStats

func (db *RedisDB) LogStats(ctx context.Context)

LogStats logs statistics about the Redis connection SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: log Redis connection pool statistics at debug level

func (*RedisDB) Ping

func (db *RedisDB) Ping(ctx context.Context) error

Ping checks if the Redis connection is alive SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: verify Redis connection liveness with a ping

func (*RedisDB) Set

func (db *RedisDB) Set(ctx context.Context, key string, value any, expiration time.Duration) error

Set sets a key-value pair with expiration. If an encryptor is configured and the key matches a sensitive pattern, the value is encrypted before writing to Redis. SEM@678dbf33e51f2c734b5011e019d5f2bff6837612: store a Redis key-value with expiration, encrypting sensitive values at rest

func (*RedisDB) SetEncryptor

func (db *RedisDB) SetEncryptor(enc *crypto.SettingsEncryptor)

SetEncryptor sets the encryptor for at-rest encryption of sensitive Redis values. When set and enabled, values for keys matching sensitive patterns are encrypted before writing and decrypted after reading. If nil or disabled, values pass through unchanged. SEM@3b4ebaddebcae67845b4c86613b8031f614a4bcc: attach an at-rest encryptor to the Redis client (mutates shared state)

type RedisHealthChecker

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

RedisHealthChecker performs health checks on Redis SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: Redis health checker holding a client, key validator, and logger (pure)

func NewRedisHealthChecker

func NewRedisHealthChecker(client *redis.Client) *RedisHealthChecker

NewRedisHealthChecker creates a new Redis health checker SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: build a RedisHealthChecker with a default key validator (pure)

func (*RedisHealthChecker) CheckHealth

CheckHealth performs a comprehensive health check on Redis SEM@3d0d5a8cf02fa74fad102f0f99c2b936a164bbea: run a full Redis health check covering connectivity, memory, key patterns, TTLs, and performance (reads DB)

func (*RedisHealthChecker) GetKeyStatistics

func (h *RedisHealthChecker) GetKeyStatistics(ctx context.Context) (map[string]int, error)

GetKeyStatistics returns statistics about keys in Redis SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: aggregate Redis key counts by two-segment prefix and return the total DB size (reads DB)

func (*RedisHealthChecker) LogHealthCheck

func (h *RedisHealthChecker) LogHealthCheck(result HealthCheckResult)

LogHealthCheck logs the health check results SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: log a health check result at the appropriate level with all errors, warnings, and details (mutates shared state)

type RedisKeyBuilder

type RedisKeyBuilder struct{}

RedisKeyBuilder provides methods to build Redis keys following the defined patterns SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: namespace for methods that build namespaced Redis keys for all entity types

func NewRedisKeyBuilder

func NewRedisKeyBuilder() *RedisKeyBuilder

NewRedisKeyBuilder creates a new Redis key builder SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: build a RedisKeyBuilder instance (pure)

func (*RedisKeyBuilder) AuthRefreshKey

func (b *RedisKeyBuilder) AuthRefreshKey(refreshTokenID string) string

AuthRefreshKey builds an auth refresh token key SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: build the Redis key for a refresh token (pure)

func (*RedisKeyBuilder) AuthStateKey

func (b *RedisKeyBuilder) AuthStateKey(state string) string

AuthStateKey builds an OAuth state key SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: build the Redis key for an OAuth state parameter (pure)

func (*RedisKeyBuilder) AuthTokenKey

func (b *RedisKeyBuilder) AuthTokenKey(tokenID string) string

AuthTokenKey builds an auth token key SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: build the Redis key for an auth access token (pure)

func (*RedisKeyBuilder) BlacklistTokenKey

func (b *RedisKeyBuilder) BlacklistTokenKey(jti string) string

BlacklistTokenKey builds a token blacklist key SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: build the Redis key for a blacklisted token JTI (pure)

func (*RedisKeyBuilder) CacheAssetKey

func (b *RedisKeyBuilder) CacheAssetKey(assetID string) string

CacheAssetKey builds an asset cache key SEM@f2c738b899d06c4246bd8283b568260c596d5168: build the Redis cache key for an asset by ID (pure)

func (*RedisKeyBuilder) CacheAuthKey

func (b *RedisKeyBuilder) CacheAuthKey(threatModelID string) string

CacheAuthKey builds an authorization data cache key SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: build the Redis cache key for authorization data of a threat model (pure)

func (*RedisKeyBuilder) CacheCellsKey

func (b *RedisKeyBuilder) CacheCellsKey(diagramID string) string

CacheCellsKey builds a diagram cells collection cache key SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: build the Redis cache key for the cells collection of a diagram (pure)

func (*RedisKeyBuilder) CacheDiagramKey

func (b *RedisKeyBuilder) CacheDiagramKey(diagramID string) string

CacheDiagramKey builds a diagram cache key SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: build the Redis cache key for a diagram by ID (pure)

func (*RedisKeyBuilder) CacheDocumentKey

func (b *RedisKeyBuilder) CacheDocumentKey(docID string) string

CacheDocumentKey builds a document cache key SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: build the Redis cache key for a document by ID (pure)

func (*RedisKeyBuilder) CacheListKey

func (b *RedisKeyBuilder) CacheListKey(entityType, parentID string, offset, limit int) string

CacheListKey builds a paginated list cache key SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: build the Redis cache key for a paginated entity list by type, parent, and page bounds (pure)

func (*RedisKeyBuilder) CacheMetadataKey

func (b *RedisKeyBuilder) CacheMetadataKey(entityType, entityID string) string

CacheMetadataKey builds a metadata collection cache key SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: build the Redis cache key for a metadata collection by entity type and ID (pure)

func (*RedisKeyBuilder) CacheNoteKey

func (b *RedisKeyBuilder) CacheNoteKey(noteID string) string

CacheNoteKey builds a note cache key SEM@bc24b01d8fe51390e6178a0cbe35e701f76556ce: build the Redis cache key for a note by ID (pure)

func (*RedisKeyBuilder) CacheRepositoryKey

func (b *RedisKeyBuilder) CacheRepositoryKey(sourceID string) string

CacheRepositoryKey builds a source code cache key SEM@73296f71a63ff321440eff41ab087d4043aa8f68: build the Redis cache key for a source repository by ID (pure)

func (*RedisKeyBuilder) CacheThreatKey

func (b *RedisKeyBuilder) CacheThreatKey(threatID string) string

CacheThreatKey builds a individual threat cache key SEM@6a25ed41f4450e7eba44de39fb07a07cac216f26: build the Redis cache key for an individual threat by ID (pure)

func (*RedisKeyBuilder) CacheThreatModelKey

func (b *RedisKeyBuilder) CacheThreatModelKey(modelID string) string

CacheThreatModelKey builds a threat model cache key SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: build the Redis cache key for a threat model by ID (pure)

func (*RedisKeyBuilder) CacheUserByEmailKey

func (b *RedisKeyBuilder) CacheUserByEmailKey(email string) string

CacheUserByEmailKey builds a user cache key by email SEM@89d554e793900a75b5703e1d10c9d58f57ceadc6: build the Redis cache key for a user by email address (pure)

func (*RedisKeyBuilder) CacheUserByProviderKey

func (b *RedisKeyBuilder) CacheUserByProviderKey(provider, providerUserID string) string

CacheUserByProviderKey builds a user cache key by provider and provider user ID SEM@89d554e793900a75b5703e1d10c9d58f57ceadc6: build the Redis cache key for a user by OAuth provider and provider user ID (pure)

func (*RedisKeyBuilder) CacheUserKey

func (b *RedisKeyBuilder) CacheUserKey(userID string) string

CacheUserKey builds a user cache key by internal UUID SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: build the Redis cache key for a user by internal UUID (pure)

func (*RedisKeyBuilder) LockKey

func (b *RedisKeyBuilder) LockKey(resource, id string) string

LockKey builds a distributed lock key SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: build the Redis key for a distributed lock on a named resource (pure)

func (*RedisKeyBuilder) ParseRateLimitKey

func (b *RedisKeyBuilder) ParseRateLimitKey(key string) (limitType, identifier, action string, err error)

ParseRateLimitKey parses a rate limit key into its components SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: parse a Redis rate-limit key into limit type, identifier, and action components (pure)

func (*RedisKeyBuilder) ParseSessionKey

func (b *RedisKeyBuilder) ParseSessionKey(key string) (userID, sessionID string, err error)

ParseSessionKey parses a session key into its components SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: parse a Redis session key into user ID and session ID components (pure)

func (*RedisKeyBuilder) RateLimitAPIKey

func (b *RedisKeyBuilder) RateLimitAPIKey(apiKey, endpoint string) string

RateLimitAPIKey builds an API key rate limit key SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: build the Redis key for a per-API-key per-endpoint rate limit counter (pure)

func (*RedisKeyBuilder) RateLimitGlobalKey

func (b *RedisKeyBuilder) RateLimitGlobalKey(ip, endpoint string) string

RateLimitGlobalKey builds a global rate limit key SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: build the Redis key for a global per-IP per-endpoint rate limit counter (pure)

func (*RedisKeyBuilder) RateLimitUserKey

func (b *RedisKeyBuilder) RateLimitUserKey(userID, action string) string

RateLimitUserKey builds a user rate limit key SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: build the Redis key for a per-user per-action rate limit counter (pure)

func (*RedisKeyBuilder) SessionKey

func (b *RedisKeyBuilder) SessionKey(userID, sessionID string) string

SessionKey builds a session key SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: build the Redis key for a user session (pure)

func (*RedisKeyBuilder) TempExportKey

func (b *RedisKeyBuilder) TempExportKey(jobID string) string

TempExportKey builds a temporary export job key SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: build the Redis key for a temporary export job (pure)

func (*RedisKeyBuilder) TempImportKey

func (b *RedisKeyBuilder) TempImportKey(jobID string) string

TempImportKey builds a temporary import job key SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: build the Redis key for a temporary import job (pure)

type RedisKeyPattern

type RedisKeyPattern struct {
	Pattern     string
	Regex       *regexp.Regexp
	DataType    string
	MaxTTL      time.Duration
	Description string
}

RedisKeyPattern defines a pattern for Redis keys SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: schema for a Redis key namespace: its regex, expected data type, and max TTL (pure)

type RedisKeyValidator

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

RedisKeyValidator validates Redis keys against defined patterns SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: validate Redis keys against registered namespace patterns with TTL and type checks (reads DB)

func NewRedisKeyValidator

func NewRedisKeyValidator() *RedisKeyValidator

NewRedisKeyValidator creates a new Redis key validator SEM@1d6e8926b4e58c0d98fff4d43bd3f6df1852d61a: build a RedisKeyValidator pre-loaded with all known key namespace patterns (pure)

func (*RedisKeyValidator) GetPatternDocumentation

func (v *RedisKeyValidator) GetPatternDocumentation() []PatternDoc

GetPatternDocumentation returns documentation for all patterns SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: list human-readable documentation for all registered Redis key patterns (pure)

func (*RedisKeyValidator) GetPatternForKey

func (v *RedisKeyValidator) GetPatternForKey(key string) (*RedisKeyPattern, error)

GetPatternForKey returns the pattern that matches the given key SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: fetch the registered pattern that matches a Redis key; error if none match (pure)

func (*RedisKeyValidator) LogValidationResults

func (v *RedisKeyValidator) LogValidationResults(results []ValidationResult)

LogValidationResults logs the validation results SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: log a summary of Redis key validation outcomes at appropriate severity levels (pure)

func (*RedisKeyValidator) ScanAndValidate

func (v *RedisKeyValidator) ScanAndValidate(ctx context.Context, client *redis.Client) ([]ValidationResult, error)

ScanAndValidate scans all keys and validates them SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: scan all Redis keys and validate each against pattern, data type, and TTL rules (reads DB)

func (*RedisKeyValidator) ValidateDataType

func (v *RedisKeyValidator) ValidateDataType(ctx context.Context, client *redis.Client, key string) error

ValidateDataType validates that a key has the expected data type SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: validate that a Redis key's stored data type matches the expected type for its pattern (reads DB)

func (*RedisKeyValidator) ValidateKey

func (v *RedisKeyValidator) ValidateKey(key string) error

ValidateKey validates a Redis key against defined patterns SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: validate a Redis key against all registered namespace patterns; error if unrecognized (pure)

func (*RedisKeyValidator) ValidateKeyWithTTL

func (v *RedisKeyValidator) ValidateKeyWithTTL(ctx context.Context, client *redis.Client, key string) error

ValidateKeyWithTTL validates a key and checks if TTL is within limits SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: validate a Redis key's pattern and assert its TTL is set and within the allowed maximum (reads DB)

type RetryConfig

type RetryConfig struct {
	MaxRetries int
	BaseDelay  time.Duration
	MaxDelay   time.Duration
}

RetryConfig holds configuration for retry behavior SEM@b6e227d0511f3e7d38d29e5059408fe7b2cd56eb: configuration parameters governing retry count and exponential backoff bounds (pure)

func DefaultRetryConfig

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig returns reasonable defaults for transaction retries SEM@b6e227d0511f3e7d38d29e5059408fe7b2cd56eb: build a RetryConfig with conservative defaults suitable for database transaction retries (pure)

type TestDB

type TestDB struct {
	DB      *gorm.DB
	Cleanup func()
}

TestDB holds a test database connection and cleanup function SEM@02214aa5ba030b20069f011c02d8be00d1e8c0ff: test fixture holding an in-memory SQLite database and its cleanup function

func MustCreateTestDB

func MustCreateTestDB(t *testing.T) *TestDB

MustCreateTestDB creates a test DB, failing the test on error. SEM@02214aa5ba030b20069f011c02d8be00d1e8c0ff: build a test database, failing the test immediately on error

func NewTestDB

func NewTestDB(t *testing.T) (*TestDB, error)

NewTestDB creates a new in-memory SQLite database for testing. It automatically migrates all models and returns a cleanup function. SEM@02214aa5ba030b20069f011c02d8be00d1e8c0ff: build an auto-migrated in-memory SQLite database for tests (mutates shared state)

func (*TestDB) SeedClientCredential

func (tdb *TestDB) SeedClientCredential(t *testing.T, ownerUUID, clientID, name string) *models.ClientCredential

SeedClientCredential creates a test client credential and returns it. SEM@2dccb03396c9b3e288e2242edb54c418635c3e08: insert a test client credential record into the test database (mutates shared state)

func (*TestDB) SeedGroup

func (tdb *TestDB) SeedGroup(t *testing.T, provider, groupName string) *models.Group

SeedGroup creates a test group and returns it. SEM@2dccb03396c9b3e288e2242edb54c418635c3e08: insert a test group record into the test database (mutates shared state)

func (*TestDB) SeedSurveyResponse

func (tdb *TestDB) SeedSurveyResponse(t *testing.T, templateID, ownerUUID string, isConfidential bool) *models.SurveyResponse

SeedSurveyResponse creates a test survey response and returns it. SEM@e530c9655ae71e6bf78a13b97320afcbd9b1e7b5: insert a test survey response into the test database (mutates shared state)

func (*TestDB) SeedSurveyResponseAccess

func (tdb *TestDB) SeedSurveyResponseAccess(t *testing.T, responseID string, userUUID *string, groupUUID *string, subjectType, role string) *models.SurveyResponseAccess

SeedSurveyResponseAccess creates a test survey response access record and returns it. SEM@ebf201816c3638ec74fc8483a2a649af3ccddfc9: insert a survey response access control record for a user or group into the test database (mutates shared state)

func (*TestDB) SeedSurveyTemplate

func (tdb *TestDB) SeedSurveyTemplate(t *testing.T, createdByUUID string) *models.SurveyTemplate

SeedSurveyTemplate creates a test survey template and returns it. SEM@2dccb03396c9b3e288e2242edb54c418635c3e08: insert a test survey template into the test database (mutates shared state)

func (*TestDB) SeedThreatModel

func (tdb *TestDB) SeedThreatModel(t *testing.T, ownerUUID, name string) *models.ThreatModel

SeedThreatModel creates a test threat model with the given owner and returns it. SEM@79a11352f14300d8a049192847b5c411d1d8166c: insert a test threat model owned by the given user into the test database (mutates shared state)

func (*TestDB) SeedThreatModelAccess

func (tdb *TestDB) SeedThreatModelAccess(t *testing.T, threatModelID string, userUUID *string, groupUUID *string, subjectType, role string) *models.ThreatModelAccess

SeedThreatModelAccess creates a test threat model access record and returns it. SEM@ebf201816c3638ec74fc8483a2a649af3ccddfc9: insert a threat model access control record for a user or group into the test database (mutates shared state)

func (*TestDB) SeedTriageNote

func (tdb *TestDB) SeedTriageNote(t *testing.T, responseID, createdByUUID, modifiedByUUID string) *models.TriageNote

SeedTriageNote creates a test triage note and returns it. SEM@2dccb03396c9b3e288e2242edb54c418635c3e08: insert a test triage note linked to a survey response into the test database (mutates shared state)

func (*TestDB) SeedUser

func (tdb *TestDB) SeedUser(t *testing.T, email, provider string) *models.User

SeedUser creates a test user and returns it. SEM@2dccb03396c9b3e288e2242edb54c418635c3e08: insert a test user record into the test database, failing the test on error (mutates shared state)

type ValidationResult

type ValidationResult struct {
	Key    string
	Valid  bool
	Errors []string
}

ValidationResult represents the result of validating a Redis key SEM@27f75e455935db4d67b8511cf30f5f77c118fc2f: outcome of validating a single Redis key including any error messages (pure)

Jump to

Keyboard shortcuts

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