db

package
v1.21.31 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 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.

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.

func IsPermanentConnectError

func IsPermanentConnectError(err error) bool

IsPermanentConnectError reports whether a connect error can never succeed on retry.

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.

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.

func NowFunc added in v1.21.31

func NowFunc() time.Time

NowFunc is the GORM clock for autoCreateTime/autoUpdateTime and hooks. It returns UTC truncated to microseconds: PostgreSQL timestamptz and Oracle TIMESTAMP(6) store microsecond precision, so a nanosecond value echoed in a write response would differ from what a later GET returns (#1155).

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]

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.

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.

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.

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.

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.

Types

type DatabaseType

type DatabaseType string

DatabaseType represents the type of database

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.

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

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

func NewGormDB

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

NewGormDB creates a new GORM database connection based on configuration

func (*GormDB) AutoMigrate

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

AutoMigrate runs GORM auto-migration for the given models.

func (*GormDB) Close

func (g *GormDB) Close() error

Close closes the database connection

func (*GormDB) DB

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

DB returns the GORM database instance

func (*GormDB) DatabaseType

func (g *GormDB) DatabaseType() DatabaseType

DatabaseType returns the type of database (postgres or oracle)

func (*GormDB) LogStats

func (g *GormDB) LogStats()

LogStats logs statistics about the database connection pool

func (*GormDB) Ping

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

Ping checks if the database connection is alive

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

type HealthMonitor

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

HealthMonitor provides background connection pool health monitoring

func NewHealthMonitor

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

NewHealthMonitor creates a new health monitor for the given database connection pool

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)

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.

func (*HealthMonitor) Stop

func (h *HealthMonitor) Stop()

Stop stops the health monitor

type Manager

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

Manager handles database connections

func GetGlobalManager

func GetGlobalManager() *Manager

GetGlobalManager returns the global database manager singleton. Returns nil if SetGlobalManager has not been called.

func NewManager

func NewManager() *Manager

NewManager creates a new database manager

func NewMockManager

func NewMockManager() *Manager

NewMockManager creates a new mock Manager

func (*Manager) Close

func (m *Manager) Close() error

Close closes all database connections

func (*Manager) Gorm

func (m *Manager) Gorm() *GormDB

Gorm returns the GORM database connection

func (*Manager) InitGorm

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

InitGorm initializes the GORM database connection (supports PostgreSQL, Oracle, MySQL, SQL Server, SQLite)

func (*Manager) InitRedis

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

InitRedis initializes the Redis connection

func (*Manager) LogConnectionStats

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

LogConnectionStats logs statistics about all database connections

func (*Manager) Ping

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

Ping checks if all database connections are alive

func (*Manager) Redis

func (m *Manager) Redis() *RedisDB

Redis returns the Redis connection

type MockManager

type MockManager struct {
}

MockManager is a mock implementation of Manager for testing

type MockRedisDB

type MockRedisDB struct{}

MockRedisDB is a mock implementation of RedisDB for testing

func NewMockRedisDB

func NewMockRedisDB() *MockRedisDB

NewMockRedisDB creates a new mock RedisDB

func (*MockRedisDB) Close

func (db *MockRedisDB) Close() error

Close is a mock implementation that does nothing

func (*MockRedisDB) Del

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

Del is a mock implementation that always succeeds

func (*MockRedisDB) Expire

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

Expire is a mock implementation that always succeeds

func (*MockRedisDB) Get

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

Get is a mock implementation that returns an empty string

func (*MockRedisDB) HDel

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

HDel is a mock implementation that always succeeds

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

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

func (*MockRedisDB) HSet

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

HSet is a mock implementation that always succeeds

func (*MockRedisDB) Ping

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

Ping is a mock implementation that always succeeds

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

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.

func (*OracleNamingStrategy) CheckerName

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

CheckerName converts checker constraint name to uppercase for Oracle

func (*OracleNamingStrategy) ColumnName

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

ColumnName converts column name to uppercase for Oracle

func (*OracleNamingStrategy) IndexName

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

IndexName converts index name to uppercase for Oracle

func (*OracleNamingStrategy) JoinTableName

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

JoinTableName converts join table name to uppercase for Oracle

func (*OracleNamingStrategy) RelationshipFKName

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

RelationshipFKName converts foreign key name to uppercase for Oracle

func (*OracleNamingStrategy) TableName

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

TableName converts table name to uppercase for Oracle

func (*OracleNamingStrategy) UniqueName

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

UniqueName converts unique constraint name to uppercase for Oracle

type PatternDoc

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

PatternDoc represents documentation for a key pattern

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

type RedisDB

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

RedisDB represents a Redis database connection

func NewRedisDB

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

NewRedisDB creates a new Redis database connection

func (*RedisDB) Close

func (db *RedisDB) Close() error

Close closes the Redis connection

func (*RedisDB) Del

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

Del deletes a key

func (*RedisDB) Expire

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

Expire sets an expiration on a 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.

func (*RedisDB) GetClient

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

GetClient returns the Redis client

func (*RedisDB) HDel

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

HDel deletes a hash field

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.

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.

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.

func (*RedisDB) LogStats

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

LogStats logs statistics about the Redis connection

func (*RedisDB) Ping

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

Ping checks if the Redis connection is alive

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.

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.

type RedisHealthChecker

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

RedisHealthChecker performs health checks on Redis

func NewRedisHealthChecker

func NewRedisHealthChecker(client *redis.Client) *RedisHealthChecker

