 Documentation
      ¶
      Documentation
      ¶
    
    
  
    
  
    Overview ¶
Package database - Connection Management System Migrated from ClubPulse to gopherkit with significant improvements
Package database - Fallback Management System Migrado de ClubPulse a gopherkit con mejoras significativas
Package database - Health Checking System Migrado de ClubPulse a gopherkit con mejoras significativas
Package database - Tenant Context Management System Migrado de ClubPulse a gopherkit con mejoras significativas
Index ¶
- type CheckDetail
- type Config
- type ConnectionManager
- func (cm *ConnectionManager) Close() error
- func (cm *ConnectionManager) ExecuteInSchema(schema string, query string, args ...interface{}) (*sql.Rows, error)
- func (cm *ConnectionManager) ExecuteWithMetrics(query string, args ...interface{}) (*sql.Rows, error)
- func (cm *ConnectionManager) GetDB() *sql.DB
- func (cm *ConnectionManager) GetHealthStatus() map[string]interface{}
- func (cm *ConnectionManager) GetQueryHistory() []QueryMetric
- func (cm *ConnectionManager) ResetMetrics()
- func (cm *ConnectionManager) Transaction(fn func(*sql.Tx) error) error
 
- type ConnectionMetrics
- type DatabaseMode
- type DefaultLogger
- type FallbackConfig
- type FallbackManager
- func (fm *FallbackManager) ForceRecovery() error
- func (fm *FallbackManager) GetCurrentMode() DatabaseMode
- func (fm *FallbackManager) GetMetrics() *FallbackMetrics
- func (fm *FallbackManager) IsInFallbackMode() bool
- func (fm *FallbackManager) SetAlertCallback(callback func(string, error))
- func (fm *FallbackManager) SetPrimaryDB(db *sql.DB)
- func (fm *FallbackManager) Stop()
 
- type FallbackMetrics
- type GormLogger
- func (gl *GormLogger) Error(ctx context.Context, msg string, data ...interface{})
- func (gl *GormLogger) Info(ctx context.Context, msg string, data ...interface{})
- func (gl *GormLogger) LogMode(level gormlogger.LogLevel) gormlogger.Interface
- func (gl *GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error)
- func (gl *GormLogger) Warn(ctx context.Context, msg string, data ...interface{})
 
- type HealthCheckResult
- type HealthChecker
- func (hc *HealthChecker) CheckAllServices(ctx context.Context) ([]*HealthCheckResult, error)
- func (hc *HealthChecker) CheckDatabase(ctx context.Context, db *sql.DB, serviceName string) *HealthCheckResult
- func (hc *HealthChecker) CheckWithRetry(ctx context.Context, db *sql.DB, serviceName string, maxRetries int) *HealthCheckResult
- func (hc *HealthChecker) GenerateHealthReport(ctx context.Context) (HealthReport, error)
- func (hc *HealthChecker) GetMetrics() *HealthMetrics
- func (hc *HealthChecker) GetOverallHealth(results []*HealthCheckResult) (HealthStatus, Severity)
 
- type HealthMetrics
- type HealthPoint
- type HealthReport
- type HealthStatus
- type HealthSummary
- type Logger
- type PostgresClient
- func (pc *PostgresClient) Close() error
- func (pc *PostgresClient) GetDB() *gorm.DB
- func (pc *PostgresClient) GetSQLDB() *sql.DB
- func (pc *PostgresClient) HealthCheck() observability.HealthCheck
- func (pc *PostgresClient) Stats() sql.DBStats
- func (pc *PostgresClient) Transaction(ctx context.Context, fn func(*gorm.DB) error) error
- func (pc *PostgresClient) WithContext(ctx context.Context) *gorm.DB
 
- type PostgresOptions
- type QueryMetric
- type RLSStatus
- type Repository
- func (r *Repository) Create(ctx context.Context, model interface{}) error
- func (r *Repository) Delete(ctx context.Context, model interface{}, id interface{}) error
- func (r *Repository) GetByID(ctx context.Context, model interface{}, id interface{}) error
- func (r *Repository) Update(ctx context.Context, model interface{}) error
 
