Documentation
¶
Index ¶
- Variables
- func RecordReconnectAttempt(name string, dbType DatabaseType, success bool)
- func ResetInstance()
- func SetupManager(cfg ManagerConfig) error
- type ConfigurationError
- type Connection
- type ConnectionConfig
- func (cc *ConnectionConfig) ApplyDefaults(global *ManagerConfig)
- func (cc *ConnectionConfig) BuildDSN() (string, error)
- func (cc *ConnectionConfig) GetConnMaxIdleTime() *time.Duration
- func (cc *ConnectionConfig) GetConnMaxLifetime() *time.Duration
- func (cc *ConnectionConfig) GetConnectTimeout() time.Duration
- func (cc *ConnectionConfig) GetDatabase() string
- func (cc *ConnectionConfig) GetEnableLogging() bool
- func (cc *ConnectionConfig) GetEnableMetrics() bool
- func (cc *ConnectionConfig) GetFilePath() string
- func (cc *ConnectionConfig) GetHost() string
- func (cc *ConnectionConfig) GetMaxIdleConns() *int
- func (cc *ConnectionConfig) GetMaxOpenConns() *int
- func (cc *ConnectionConfig) GetName() string
- func (cc *ConnectionConfig) GetPassword() string
- func (cc *ConnectionConfig) GetPort() int
- func (cc *ConnectionConfig) GetQueryTimeout() time.Duration
- func (cc *ConnectionConfig) GetReadPreference() string
- func (cc *ConnectionConfig) GetType() string
- func (cc *ConnectionConfig) GetUser() string
- func (cc *ConnectionConfig) Validate() error
- type ConnectionError
- type ConnectionStats
- type DatabaseType
- type Manager
- type ManagerConfig
- type ManagerStats
- type ORMType
- type Provider
Constants ¶
This section is empty.
Variables ¶
var ( // ErrConnectionNotFound is returned when a connection with the given name doesn't exist ErrConnectionNotFound = errors.New("connection not found") // ErrInvalidConfiguration is returned when the configuration is invalid ErrInvalidConfiguration = errors.New("invalid configuration") // ErrConnectionClosed is returned when attempting to use a closed connection ErrConnectionClosed = errors.New("connection is closed") // ErrNotSQLDatabase is returned when attempting SQL operations on a non-SQL database ErrNotSQLDatabase = errors.New("not a SQL database") // ErrNotMongoDB is returned when attempting MongoDB operations on a non-MongoDB connection ErrNotMongoDB = errors.New("not a MongoDB connection") // ErrUnsupportedDatabase is returned when the database type is not supported ErrUnsupportedDatabase = errors.New("unsupported database type") // ErrNoDefaultConnection is returned when no default connection is configured ErrNoDefaultConnection = errors.New("no default connection configured") // ErrAlreadyConnected is returned when attempting to connect an already connected connection ErrAlreadyConnected = errors.New("already connected") )
Common errors
Functions ¶
func RecordReconnectAttempt ¶
func RecordReconnectAttempt(name string, dbType DatabaseType, success bool)
RecordReconnectAttempt records a reconnection attempt
func ResetInstance ¶ added in v1.0.7
func ResetInstance()
ResetInstance resets the singleton instance (primarily for testing purposes). WARNING: This should only be used in tests. Calling this in production code while the manager is in use can lead to undefined behavior.
func SetupManager ¶ added in v1.0.7
func SetupManager(cfg ManagerConfig) error
SetupManager initializes the singleton database manager with the provided configuration. This function must be called before GetInstance(). Returns an error if the manager is already initialized or if configuration is invalid.
Types ¶
type ConfigurationError ¶
ConfigurationError wraps configuration-related errors
func NewConfigurationError ¶
func NewConfigurationError(field string, err error) *ConfigurationError
NewConfigurationError creates a new ConfigurationError
func (*ConfigurationError) Error ¶
func (e *ConfigurationError) Error() string
func (*ConfigurationError) Unwrap ¶
func (e *ConfigurationError) Unwrap() error
type Connection ¶
type Connection interface {
// Metadata
Name() string
Type() DatabaseType
// ORM Access (SQL databases only)
Bun() (*bun.DB, error)
GORM() (*gorm.DB, error)
Native() (*sql.DB, error)
// Common Database interface (for SQL databases)
Database() (common.Database, error)
// MongoDB Access (MongoDB only)
MongoDB() (*mongo.Client, error)
// Lifecycle
Connect(ctx context.Context) error
Close() error
HealthCheck(ctx context.Context) error
Reconnect(ctx context.Context) error
// Stats
Stats() *ConnectionStats
}
Connection represents a single named database connection
type ConnectionConfig ¶
type ConnectionConfig struct {
// Name is the unique name of this connection
Name string `mapstructure:"name"`
// Type is the database type (postgres, sqlite, mssql, mongodb)
Type DatabaseType `mapstructure:"type"`
// DSN is the complete Data Source Name / connection string
// If provided, this takes precedence over individual connection parameters
DSN string `mapstructure:"dsn"`
// Connection parameters (used if DSN is not provided)
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
User string `mapstructure:"user"`
Password string `mapstructure:"password"`
Database string `mapstructure:"database"`
// PostgreSQL/MSSQL specific
SSLMode string `mapstructure:"sslmode"` // disable, require, verify-ca, verify-full
Schema string `mapstructure:"schema"` // Default schema
// SQLite specific
FilePath string `mapstructure:"filepath"`
// MongoDB specific
AuthSource string `mapstructure:"auth_source"`
ReplicaSet string `mapstructure:"replica_set"`
ReadPreference string `mapstructure:"read_preference"` // primary, secondary, etc.
// Connection pool settings (overrides global defaults)
MaxOpenConns *int `mapstructure:"max_open_conns"`
MaxIdleConns *int `mapstructure:"max_idle_conns"`
ConnMaxLifetime *time.Duration `mapstructure:"conn_max_lifetime"`
ConnMaxIdleTime *time.Duration `mapstructure:"conn_max_idle_time"`
// Timeouts
ConnectTimeout time.Duration `mapstructure:"connect_timeout"`
QueryTimeout time.Duration `mapstructure:"query_timeout"`
// Features
EnableTracing bool `mapstructure:"enable_tracing"`
EnableMetrics bool `mapstructure:"enable_metrics"`
EnableLogging bool `mapstructure:"enable_logging"`
// DefaultORM specifies which ORM to use for the Database() method
// Options: "bun", "gorm", "native"
DefaultORM string `mapstructure:"default_orm"`
// Tags for organization and filtering
Tags map[string]string `mapstructure:"tags"`
}
ConnectionConfig defines configuration for a single database connection
func (*ConnectionConfig) ApplyDefaults ¶
func (cc *ConnectionConfig) ApplyDefaults(global *ManagerConfig)
ApplyDefaults applies default values and global settings to the connection configuration
func (*ConnectionConfig) BuildDSN ¶
func (cc *ConnectionConfig) BuildDSN() (string, error)
BuildDSN builds a connection string from individual parameters
func (*ConnectionConfig) GetConnMaxIdleTime ¶
func (cc *ConnectionConfig) GetConnMaxIdleTime() *time.Duration
func (*ConnectionConfig) GetConnMaxLifetime ¶
func (cc *ConnectionConfig) GetConnMaxLifetime() *time.Duration
func (*ConnectionConfig) GetConnectTimeout ¶
func (cc *ConnectionConfig) GetConnectTimeout() time.Duration
func (*ConnectionConfig) GetDatabase ¶
func (cc *ConnectionConfig) GetDatabase() string
func (*ConnectionConfig) GetEnableLogging ¶
func (cc *ConnectionConfig) GetEnableLogging() bool
func (*ConnectionConfig) GetEnableMetrics ¶
func (cc *ConnectionConfig) GetEnableMetrics() bool
func (*ConnectionConfig) GetFilePath ¶
func (cc *ConnectionConfig) GetFilePath() string
func (*ConnectionConfig) GetHost ¶
func (cc *ConnectionConfig) GetHost() string
func (*ConnectionConfig) GetMaxIdleConns ¶
func (cc *ConnectionConfig) GetMaxIdleConns() *int
func (*ConnectionConfig) GetMaxOpenConns ¶
func (cc *ConnectionConfig) GetMaxOpenConns() *int
func (*ConnectionConfig) GetName ¶
func (cc *ConnectionConfig) GetName() string
Getter methods to implement providers.ConnectionConfig interface
func (*ConnectionConfig) GetPassword ¶
func (cc *ConnectionConfig) GetPassword() string
func (*ConnectionConfig) GetPort ¶
func (cc *ConnectionConfig) GetPort() int
func (*ConnectionConfig) GetQueryTimeout ¶
func (cc *ConnectionConfig) GetQueryTimeout() time.Duration
func (*ConnectionConfig) GetReadPreference ¶
func (cc *ConnectionConfig) GetReadPreference() string
func (*ConnectionConfig) GetType ¶
func (cc *ConnectionConfig) GetType() string
func (*ConnectionConfig) GetUser ¶
func (cc *ConnectionConfig) GetUser() string
func (*ConnectionConfig) Validate ¶
func (cc *ConnectionConfig) Validate() error
Validate validates the connection configuration
type ConnectionError ¶
ConnectionError wraps errors that occur during connection operations
func NewConnectionError ¶
func NewConnectionError(name, operation string, err error) *ConnectionError
NewConnectionError creates a new ConnectionError
func (*ConnectionError) Error ¶
func (e *ConnectionError) Error() string
func (*ConnectionError) Unwrap ¶
func (e *ConnectionError) Unwrap() error
type ConnectionStats ¶
type ConnectionStats struct {
Name string
Type DatabaseType
Connected bool
LastHealthCheck time.Time
HealthCheckStatus string
// SQL connection pool stats
OpenConnections int
InUse int
Idle int
WaitCount int64
WaitDuration time.Duration
MaxIdleClosed int64
MaxLifetimeClosed int64
}
ConnectionStats contains statistics about a database connection
type DatabaseType ¶
type DatabaseType string
DatabaseType represents the type of database
const ( // DatabaseTypePostgreSQL represents PostgreSQL database DatabaseTypePostgreSQL DatabaseType = "postgres" // DatabaseTypeSQLite represents SQLite database DatabaseTypeSQLite DatabaseType = "sqlite" // DatabaseTypeMSSQL represents Microsoft SQL Server database DatabaseTypeMSSQL DatabaseType = "mssql" // DatabaseTypeMongoDB represents MongoDB database DatabaseTypeMongoDB DatabaseType = "mongodb" )
type Manager ¶
type Manager interface {
// Connection retrieval
Get(name string) (Connection, error)
GetDefault() (Connection, error)
GetAll() map[string]Connection
// Default database management
GetDefaultDatabase() (common.Database, error)
SetDefaultDatabase(name string) error
// Lifecycle
Connect(ctx context.Context) error
Close() error
HealthCheck(ctx context.Context) error
// Stats
Stats() *ManagerStats
}
Manager manages multiple named database connections
func GetInstance ¶ added in v1.0.7
GetInstance returns the singleton instance of the database manager. Returns an error if SetupManager has not been called yet.
func NewManager ¶
func NewManager(cfg ManagerConfig) (Manager, error)
NewManager creates a new database connection manager
type ManagerConfig ¶
type ManagerConfig struct {
// DefaultConnection is the name of the default connection to use
DefaultConnection string `mapstructure:"default_connection"`
// Connections is a map of connection name to connection configuration
Connections map[string]ConnectionConfig `mapstructure:"connections"`
// Global connection pool defaults
MaxOpenConns int `mapstructure:"max_open_conns"`
MaxIdleConns int `mapstructure:"max_idle_conns"`
ConnMaxLifetime time.Duration `mapstructure:"conn_max_lifetime"`
ConnMaxIdleTime time.Duration `mapstructure:"conn_max_idle_time"`
// Retry policy
RetryAttempts int `mapstructure:"retry_attempts"`
RetryDelay time.Duration `mapstructure:"retry_delay"`
RetryMaxDelay time.Duration `mapstructure:"retry_max_delay"`
// Health checks
HealthCheckInterval time.Duration `mapstructure:"health_check_interval"`
EnableAutoReconnect bool `mapstructure:"enable_auto_reconnect"`
}
ManagerConfig contains configuration for the database connection manager
func DefaultManagerConfig ¶
func DefaultManagerConfig() ManagerConfig
DefaultManagerConfig returns a ManagerConfig with sensible defaults
func FromConfig ¶
func FromConfig(cfg config.DBManagerConfig) ManagerConfig
FromConfig converts config.DBManagerConfig to internal ManagerConfig
func (*ManagerConfig) ApplyDefaults ¶
func (c *ManagerConfig) ApplyDefaults()
ApplyDefaults applies default values to the manager configuration
func (*ManagerConfig) Validate ¶
func (c *ManagerConfig) Validate() error
Validate validates the manager configuration
type ManagerStats ¶
type ManagerStats struct {
TotalConnections int
HealthyCount int
UnhealthyCount int
ConnectionStats map[string]*ConnectionStats
}
ManagerStats contains statistics about the connection manager