NewRedisHealthChecker creates a new Redis health checker

func (*RedisHealthChecker) CheckHealth

CheckHealth performs a comprehensive health check on Redis

func (*RedisHealthChecker) GetKeyStatistics

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

GetKeyStatistics returns statistics about keys in Redis

func (*RedisHealthChecker) LogHealthCheck

func (h *RedisHealthChecker) LogHealthCheck(result HealthCheckResult)

LogHealthCheck logs the health check results

type RedisKeyBuilder

type RedisKeyBuilder struct{}

RedisKeyBuilder provides methods to build Redis keys following the defined patterns

func NewRedisKeyBuilder

func NewRedisKeyBuilder() *RedisKeyBuilder

NewRedisKeyBuilder creates a new Redis key builder

func (*RedisKeyBuilder) AuthRefreshKey

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

AuthRefreshKey builds an auth refresh token key

func (*RedisKeyBuilder) AuthStateKey

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

AuthStateKey builds an OAuth state key

func (*RedisKeyBuilder) AuthTokenKey

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

AuthTokenKey builds an auth token key

func (*RedisKeyBuilder) BlacklistTokenKey

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

BlacklistTokenKey builds a token blacklist key

func (*RedisKeyBuilder) CacheAssetKey

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

CacheAssetKey builds an asset cache key

func (*RedisKeyBuilder) CacheAuthKey

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

CacheAuthKey builds an authorization data cache key

func (*RedisKeyBuilder) CacheCellsKey

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

CacheCellsKey builds a diagram cells collection cache key

func (*RedisKeyBuilder) CacheDiagramKey

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

CacheDiagramKey builds a diagram cache key

func (*RedisKeyBuilder) CacheDocumentKey

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

CacheDocumentKey builds a document cache key

func (*RedisKeyBuilder) CacheListKey

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

CacheListKey builds a paginated list cache key

func (*RedisKeyBuilder) CacheMetadataKey

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

CacheMetadataKey builds a metadata collection cache key

func (*RedisKeyBuilder) CacheNoteKey

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

CacheNoteKey builds a note cache key

func (*RedisKeyBuilder) CacheRepositoryKey

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

CacheRepositoryKey builds a source code cache key

func (*RedisKeyBuilder) CacheThreatKey

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

CacheThreatKey builds a individual threat cache key

func (*RedisKeyBuilder) CacheThreatModelKey

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

CacheThreatModelKey builds a threat model cache key

func (*RedisKeyBuilder) CacheUserByEmailKey

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

CacheUserByEmailKey builds a user cache key by email

func (*RedisKeyBuilder) CacheUserByProviderKey

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

CacheUserByProviderKey builds a user cache key by provider and provider user ID

func (*RedisKeyBuilder) CacheUserKey

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

CacheUserKey builds a user cache key by internal UUID

func (*RedisKeyBuilder) LockKey

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

LockKey builds a distributed lock key

func (*RedisKeyBuilder) ParseRateLimitKey

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

ParseRateLimitKey parses a rate limit key into its components

func (*RedisKeyBuilder) ParseSessionKey

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

ParseSessionKey parses a session key into its components

func (*RedisKeyBuilder) RateLimitAPIKey

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

RateLimitAPIKey builds an API key rate limit key

func (*RedisKeyBuilder) RateLimitGlobalKey

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

RateLimitGlobalKey builds a global rate limit key

func (*RedisKeyBuilder) RateLimitUserKey

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

RateLimitUserKey builds a user rate limit key

func (*RedisKeyBuilder) SessionKey

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

SessionKey builds a session key

func (*RedisKeyBuilder) TempExportKey

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

TempExportKey builds a temporary export job key

func (*RedisKeyBuilder) TempImportKey

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

TempImportKey builds a temporary import job key

type RedisKeyPattern

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

RedisKeyPattern defines a pattern for Redis keys

type RedisKeyValidator

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

RedisKeyValidator validates Redis keys against defined patterns

func NewRedisKeyValidator

func NewRedisKeyValidator() *RedisKeyValidator

NewRedisKeyValidator creates a new Redis key validator

func (*RedisKeyValidator) GetPatternDocumentation

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

GetPatternDocumentation returns documentation for all patterns

func (*RedisKeyValidator) GetPatternForKey

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

GetPatternForKey returns the pattern that matches the given key

func (*RedisKeyValidator) LogValidationResults

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

LogValidationResults logs the validation results

func (*RedisKeyValidator) ScanAndValidate

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

ScanAndValidate scans all keys and validates them

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

func (*RedisKeyValidator) ValidateKey

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

ValidateKey validates a Redis key against defined patterns

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

type RetryConfig

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

RetryConfig holds configuration for retry behavior

func DefaultRetryConfig

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig returns reasonable defaults for transaction retries

type TestDB

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

TestDB holds a test database connection and cleanup function

func MustCreateTestDB

func MustCreateTestDB(t *testing.T) *TestDB

MustCreateTestDB creates a test DB, failing the test 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.

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.

func (*TestDB) SeedGroup

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

SeedGroup creates a test group and returns it.

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.

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.

func (*TestDB) SeedSurveyTemplate

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

SeedSurveyTemplate creates a test survey template and returns it.

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.

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.

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.

func (*TestDB) SeedUser

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

SeedUser creates a test user and returns it.

type ValidationResult

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

ValidationResult represents the result of validating a Redis key

Jump to

Keyboard shortcuts

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