- type Severity
- type TenantCache
- type TenantCacheEntry
- type TenantConfig
- type TenantContextManager
- func (tcm *TenantContextManager) ClearTenantContext(ctx context.Context) error
- func (tcm *TenantContextManager) GetCacheStats() map[string]interface{}
- func (tcm *TenantContextManager) GetConfig() *TenantConfig
- func (tcm *TenantContextManager) GetCurrentTenant(ctx context.Context) (string, error)
- func (tcm *TenantContextManager) GetMetrics() *TenantMetrics
- func (tcm *TenantContextManager) GetTenantStats(ctx context.Context, tenantID string, tables []string) ([]TenantStats, error)
- func (tcm *TenantContextManager) HealthCheck(ctx context.Context) error
- func (tcm *TenantContextManager) ResetMetrics()
- func (tcm *TenantContextManager) SetTenantContext(ctx context.Context, tenantID string) error
- func (tcm *TenantContextManager) TenantAwareExec(ctx context.Context, tenantID, query string, args ...interface{}) (sql.Result, error)
- func (tcm *TenantContextManager) TenantAwareQuery(ctx context.Context, tenantID, query string, args ...interface{}) (*sql.Rows, error)
- func (tcm *TenantContextManager) ValidateTenantAccess(ctx context.Context, tenantID, resourceTable, resourceID string) (bool, error)
- func (tcm *TenantContextManager) VerifyRLSStatus(ctx context.Context) ([]RLSStatus, error)
- func (tcm *TenantContextManager) WithTenantContext(ctx context.Context, tenantID string, fn func(context.Context) error) error
 
- type TenantMetrics
- type TenantOperation
- type TenantStats
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type CheckDetail ¶ added in v1.0.2
type CheckDetail struct {
	Name        string        `json:"name"`
	Status      HealthStatus  `json:"status"`
	Duration    time.Duration `json:"duration"`
	Description string        `json:"description"`
	Error       string        `json:"error,omitempty"`
}
    CheckDetail detalle de una verificación específica
type Config ¶ added in v1.0.2
type Config struct {
	// Common fields
	DatabaseMode DatabaseMode `json:"database_mode"`
	DatabaseURL  string       `json:"database_url"`
	// Single mode specific
	DatabaseSchema string `json:"database_schema"`
	// Connection pool settings
	MaxOpenConns        int           `json:"max_open_conns"`
	MaxIdleConns        int           `json:"max_idle_conns"`
	ConnMaxLifetime     time.Duration `json:"conn_max_lifetime"`
	ConnMaxIdleTime     time.Duration `json:"conn_max_idle_time"`
	EnableFallback      bool          `json:"enable_fallback"`
	FallbackDatabaseURL string        `json:"fallback_database_url"`
	// Monitoring and observability
	EnableMetrics        bool          `json:"enable_metrics"`
	ServiceName          string        `json:"service_name"`
	EnableHealthChecks   bool          `json:"enable_health_checks"`
	HealthCheckInterval  time.Duration `json:"health_check_interval"`
	EnableRetryLogic     bool          `json:"enable_retry_logic"`
	MaxRetryAttempts     int           `json:"max_retry_attempts"`
	RetryBackoffDuration time.Duration `json:"retry_backoff_duration"`
	ConnectionTimeout    time.Duration `json:"connection_timeout"`
	EnableSlowQueryLog   bool          `json:"enable_slow_query_log"`
	SlowQueryThreshold   time.Duration `json:"slow_query_threshold"`
}
    Config holds database configuration with enhanced options
func DefaultConfig ¶ added in v1.0.2
func DefaultConfig() *Config
DefaultConfig retorna configuración por defecto mejorada
type ConnectionManager ¶ added in v1.0.2
type ConnectionManager struct {
	// contains filtered or unexported fields
}
    ConnectionManager manages database connections with enhanced features
func GetInstance ¶ added in v1.0.2
func GetInstance(config *Config) (*ConnectionManager, error)
GetInstance returns singleton instance of ConnectionManager
func NewConnectionManager ¶ added in v1.0.2
func NewConnectionManager(config *Config) (*ConnectionManager, error)
NewConnectionManager creates a new enhanced connection manager
func (*ConnectionManager) Close ¶ added in v1.0.2
func (cm *ConnectionManager) Close() error
Close closes all database connections with graceful shutdown
func (*ConnectionManager) ExecuteInSchema ¶ added in v1.0.2
func (cm *ConnectionManager) ExecuteInSchema(schema string, query string, args ...interface{}) (*sql.Rows, error)
ExecuteInSchema executes a query in a specific schema (single mode only) with improvements
func (*ConnectionManager) ExecuteWithMetrics ¶ added in v1.0.2
func (cm *ConnectionManager) ExecuteWithMetrics(query string, args ...interface{}) (*sql.Rows, error)
ExecuteWithMetrics executes a query with performance metrics
func (*ConnectionManager) GetDB ¶ added in v1.0.2
func (cm *ConnectionManager) GetDB() *sql.DB
GetDB returns the active database connection with intelligent fallback
func (*ConnectionManager) GetHealthStatus ¶ added in v1.0.2
func (cm *ConnectionManager) GetHealthStatus() map[string]interface{}
GetHealthStatus returns current enhanced health status
func (*ConnectionManager) GetQueryHistory ¶ added in v1.0.2
func (cm *ConnectionManager) GetQueryHistory() []QueryMetric
GetQueryHistory returns recent query history
func (*ConnectionManager) ResetMetrics ¶ added in v1.0.2
func (cm *ConnectionManager) ResetMetrics()
ResetMetrics resets all connection metrics
func (*ConnectionManager) Transaction ¶ added in v1.0.2
func (cm *ConnectionManager) Transaction(fn func(*sql.Tx) error) error
Transaction executes a function within a database transaction with enhanced error handling
type ConnectionMetrics ¶ added in v1.0.2
type ConnectionMetrics struct {
	TotalConnections    int64            `json:"total_connections"`
	ActiveConnections   int64            `json:"active_connections"`
	FailedConnections   int64            `json:"failed_connections"`
	FallbackUsed        int64            `json:"fallback_used"`
	QueryTime           time.Duration    `json:"query_time"`
	SchemaQueries       map[string]int64 `json:"schema_queries"`
	SlowQueries         int64            `json:"slow_queries"`
	ConnectionErrors    map[string]int64 `json:"connection_errors"`
	QueryHistory        []QueryMetric    `json:"query_history"`
	HealthCheckFailures int64            `json:"health_check_failures"`
	RecoveryAttempts    int64            `json:"recovery_attempts"`
	LastError           string           `json:"last_error"`
	LastErrorTime       time.Time        `json:"last_error_time"`
	// contains filtered or unexported fields
}
    ConnectionMetrics tracks enhanced connection statistics
type DatabaseMode ¶ added in v1.0.2
type DatabaseMode string
DatabaseMode represents the database operation mode
const ( ModeSingle DatabaseMode = "single" ModeMulti DatabaseMode = "multi" )
type DefaultLogger ¶ added in v1.0.2
type DefaultLogger struct{}
    DefaultLogger implementación simple de logger
func (*DefaultLogger) Debugf ¶ added in v1.0.2
func (dl *DefaultLogger) Debugf(format string, args ...interface{})
func (*DefaultLogger) Error ¶ added in v1.0.2
func (dl *DefaultLogger) Error(msg string)
func (*DefaultLogger) Info ¶ added in v1.0.2
func (dl *DefaultLogger) Info(msg string)
func (*DefaultLogger) Warn ¶ added in v1.0.2
func (dl *DefaultLogger) Warn(msg string)
func (*DefaultLogger) WithField ¶ added in v1.0.2
func (dl *DefaultLogger) WithField(key string, value interface{}) Logger
type FallbackConfig ¶ added in v1.0.2
type FallbackConfig struct {
	EnableAutoFallback     bool          `json:"enable_auto_fallback"`
	HealthCheckInterval    time.Duration `json:"health_check_interval"`
	FailureThreshold       int           `json:"failure_threshold"`
	RecoveryCheckInterval  time.Duration `json:"recovery_check_interval"`
	FallbackTimeout        time.Duration `json:"fallback_timeout"`
	AlertWebhookURL        string        `json:"alert_webhook_url"`
	MaxRetryAttempts       int           `json:"max_retry_attempts"`
	RetryBackoffMultiplier float64       `json:"retry_backoff_multiplier"`
	EnableNotifications    bool          `json:"enable_notifications"`
	NotificationChannels   []string      `json:"notification_channels"`
	AutoRecoveryEnabled    bool          `json:"auto_recovery_enabled"`
	RecoveryConfidence     float64       `json:"recovery_confidence"`
}
    FallbackConfig configuración mejorada para el sistema de fallback
func DefaultFallbackConfig ¶ added in v1.0.2
func DefaultFallbackConfig() *FallbackConfig
DefaultFallbackConfig retorna configuración por defecto mejorada
type FallbackManager ¶ added in v1.0.2
type FallbackManager struct {
	// contains filtered or unexported fields
}
    FallbackManager gestiona el fallback automático entre modos de database mejorado
func NewFallbackManager ¶ added in v1.0.2
func NewFallbackManager(config *Config, logger Logger) (*FallbackManager, error)
NewFallbackManager crea un nuevo gestor de fallback mejorado
func (*FallbackManager) ForceRecovery ¶ added in v1.0.2
func (fm *FallbackManager) ForceRecovery() error
ForceRecovery fuerza un intento de recuperación manual
func (*FallbackManager) GetCurrentMode ¶ added in v1.0.2
func (fm *FallbackManager) GetCurrentMode() DatabaseMode
GetCurrentMode obtiene el modo actual de la database
func (*FallbackManager) GetMetrics ¶ added in v1.0.2
func (fm *FallbackManager) GetMetrics() *FallbackMetrics
GetMetrics retorna las métricas del fallback manager
func (*FallbackManager) IsInFallbackMode ¶ added in v1.0.2
func (fm *FallbackManager) IsInFallbackMode() bool
IsInFallbackMode verifica si está en modo fallback
func (*FallbackManager) SetAlertCallback ¶ added in v1.0.2
func (fm *FallbackManager) SetAlertCallback(callback func(string, error))
SetAlertCallback permite configurar un callback personalizado para alertas
func (*FallbackManager) SetPrimaryDB ¶ added in v1.0.2
func (fm *FallbackManager) SetPrimaryDB(db *sql.DB)
SetPrimaryDB establece la conexión primaria
func (*FallbackManager) Stop ¶ added in v1.0.2
func (fm *FallbackManager) Stop()
Stop detiene el monitoreo de fallback con limpieza mejorada
type FallbackMetrics ¶ added in v1.0.2
type FallbackMetrics struct {
	FallbackActivations  int64                    `json:"fallback_activations"`
	RecoveryAttempts     int64                    `json:"recovery_attempts"`
	SuccessfulRecoveries int64                    `json:"successful_recoveries"`
	FailedRecoveries     int64                    `json:"failed_recoveries"`
	TimeInFallbackMode   time.Duration            `json:"time_in_fallback_mode"`
	LastFallbackTime     time.Time                `json:"last_fallback_time"`
	LastRecoveryTime     time.Time                `json:"last_recovery_time"`
	HealthCheckFailures  map[string]int64         `json:"health_check_failures"`
	FallbackDuration     map[string]time.Duration `json:"fallback_duration"`
	AlertsSent           int64                    `json:"alerts_sent"`
	// contains filtered or unexported fields
}
    FallbackMetrics métricas del sistema de fallback
type GormLogger ¶
type GormLogger struct {
	// contains filtered or unexported fields
}
    Custom GORM logger that integrates with our logger
func NewGormLogger ¶
func NewGormLogger(logger logger.Logger) *GormLogger
NewGormLogger creates a new GORM logger
func (*GormLogger) Error ¶
func (gl *GormLogger) Error(ctx context.Context, msg string, data ...interface{})
Error logs error messages
func (*GormLogger) Info ¶
func (gl *GormLogger) Info(ctx context.Context, msg string, data ...interface{})
Info logs info messages
func (*GormLogger) LogMode ¶
func (gl *GormLogger) LogMode(level gormlogger.LogLevel) gormlogger.Interface
LogMode sets the log level
type HealthCheckResult ¶ added in v1.0.2
type HealthCheckResult struct {
	Service      string        `json:"service"`
	Status       HealthStatus  `json:"status"`
	ResponseTime time.Duration `json:"response_time"`
	Error        string        `json:"error,omitempty"`
	Details      interface{}   `json:"details,omitempty"`
	Timestamp    time.Time     `json:"timestamp"`
	Checks       []CheckDetail `json:"checks,omitempty"`
	Severity     Severity      `json:"severity"`
	Suggestions  []string      `json:"suggestions,omitempty"`
}
    HealthCheckResult resultado mejorado de una verificación de salud
type HealthChecker ¶ added in v1.0.2
type HealthChecker struct {
	// contains filtered or unexported fields
}
    HealthChecker realiza verificaciones de salud de databases mejorado
func NewHealthChecker ¶ added in v1.0.2
func NewHealthChecker(config *Config) *HealthChecker
NewHealthChecker crea un nuevo verificador de salud mejorado
func (*HealthChecker) CheckAllServices ¶ added in v1.0.2
func (hc *HealthChecker) CheckAllServices(ctx context.Context) ([]*HealthCheckResult, error)
CheckAllServices verifica la salud de todos los servicios con mejoras
func (*HealthChecker) CheckDatabase ¶ added in v1.0.2
func (hc *HealthChecker) CheckDatabase(ctx context.Context, db *sql.DB, serviceName string) *HealthCheckResult
CheckDatabase verifica la salud de una database específica con mejoras
func (*HealthChecker) CheckWithRetry ¶ added in v1.0.2
func (hc *HealthChecker) CheckWithRetry(ctx context.Context, db *sql.DB, serviceName string, maxRetries int) *HealthCheckResult
CheckWithRetry verifica con reintentos mejorado
func (*HealthChecker) GenerateHealthReport ¶ added in v1.0.2
func (hc *HealthChecker) GenerateHealthReport(ctx context.Context) (HealthReport, error)
GenerateHealthReport genera un reporte completo de salud mejorado
func (*HealthChecker) GetMetrics ¶ added in v1.0.2
func (hc *HealthChecker) GetMetrics() *HealthMetrics
GetMetrics retorna las métricas del health checker
func (*HealthChecker) GetOverallHealth ¶ added in v1.0.2
func (hc *HealthChecker) GetOverallHealth(results []*HealthCheckResult) (HealthStatus, Severity)
GetOverallHealth calcula el estado general de salud mejorado
type HealthMetrics ¶ added in v1.0.2
type HealthMetrics struct {
	TotalChecks      int64                    `json:"total_checks"`
	SuccessfulChecks int64                    `json:"successful_checks"`
	FailedChecks     int64                    `json:"failed_checks"`
	CheckDurations   []time.Duration          `json:"check_durations"`
	ServiceFailures  map[string]int64         `json:"service_failures"`
	LastCheckTime    time.Time                `json:"last_check_time"`
	AverageCheckTime time.Duration            `json:"average_check_time"`
	HealthTrends     map[string][]HealthPoint `json:"health_trends"`
	// contains filtered or unexported fields
}
    HealthMetrics métricas del health checker
type HealthPoint ¶ added in v1.0.2
type HealthPoint struct {
	Timestamp time.Time     `json:"timestamp"`
	Status    HealthStatus  `json:"status"`
	Duration  time.Duration `json:"duration"`
}
    HealthPoint representa un punto en el tiempo para tendencias de salud
type HealthReport ¶ added in v1.0.2
type HealthReport struct {
	Timestamp       time.Time            `json:"timestamp"`
	DatabaseMode    string               `json:"database_mode"`
	OverallHealth   HealthStatus         `json:"overall_health"`
	OverallSeverity Severity             `json:"overall_severity"`
	Services        []*HealthCheckResult `json:"services"`
	Summary         HealthSummary        `json:"summary"`
	Recommendations []string             `json:"recommendations"`
	Metrics         *HealthMetrics       `json:"metrics"`
}
    HealthReport estructura mejorada del reporte de salud
type HealthStatus ¶ added in v1.0.2
type HealthStatus string
HealthStatus estado de salud mejorado
const ( HealthStatusHealthy HealthStatus = "healthy" HealthStatusUnhealthy HealthStatus = "unhealthy" HealthStatusDegraded HealthStatus = "degraded" HealthStatusUnknown HealthStatus = "unknown" HealthStatusWarning HealthStatus = "warning" )
type HealthSummary ¶ added in v1.0.2
type HealthSummary struct {
	TotalServices     int `json:"total_services"`
	HealthyServices   int `json:"healthy_services"`
	WarningServices   int `json:"warning_services"`
	DegradedServices  int `json:"degraded_services"`
	UnhealthyServices int `json:"unhealthy_services"`
}
    HealthSummary resumen mejorado del estado de salud
type Logger ¶ added in v1.0.2
type Logger interface {
	Info(msg string)
	Warn(msg string)
	Error(msg string)
	Debugf(format string, args ...interface{})
	WithField(key string, value interface{}) Logger
}
    Logger interface para logging
type PostgresClient ¶
type PostgresClient struct {
	// contains filtered or unexported fields
}
    PostgresClient provides PostgreSQL database operations
func NewPostgresClient ¶
func NewPostgresClient(opts PostgresOptions) (*PostgresClient, error)
NewPostgresClient creates a new PostgreSQL client
func (*PostgresClient) Close ¶
func (pc *PostgresClient) Close() error
Close closes the database connection
func (*PostgresClient) GetDB ¶
func (pc *PostgresClient) GetDB() *gorm.DB
GetDB returns the GORM database instance
func (*PostgresClient) GetSQLDB ¶
func (pc *PostgresClient) GetSQLDB() *sql.DB
GetSQLDB returns the underlying sql.DB instance
func (*PostgresClient) HealthCheck ¶
func (pc *PostgresClient) HealthCheck() observability.HealthCheck
HealthCheck returns a health check for the database
func (*PostgresClient) Stats ¶
func (pc *PostgresClient) Stats() sql.DBStats
Stats returns database connection statistics
func (*PostgresClient) Transaction ¶
Transaction executes a function within a database transaction
func (*PostgresClient) WithContext ¶
func (pc *PostgresClient) WithContext(ctx context.Context) *gorm.DB
WithContext returns a new GORM DB instance with context
type PostgresOptions ¶
type PostgresOptions struct {
	Config config.DatabaseConfig
	Logger logger.Logger
	Models []interface{} // Models to auto-migrate
}
    PostgresOptions holds options for PostgreSQL client
type QueryMetric ¶ added in v1.0.2
type QueryMetric struct {
	Query     string        `json:"query"`
	Duration  time.Duration `json:"duration"`
	Success   bool          `json:"success"`
	Error     string        `json:"error,omitempty"`
	Timestamp time.Time     `json:"timestamp"`
}
    QueryMetric representa métricas de una query individual
type RLSStatus ¶ added in v1.0.2
type RLSStatus struct {
	DatabaseName string `db:"database_name" json:"database_name"`
	TableName    string `db:"table_name" json:"table_name"`
	RLSEnabled   bool   `db:"rls_enabled" json:"rls_enabled"`
	PolicyCount  int    `db:"policy_count" json:"policy_count"`
}
    RLSStatus representa el estado de Row Level Security para una tabla
type Repository ¶
type Repository struct {
	// contains filtered or unexported fields
}
    Repository provides common repository patterns
func NewRepository ¶
func NewRepository(db *gorm.DB, logger logger.Logger) *Repository
NewRepository creates a new repository instance
func (*Repository) Create ¶
func (r *Repository) Create(ctx context.Context, model interface{}) error
Create creates a new record
func (*Repository) Delete ¶
func (r *Repository) Delete(ctx context.Context, model interface{}, id interface{}) error
Delete deletes a record
type TenantCache ¶ added in v1.0.2
type TenantCache struct {
	// contains filtered or unexported fields
}
    TenantCache cache simple para contextos de tenant
func NewTenantCache ¶ added in v1.0.2
func NewTenantCache(ttl time.Duration, maxSize int) *TenantCache
NewTenantCache crea un nuevo cache de tenants
func (*TenantCache) Get ¶ added in v1.0.2
func (tc *TenantCache) Get(key string) (string, bool)
Get obtiene un tenant del cache
func (*TenantCache) Set ¶ added in v1.0.2
func (tc *TenantCache) Set(key, tenantID string)
Set almacena un tenant en el cache
type TenantCacheEntry ¶ added in v1.0.2
type TenantCacheEntry struct {
	TenantID string    `json:"tenant_id"`
	SetTime  time.Time `json:"set_time"`
	LastUsed time.Time `json:"last_used"`
	UseCount int64     `json:"use_count"`
}
    TenantCacheEntry entrada del cache de tenant
type TenantConfig ¶ added in v1.0.2
type TenantConfig struct {
	EnableCaching        bool          `json:"enable_caching"`
	CacheTTL             time.Duration `json:"cache_ttl"`
	EnableValidation     bool          `json:"enable_validation"`
	EnableAuditLog       bool          `json:"enable_audit_log"`
	MaxConcurrentTenants int           `json:"max_concurrent_tenants"`
	TenantTimeout        time.Duration `json:"tenant_timeout"`
	EnableMetrics        bool          `json:"enable_metrics"`
	EnableSecurityChecks bool          `json:"enable_security_checks"`
	DefaultTenantID      string        `json:"default_tenant_id"`
}
    TenantConfig configuración del sistema de multi-tenancy
func DefaultTenantConfig ¶ added in v1.0.2
func DefaultTenantConfig() *TenantConfig
DefaultTenantConfig retorna configuración por defecto
type TenantContextManager ¶ added in v1.0.2
type TenantContextManager struct {
	// contains filtered or unexported fields
}
    TenantContextManager maneja el contexto de tenant en la base de datos mejorado para implementar Row Level Security (RLS) con funcionalidades avanzadas
func NewTenantContextManager ¶ added in v1.0.2
func NewTenantContextManager(db *sqlx.DB, logger Logger, config *TenantConfig) *TenantContextManager
NewTenantContextManager crea una nueva instancia mejorada del manejador de contexto de tenant
func (*TenantContextManager) ClearTenantContext ¶ added in v1.0.2
func (tcm *TenantContextManager) ClearTenantContext(ctx context.Context) error
ClearTenantContext limpia el contexto de tenant de la sesión con mejoras
func (*TenantContextManager) GetCacheStats ¶ added in v1.0.2
func (tcm *TenantContextManager) GetCacheStats() map[string]interface{}
GetCacheStats retorna estadísticas del cache
func (*TenantContextManager) GetConfig ¶ added in v1.0.2
func (tcm *TenantContextManager) GetConfig() *TenantConfig
GetConfig retorna la configuración actual
func (*TenantContextManager) GetCurrentTenant ¶ added in v1.0.2
func (tcm *TenantContextManager) GetCurrentTenant(ctx context.Context) (string, error)
GetCurrentTenant obtiene el tenant_id actual de la sesión de base de datos con mejoras
func (*TenantContextManager) GetMetrics ¶ added in v1.0.2
func (tcm *TenantContextManager) GetMetrics() *TenantMetrics
GetMetrics retorna las métricas del tenant context manager
func (*TenantContextManager) GetTenantStats ¶ added in v1.0.2
func (tcm *TenantContextManager) GetTenantStats(ctx context.Context, tenantID string, tables []string) ([]TenantStats, error)
GetTenantStats obtiene estadísticas de datos para un tenant específico mejorado
func (*TenantContextManager) HealthCheck ¶ added in v1.0.2
func (tcm *TenantContextManager) HealthCheck(ctx context.Context) error
HealthCheck verifica que el sistema de multi-tenancy esté funcionando correctamente mejorado
func (*TenantContextManager) ResetMetrics ¶ added in v1.0.2
func (tcm *TenantContextManager) ResetMetrics()
ResetMetrics reinicia todas las métricas
func (*TenantContextManager) SetTenantContext ¶ added in v1.0.2
func (tcm *TenantContextManager) SetTenantContext(ctx context.Context, tenantID string) error
SetTenantContext establece el contexto de tenant en la sesión de base de datos con mejoras
func (*TenantContextManager) TenantAwareExec ¶ added in v1.0.2
func (tcm *TenantContextManager) TenantAwareExec(ctx context.Context, tenantID, query string, args ...interface{}) (sql.Result, error)
TenantAwareExec ejecuta una declaración SQL con contexto de tenant mejorado
func (*TenantContextManager) TenantAwareQuery ¶ added in v1.0.2
func (tcm *TenantContextManager) TenantAwareQuery(ctx context.Context, tenantID, query string, args ...interface{}) (*sql.Rows, error)
TenantAwareQuery ejecuta una consulta con contexto de tenant mejorado
func (*TenantContextManager) ValidateTenantAccess ¶ added in v1.0.2
func (tcm *TenantContextManager) ValidateTenantAccess(ctx context.Context, tenantID, resourceTable, resourceID string) (bool, error)
ValidateTenantAccess verifica que el tenant tiene acceso a un recurso específico mejorado
func (*TenantContextManager) VerifyRLSStatus ¶ added in v1.0.2
func (tcm *TenantContextManager) VerifyRLSStatus(ctx context.Context) ([]RLSStatus, error)
VerifyRLSStatus verifica que Row Level Security está habilitado con mejoras
func (*TenantContextManager) WithTenantContext ¶ added in v1.0.2
func (tcm *TenantContextManager) WithTenantContext(ctx context.Context, tenantID string, fn func(context.Context) error) error
WithTenantContext ejecuta una función con contexto de tenant establecido mejorado
type TenantMetrics ¶ added in v1.0.2
type TenantMetrics struct {
	TenantSets         int64                `json:"tenant_sets"`
	TenantGets         int64                `json:"tenant_gets"`
	TenantClears       int64                `json:"tenant_clears"`
	ValidationFailures int64                `json:"validation_failures"`
	SecurityViolations int64                `json:"security_violations"`
	CacheHits          int64                `json:"cache_hits"`
	CacheMisses        int64                `json:"cache_misses"`
	ActiveTenants      map[string]time.Time `json:"active_tenants"`
	TenantOperations   map[string]int64     `json:"tenant_operations"`
	AverageSetTime     time.Duration        `json:"average_set_time"`
	AverageGetTime     time.Duration        `json:"average_get_time"`
	LastOperation      time.Time            `json:"last_operation"`
	OperationHistory   []TenantOperation    `json:"operation_history"`
	// contains filtered or unexported fields
}
    TenantMetrics métricas del sistema de tenancy
type TenantOperation ¶ added in v1.0.2
type TenantOperation struct {
	Type      string        `json:"type"`
	TenantID  string        `json:"tenant_id"`
	Success   bool          `json:"success"`
	Duration  time.Duration `json:"duration"`
	Error     string        `json:"error,omitempty"`
	Timestamp time.Time     `json:"timestamp"`
}
    TenantOperation representa una operación de tenant