dbconn

package
v0.0.0-...-caaa3fa Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2025 License: MIT Imports: 25 Imported by: 3

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	/*
		mysql,sqlserver, goracle
	*/
	DatabaseType = "mysql"

	/*
		user:password@tcp(localhost:3306)/mydb
		server=%s;port=%d;user id=%s;password=%s;database=%s
	*/
	//DatabaseConnection = "server=xxx;user id=xx;password=xxx;database=xxx"  //sqlserver
	DatabaseConnection = "user:iacf12345678@tcp(localhost:3306)/iac?charset=utf8mb4&parseTime=True&loc=Local"
	MaxIdleConns       = 5
	MaxOpenConns       = 10
)
View Source
var (
	ErrInvalidDatabaseType = errors.New("invalid database type")
	ErrMissingHost         = errors.New("database host is required")
	ErrMissingDatabase     = errors.New("database name is required")
	ErrMissingUsername     = errors.New("database username is required")
	ErrInvalidPort         = errors.New("invalid database port")
	ErrInvalidConfig       = errors.New("invalid database configuration")
)

Configuration Errors

View Source
var (
	ErrConnectionFailed  = errors.New("failed to connect to database")
	ErrConnectionClosed  = errors.New("database connection is closed")
	ErrConnectionTimeout = errors.New("database connection timeout")
	ErrPingFailed        = errors.New("database ping failed")
	ErrNotConnected      = errors.New("not connected to database")
)

Connection Errors

View Source
var (
	ErrQueryFailed         = errors.New("query execution failed")
	ErrInvalidQuery        = errors.New("invalid query")
	ErrNoRows              = errors.New("no rows returned")
	ErrDuplicateKey        = errors.New("duplicate key violation")
	ErrForeignKeyViolation = errors.New("foreign key constraint violation")
)

Query Errors

View Source
var (
	ErrTransactionFailed = errors.New("transaction failed")
	ErrCommitFailed      = errors.New("transaction commit failed")
	ErrRollbackFailed    = errors.New("transaction rollback failed")
	ErrNoTransaction     = errors.New("no active transaction")
)

Transaction Errors

View Source
var (
	ErrTableNotFound  = errors.New("table not found")
	ErrColumnNotFound = errors.New("column not found")
	ErrSchemaNotFound = errors.New("schema not found")
	ErrInvalidSchema  = errors.New("invalid schema")
)

Schema Errors

View Source
var (
	ErrFeatureNotSupported = errors.New("feature not supported by this database")
	ErrDialectNotFound     = errors.New("dialect not found for database type")
)

Feature Errors

View Source
var (
	ErrCacheDisabled          = fmt.Errorf("cache is disabled")
	ErrCacheMiss              = fmt.Errorf("cache miss")
	ErrCacheSizeLimitExceeded = fmt.Errorf("cache size limit exceeded")
)

Cache errors

View Source
var (
	ErrTransactionAlreadyCommitted  = fmt.Errorf("transaction already committed")
	ErrTransactionAlreadyRolledBack = fmt.Errorf("transaction already rolled back")
	ErrTransactionFinished          = fmt.Errorf("transaction already finished")
	ErrSavepointNotFound            = fmt.Errorf("savepoint not found")
)

Additional error types

View Source
var DB *sql.DB

DB is the interface for database connection

Functions

func BuildConnectionString

func BuildConnectionString(config *DBConfig) (string, error)

BuildConnectionString builds a database-specific connection string

func CloseAllDatabases

func CloseAllDatabases() error

CloseAllDatabases closes all database instances using the global factory

func CloseDBInstance

func CloseDBInstance(name string) error

CloseDBInstance closes a database instance using the global factory

func ConnectDB

func ConnectDB() error

func DBPing

func DBPing() error

func ExampleDatabaseSelection

func ExampleDatabaseSelection()

Example usage:

func IsDuplicateKeyError

func IsDuplicateKeyError(err error) bool

IsDuplicateKeyError checks if an error is a duplicate key error

func IsForeignKeyError

func IsForeignKeyError(err error) bool

IsForeignKeyError checks if an error is a foreign key violation

func IsRetryableError

func IsRetryableError(err error) bool

IsRetryableError checks if an error is retryable

func LogDatabaseAccess

func LogDatabaseAccess(log AuditLog)

LogDatabaseAccess logs database access for audit purposes This is a placeholder for actual audit logging implementation

func SanitizeErrorMessage

func SanitizeErrorMessage(err error, config DBConfig) string

SanitizeErrorMessage removes sensitive information from error messages

func ValidateConnectionConfig

func ValidateConnectionConfig(config DBConfig) error

ValidateConnectionConfig validates database connection configuration for security

func ValidateIdentifier

func ValidateIdentifier(identifier string) error

ValidateIdentifier validates database identifiers (schema, table, column names) to prevent SQL injection via identifier manipulation

func ValidateSSLConfig

func ValidateSSLConfig(config DBConfig) error

ValidateSSLConfig validates SSL configuration and enforces SSL in production

func ValidateSecurityConfig

func ValidateSecurityConfig(config *SecurityConfig) error

ValidateSecurityConfig validates the security configuration

func ValidateShardKey

func ValidateShardKey(key string) error

ValidateShardKey validates a shard key

func WithDatabase

func WithDatabase(ctx context.Context, db RelationalDB) context.Context

WithDatabase adds a database to context.Context

func WithDatabaseContext

func WithDatabaseContext(ctx context.Context, dbCtx *DatabaseContext) context.Context

WithDatabaseContext adds database context to context.Context

Types

type AuditLog

type AuditLog struct {
	Timestamp string `json:"timestamp"`
	User      string `json:"user"`
	Database  string `json:"database"`
	Operation string `json:"operation"`
	Success   bool   `json:"success"`
	Error     string `json:"error,omitempty"`
	IPAddress string `json:"ip_address,omitempty"`
	Duration  int64  `json:"duration_ms,omitempty"`
}

AuditLog represents a database access audit log entry

type BackupConfig

type BackupConfig struct {
	// BackupDir is the directory for backup files
	BackupDir string

	// Format specifies backup format
	Format BackupFormat

	// Compression enables compression
	Compression bool

	// MaxBackups is the maximum number of backups to retain
	MaxBackups int

	// RetentionDays is how long to keep backups
	RetentionDays int

	// VerifyBackup verifies backup after creation
	VerifyBackup bool

	// ScheduleExpression is cron expression for scheduled backups
	ScheduleExpression string
}

BackupConfig configures backup operations

func DefaultBackupConfig

func DefaultBackupConfig() *BackupConfig

DefaultBackupConfig returns default configuration

type BackupFormat

type BackupFormat string

BackupFormat defines the backup file format

const (
	// SQLFormat exports as SQL statements
	SQLFormat BackupFormat = "sql"

	// BinaryFormat exports as binary dump
	BinaryFormat BackupFormat = "binary"

	// CompressedFormat exports as compressed archive
	CompressedFormat BackupFormat = "compressed"
)

type BackupInfo

type BackupInfo struct {
	ID           string
	DatabaseName string
	DatabaseType string
	BackupType   BackupType
	Format       BackupFormat
	FilePath     string
	FileSize     int64
	CreatedAt    time.Time
	Compressed   bool
	Verified     bool
	Metadata     map[string]string
}

BackupInfo contains information about a backup

type BackupManager

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

BackupManager manages database backups and restores

func NewBackupManager

func NewBackupManager(config *BackupConfig) (*BackupManager, error)

NewBackupManager creates a new backup manager

func (*BackupManager) Backup

func (bm *BackupManager) Backup(ctx context.Context, db *sql.DB, dbType, dbName string) (*BackupInfo, error)

Backup creates a database backup

func (*BackupManager) DeleteBackup

func (bm *BackupManager) DeleteBackup(backupID string) error

DeleteBackup deletes a backup

func (*BackupManager) GetBackup

func (bm *BackupManager) GetBackup(backupID string) (*BackupInfo, error)

GetBackup returns specific backup by ID

func (*BackupManager) ListBackups

func (bm *BackupManager) ListBackups() []*BackupInfo

ListBackups returns all available backups

func (*BackupManager) Restore

func (bm *BackupManager) Restore(ctx context.Context, db *sql.DB, backupID string, options *RestoreOptions) error

Restore restores a database from backup

func (*BackupManager) StartScheduler

func (bm *BackupManager) StartScheduler(ctx context.Context, db *sql.DB, dbType, dbName string)

StartScheduler starts the backup scheduler

func (*BackupManager) StopScheduler

func (bm *BackupManager) StopScheduler()

StopScheduler stops the backup scheduler

type BackupScheduler

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

BackupScheduler manages scheduled backups

type BackupType

type BackupType string

BackupType defines the type of backup

const (
	// FullBackup is a complete database backup
	FullBackup BackupType = "full"

	// IncrementalBackup is an incremental backup
	IncrementalBackup BackupType = "incremental"

	// DifferentialBackup is a differential backup
	DifferentialBackup BackupType = "differential"
)

type CacheBackend

type CacheBackend interface {
	Get(ctx context.Context, key string) ([]byte, error)
	Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
	Delete(ctx context.Context, key string) error
	DeletePattern(ctx context.Context, pattern string) error
	Exists(ctx context.Context, key string) (bool, error)
	Clear(ctx context.Context) error
}

CacheBackend defines the interface for cache storage backends

type CacheMetrics

type CacheMetrics struct {
	Hits          int64
	Misses        int64
	Sets          int64
	Errors        int64
	Invalidations int64
	HitRate       float64
}

CacheMetrics contains cache statistics

type ColumnInfo

type ColumnInfo struct {
	Name         string
	DataType     string
	IsNullable   bool
	DefaultValue *string
	MaxLength    *int
	Precision    *int
	Scale        *int
	IsPrimaryKey bool
	IsForeignKey bool
	IsUnique     bool
	Comment      string
}

ColumnInfo represents column metadata

type ConnectionPool

type ConnectionPool struct {
	Name     string
	Type     PoolType
	DB       RelationalDB
	Config   *DBConfig
	Priority int
	Weight   int
	Active   bool
	// contains filtered or unexported fields
}

ConnectionPool represents a named database connection

type ConnectionPoolProxy

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

ConnectionPoolProxy wraps a connection pool with additional features

func NewConnectionPoolProxy

func NewConnectionPoolProxy(db *sql.DB, maxConns int) *ConnectionPoolProxy

NewConnectionPoolProxy creates a new connection pool proxy

func (*ConnectionPoolProxy) GetConnection

func (cpp *ConnectionPoolProxy) GetConnection(ctx context.Context) (*sql.Conn, error)

GetConnection gets a connection from the pool

func (*ConnectionPoolProxy) GetStats

func (cpp *ConnectionPoolProxy) GetStats() ConnectionPoolStats

GetStats returns connection pool statistics

func (*ConnectionPoolProxy) ReleaseConnection

func (cpp *ConnectionPoolProxy) ReleaseConnection(conn *sql.Conn) error

ReleaseConnection releases a connection back to the pool

type ConnectionPoolStats

type ConnectionPoolStats struct {
	ActiveConnections int64
	TotalConnections  int64
	AverageWaitTime   time.Duration
	MaxConnections    int
}

ConnectionPoolStats contains connection pool statistics

type ConnectionStats

type ConnectionStats struct {
	MaxOpenConnections int
	OpenConnections    int
	InUse              int
	Idle               int
	WaitCount          int64
	WaitDuration       time.Duration
	MaxIdleClosed      int64
	MaxLifetimeClosed  int64
}

ConnectionStats represents connection pool statistics

func GetStats

func GetStats(stats sql.DBStats) ConnectionStats

GetStats converts sql.DBStats to ConnectionStats

type ContextKey

type ContextKey string

ContextKey is the type for context keys

const (
	// DatabaseContextKey is the context key for database selection
	DatabaseContextKey ContextKey = "db_context"
	// SelectedDatabaseKey is the context key for the selected database
	SelectedDatabaseKey ContextKey = "selected_db"
)

type DBConfig

type DBConfig struct {
	// Connection Details
	Type     DBType `json:"type"`
	Host     string `json:"host"`
	Port     int    `json:"port"`
	Database string `json:"database"`
	Schema   string `json:"schema,omitempty"`
	Username string `json:"username"`
	Password string `json:"password"`

	// Connection Options
	SSLMode     string `json:"ssl_mode,omitempty"`
	SSLCert     string `json:"ssl_cert,omitempty"`
	SSLKey      string `json:"ssl_key,omitempty"`
	SSLRootCert string `json:"ssl_root_cert,omitempty"`

	// Pool Configuration
	MaxIdleConns    int           `json:"max_idle_conns"`
	MaxOpenConns    int           `json:"max_open_conns"`
	ConnMaxLifetime time.Duration `json:"conn_max_lifetime,omitempty"`
	ConnMaxIdleTime time.Duration `json:"conn_max_idle_time,omitempty"`
	ConnTimeout     int           `json:"conn_timeout"`

	// Database-Specific Options
	Options map[string]string `json:"options,omitempty"`
}

DBConfig represents database connection configuration

func ParseConnectionString

func ParseConnectionString(connStr string, dbType DBType) (*DBConfig, error)

ParseConnectionString parses a connection string into DBConfig This is useful for backward compatibility

func (*DBConfig) BuildConnectionString

func (c *DBConfig) BuildConnectionString() string

BuildConnectionString builds database-specific connection string

func (*DBConfig) Validate

func (c *DBConfig) Validate() error

Validate validates the database configuration

type DBOperation

type DBOperation struct {
	DBTx       *sql.Tx
	ModuleName string

	User string
	// contains filtered or unexported fields
}

func NewDBOperation

func NewDBOperation(User string, DBTx *sql.Tx, moduleName string) *DBOperation

func (*DBOperation) Conto_Json

func (db *DBOperation) Conto_Json(rows *sql.Rows) ([]map[string]interface{}, error)

func (*DBOperation) Conto_JsonbyList

func (db *DBOperation) Conto_JsonbyList(rows *sql.Rows) (map[string][]interface{}, int, int, error)

func (*DBOperation) ExeSPwithRow

func (db *DBOperation) ExeSPwithRow(procedureName string, args ...interface{}) (*sql.Rows, error)

func (*DBOperation) ExecSP

func (db *DBOperation) ExecSP(procedureName string, args ...interface{}) error

func (*DBOperation) ExecSP_Json

func (db *DBOperation) ExecSP_Json(procedureName string, args ...interface{}) ([]map[string]interface{}, error)

func (*DBOperation) GetDialect

func (db *DBOperation) GetDialect() Dialect

GetDialect returns the dialect for the current database type This provides automatic database type support by using the factory pattern

func (*DBOperation) GetPlaceholder

func (db *DBOperation) GetPlaceholder(n int) string

GetPlaceholder returns the database-specific placeholder for parameter n

func (*DBOperation) Query

func (db *DBOperation) Query(querystr string, args ...interface{}) (*sql.Rows, error)

func (*DBOperation) Query_Json

func (db *DBOperation) Query_Json(querystr string, args ...interface{}) ([]map[string]interface{}, error)

func (*DBOperation) QuerybyList

func (db *DBOperation) QuerybyList(querystr string, namelist []string, inputs map[string]interface{}, finputs []types.Input) (map[string][]interface{}, int, int, error)

func (*DBOperation) QuoteIdentifier

func (db *DBOperation) QuoteIdentifier(name string) string

QuoteIdentifier returns the database-specific quoted identifier

func (*DBOperation) TableDelete

func (db *DBOperation) TableDelete(TableName string, Where string) (int64, error)

TableDelete deletes records from a table based on the provided WHERE clause. It returns the number of affected rows and an error, if any. The function measures the performance duration of the operation using the PerformanceWithDuration method of the db.iLog object.

func (*DBOperation) TableInsert

func (db *DBOperation) TableInsert(TableName string, Columns []string, Values []string) (int64, error)

TableInsert inserts data into a specified table in the database. It takes the table name, column names, and corresponding values as input. It returns the last insert ID and any error encountered during the operation. The function measures the performance duration of the operation using the PerformanceWithDuration method of the db.iLog object.

func (*DBOperation) TableUpdate

func (db *DBOperation) TableUpdate(TableName string, Columns []string, Values []string, datatypes []int, Where string) (int64, error)

TableUpdate updates the specified table with the given columns, values, data types, and WHERE clause. It returns the number of rows affected and any error encountered during the update operation. The function measures the performance duration of the operation using the PerformanceWithDuration method of the db.iLog object. If there is a panic during the execution, it logs an error message with the error details.

func (*DBOperation) TableUpdate_v2

func (db *DBOperation) TableUpdate_v2(TableName string, Columns []string, Values []interface{}, datatypes []int, Where string) (int64, error)

type DBType

type DBType string

DBType represents supported database types

const (
	DBTypeMySQL      DBType = "mysql"
	DBTypePostgreSQL DBType = "postgres"
	DBTypeMSSQL      DBType = "mssql"
	DBTypeOracle     DBType = "oracle"
)

type DatabaseContext

type DatabaseContext struct {
	Operation OperationType
	TenantID  string
	UserID    string
	Priority  int
	Metadata  map[string]interface{}
}

DatabaseContext represents context for database selection

func GetDatabaseContext

func GetDatabaseContext(ctx context.Context) (*DatabaseContext, bool)

GetDatabaseContext retrieves database context from context.Context

type DatabaseError

type DatabaseError struct {
	Operation string
	Err       error
	DBType    DBType
	Query     string
}

DatabaseError wraps a database error with additional context

func NewDatabaseError

func NewDatabaseError(operation string, err error, dbType DBType, query string) *DatabaseError

NewDatabaseError creates a new DatabaseError

func (*DatabaseError) Error

func (e *DatabaseError) Error() string

func (*DatabaseError) Unwrap

func (e *DatabaseError) Unwrap() error

type DatabaseFactory

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

DatabaseFactory manages database instance creation

func GetFactory

func GetFactory() *DatabaseFactory

GetFactory returns the global database factory instance

func (*DatabaseFactory) CloseAll

func (f *DatabaseFactory) CloseAll() error

CloseAll closes all database instances

func (*DatabaseFactory) CloseDB

func (f *DatabaseFactory) CloseDB(name string) error

CloseDB closes and removes a database instance

func (*DatabaseFactory) GetDB

func (f *DatabaseFactory) GetDB(name string) (RelationalDB, error)

GetDB retrieves an existing database instance

func (*DatabaseFactory) GetDialect

func (f *DatabaseFactory) GetDialect(dbType DBType) (Dialect, error)

GetDialect returns the dialect for a database type

func (*DatabaseFactory) GetOrCreateDB

func (f *DatabaseFactory) GetOrCreateDB(name string, config *DBConfig) (RelationalDB, error)

GetOrCreateDB gets an existing database instance or creates a new one

func (*DatabaseFactory) ListInstances

func (f *DatabaseFactory) ListInstances() []string

ListInstances returns the names of all active database instances

func (*DatabaseFactory) NewRelationalDB

func (f *DatabaseFactory) NewRelationalDB(config *DBConfig) (RelationalDB, error)

NewRelationalDB creates a new relational database instance

func (*DatabaseFactory) RegisterDialect

func (f *DatabaseFactory) RegisterDialect(dbType DBType, dialect Dialect)

RegisterDialect registers a database dialect

func (*DatabaseFactory) RegisterDriver

func (f *DatabaseFactory) RegisterDriver(dbType DBType, constructor DriverConstructor)

RegisterDriver registers a database driver constructor

type DatabaseProxy

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

DatabaseProxy provides a proxy layer for database operations

func NewDatabaseProxy

func NewDatabaseProxy(config *ProxyConfig) *DatabaseProxy

NewDatabaseProxy creates a new database proxy

func (*DatabaseProxy) Exec

func (dp *DatabaseProxy) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

Exec executes a non-query statement through the proxy

func (*DatabaseProxy) GetMetrics

func (dp *DatabaseProxy) GetMetrics() ProxyMetrics

GetMetrics returns proxy metrics

func (*DatabaseProxy) Query

func (dp *DatabaseProxy) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

Query executes a query through the proxy

func (*DatabaseProxy) SetPoolManager

func (dp *DatabaseProxy) SetPoolManager(pm *PoolManager)

SetPoolManager sets the connection pool manager

func (*DatabaseProxy) SetQueryCache

func (dp *DatabaseProxy) SetQueryCache(qc *QueryCache)

SetQueryCache sets the query cache

func (*DatabaseProxy) SetReplicaManager

func (dp *DatabaseProxy) SetReplicaManager(rm *ReplicaManager)

SetReplicaManager sets the replica manager

type DatabaseRouter

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

DatabaseRouter routes requests to appropriate databases

func GetGlobalRouter

func GetGlobalRouter() *DatabaseRouter

GetGlobalRouter returns the global database router

func NewDatabaseRouter

func NewDatabaseRouter(selector *DatabaseSelector) *DatabaseRouter

NewDatabaseRouter creates a new database router

func (*DatabaseRouter) AddRoutingRule

func (dr *DatabaseRouter) AddRoutingRule(rule RoutingRule)

AddRoutingRule adds a routing rule

func (*DatabaseRouter) Middleware

func (dr *DatabaseRouter) Middleware(next func(context.Context) error) func(context.Context) error

Middleware creates a middleware for automatic database selection

func (*DatabaseRouter) RegisterTenant

func (dr *DatabaseRouter) RegisterTenant(tenantID, poolName string)

RegisterTenant registers a tenant with a specific database pool

func (*DatabaseRouter) Route

func (dr *DatabaseRouter) Route(ctx context.Context) (RelationalDB, error)

Route routes a request to appropriate database

type DatabaseSelector

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

DatabaseSelector selects appropriate database based on context

func GetGlobalSelector

func GetGlobalSelector() *DatabaseSelector

GetGlobalSelector returns the global database selector

func NewDatabaseSelector

func NewDatabaseSelector(poolManager *PoolManager) *DatabaseSelector

NewDatabaseSelector creates a new database selector

func (*DatabaseSelector) AddRule

func (ds *DatabaseSelector) AddRule(rule SelectionRule)

AddRule adds a selection rule

func (*DatabaseSelector) SelectDatabase

func (ds *DatabaseSelector) SelectDatabase(ctx *DatabaseContext) (RelationalDB, error)

SelectDatabase selects a database based on context

func (*DatabaseSelector) SelectForRead

func (ds *DatabaseSelector) SelectForRead() (RelationalDB, error)

SelectForRead selects a database for read operations

func (*DatabaseSelector) SelectForWrite

func (ds *DatabaseSelector) SelectForWrite() (RelationalDB, error)

SelectForWrite selects a database for write operations

func (*DatabaseSelector) SetStrategy

func (ds *DatabaseSelector) SetStrategy(strategy SelectionStrategy)

SetStrategy sets the selection strategy

type Dialect

type Dialect interface {
	// Query Building
	QuoteIdentifier(name string) string
	Placeholder(n int) string
	LimitOffset(limit, offset int) string

	// Type Conversion
	DataTypeMapping(genericType string) string
	ConvertValue(value interface{}, targetType string) (interface{}, error)

	// Feature Detection
	SupportsReturning() bool
	SupportsUpsert() bool
	SupportsCTE() bool
	SupportsJSON() bool
	SupportsFullTextSearch() bool

	// Query Translation
	TranslatePagination(query string, limit, offset int) string
	TranslateUpsert(table string, columns []string, conflictColumns []string) string
	ConvertJSONQuery(query string) string // Convert MySQL JSON_TABLE to database-specific syntax

	// DDL Generation - Schema Management
	// These methods enable database-agnostic table schema definitions
	CreateTableDDL(schema *TableSchema) string
	AddColumnDDL(tableName string, column *ColumnInfo) string
	DropColumnDDL(tableName, columnName string) string
	AlterColumnDDL(tableName string, column *ColumnInfo) string
	CreateIndexDDL(tableName string, index *IndexInfo) string
	DropIndexDDL(tableName, indexName string) string
}

Dialect defines the interface for database-specific SQL dialect operations

type DriverConstructor

type DriverConstructor func(*DBConfig) (RelationalDB, error)

DriverConstructor is a function that creates a database driver instance

type Feature

type Feature string

Feature represents database feature flags

const (
	FeatureCTE              Feature = "cte"
	FeatureWindowFunctions  Feature = "window_functions"
	FeatureJSON             Feature = "json"
	FeatureFullTextSearch   Feature = "fulltext_search"
	FeatureReturning        Feature = "returning"
	FeatureUpsert           Feature = "upsert"
	FeatureArrays           Feature = "arrays"
	FeaturePartitioning     Feature = "partitioning"
	FeatureStoredProcedures Feature = "stored_procedures"
)

type GenericSQLDB

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

GenericSQLDB is a generic SQL database adapter implementing RelationalDB

func NewGenericSQLDB

func NewGenericSQLDB(config *DBConfig) *GenericSQLDB

NewGenericSQLDB creates a new generic SQL database adapter

func (*GenericSQLDB) BeginTx

func (g *GenericSQLDB) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)

func (*GenericSQLDB) Close

func (g *GenericSQLDB) Close() error

func (*GenericSQLDB) Connect

func (g *GenericSQLDB) Connect(config *DBConfig) error

Connect establishes connection to the database

func (*GenericSQLDB) DB

func (g *GenericSQLDB) DB() *sql.DB

func (*GenericSQLDB) Exec

func (g *GenericSQLDB) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

func (*GenericSQLDB) GetDialect

func (g *GenericSQLDB) GetDialect() Dialect

func (*GenericSQLDB) GetTableSchema

func (g *GenericSQLDB) GetTableSchema(ctx context.Context, schema, tableName string) (*TableSchema, error)

func (*GenericSQLDB) GetType

func (g *GenericSQLDB) GetType() DBType

func (*GenericSQLDB) IsConnected

func (g *GenericSQLDB) IsConnected() bool

func (*GenericSQLDB) ListTables

func (g *GenericSQLDB) ListTables(ctx context.Context, schema string) ([]string, error)

func (*GenericSQLDB) Ping

func (g *GenericSQLDB) Ping() error

func (*GenericSQLDB) Query

func (g *GenericSQLDB) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

func (*GenericSQLDB) QueryRow

func (g *GenericSQLDB) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row

func (*GenericSQLDB) Stats

func (g *GenericSQLDB) Stats() sql.DBStats

func (*GenericSQLDB) SupportsFeature

func (g *GenericSQLDB) SupportsFeature(feature Feature) bool

func (*GenericSQLDB) TableExists

func (g *GenericSQLDB) TableExists(ctx context.Context, schema, tableName string) (bool, error)

type HashFunction

type HashFunction string

HashFunction defines hash functions for shard key

const (
	// CRC32Hash uses CRC32 hash
	CRC32Hash HashFunction = "crc32"

	// FNV1Hash uses FNV-1 hash
	FNV1Hash HashFunction = "fnv1"

	// FNV1aHash uses FNV-1a hash
	FNV1aHash HashFunction = "fnv1a"
)

type IndexInfo

type IndexInfo struct {
	Name     string
	Columns  []string
	IsUnique bool
	Type     string
}

IndexInfo represents index metadata

type InvalidationRule

type InvalidationRule struct {
	// Pattern matches cache keys to invalidate
	Pattern string

	// OnWrite invalidates on write operations to specified tables
	OnWrite []string

	// TTL custom TTL for this rule
	TTL time.Duration
}

InvalidationRule defines when to invalidate cache

type LoadBalancer

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

LoadBalancer balances queries across multiple databases

func NewLoadBalancer

func NewLoadBalancer(strategy LoadBalancingStrategy) *LoadBalancer

NewLoadBalancer creates a new load balancer

func (*LoadBalancer) AddDatabase

func (lb *LoadBalancer) AddDatabase(db RelationalDB)

AddDatabase adds a database to the load balancer

func (*LoadBalancer) SelectDatabase

func (lb *LoadBalancer) SelectDatabase() (RelationalDB, error)

SelectDatabase selects a database based on strategy

type LoadBalancingStrategy

type LoadBalancingStrategy string

LoadBalancingStrategy defines the strategy for selecting replicas

const (
	// RoundRobin selects replicas in round-robin fashion
	RoundRobin LoadBalancingStrategy = "round_robin"

	// WeightedRoundRobin selects replicas based on their weight
	WeightedRoundRobin LoadBalancingStrategy = "weighted_round_robin"

	// LeastConnections selects replica with least active connections
	LeastConnections LoadBalancingStrategy = "least_connections"

	// Random selects a random healthy replica
	Random LoadBalancingStrategy = "random"

	// LeastLag selects replica with minimum replication lag
	LeastLag LoadBalancingStrategy = "least_lag"
)

type MSSQLDialect

type MSSQLDialect struct{}

MSSQLDialect implements MSSQL/SQL Server-specific SQL operations

func NewMSSQLDialect

func NewMSSQLDialect() *MSSQLDialect

func (*MSSQLDialect) AddColumnDDL

func (d *MSSQLDialect) AddColumnDDL(tableName string, column *ColumnInfo) string

func (*MSSQLDialect) AlterColumnDDL

func (d *MSSQLDialect) AlterColumnDDL(tableName string, column *ColumnInfo) string

func (*MSSQLDialect) ConvertJSONQuery

func (d *MSSQLDialect) ConvertJSONQuery(query string) string

func (*MSSQLDialect) ConvertValue

func (d *MSSQLDialect) ConvertValue(value interface{}, targetType string) (interface{}, error)

func (*MSSQLDialect) CreateIndexDDL

func (d *MSSQLDialect) CreateIndexDDL(tableName string, index *IndexInfo) string

func (*MSSQLDialect) CreateTableDDL

func (d *MSSQLDialect) CreateTableDDL(schema *TableSchema) string

func (*MSSQLDialect) DataTypeMapping

func (d *MSSQLDialect) DataTypeMapping(genericType string) string

func (*MSSQLDialect) DropColumnDDL

func (d *MSSQLDialect) DropColumnDDL(tableName, columnName string) string

func (*MSSQLDialect) DropIndexDDL

func (d *MSSQLDialect) DropIndexDDL(tableName, indexName string) string

func (*MSSQLDialect) LimitOffset

func (d *MSSQLDialect) LimitOffset(limit, offset int) string

func (*MSSQLDialect) Placeholder

func (d *MSSQLDialect) Placeholder(n int) string

func (*MSSQLDialect) QuoteIdentifier

func (d *MSSQLDialect) QuoteIdentifier(name string) string

func (*MSSQLDialect) SupportsCTE

func (d *MSSQLDialect) SupportsCTE() bool

func (*MSSQLDialect) SupportsFullTextSearch

func (d *MSSQLDialect) SupportsFullTextSearch() bool

func (*MSSQLDialect) SupportsJSON

func (d *MSSQLDialect) SupportsJSON() bool

func (*MSSQLDialect) SupportsReturning

func (d *MSSQLDialect) SupportsReturning() bool

func (*MSSQLDialect) SupportsUpsert

func (d *MSSQLDialect) SupportsUpsert() bool

func (*MSSQLDialect) TranslatePagination

func (d *MSSQLDialect) TranslatePagination(query string, limit, offset int) string

func (*MSSQLDialect) TranslateUpsert

func (d *MSSQLDialect) TranslateUpsert(table string, columns []string, conflictColumns []string) string

type ManagedTransaction

type ManagedTransaction struct {
	ID           string
	Tx           *sql.Tx
	StartTime    time.Time
	Isolation    sql.IsolationLevel
	Savepoints   []string
	IsCommitted  bool
	IsRolledBack bool
	// contains filtered or unexported fields
}

ManagedTransaction represents a managed database transaction

func (*ManagedTransaction) Commit

func (mtx *ManagedTransaction) Commit() error

Commit commits the transaction

func (*ManagedTransaction) GetDuration

func (mtx *ManagedTransaction) GetDuration() time.Duration

GetDuration returns the duration of the transaction

func (*ManagedTransaction) IsActive

func (mtx *ManagedTransaction) IsActive() bool

IsActive returns whether the transaction is still active

func (*ManagedTransaction) ReleaseSavepoint

func (mtx *ManagedTransaction) ReleaseSavepoint(name string) error

ReleaseSavepoint releases a savepoint

func (*ManagedTransaction) Rollback

func (mtx *ManagedTransaction) Rollback() error

Rollback rolls back the transaction

func (*ManagedTransaction) RollbackToSavepoint

func (mtx *ManagedTransaction) RollbackToSavepoint(name string) error

RollbackToSavepoint rolls back to a specific savepoint

func (*ManagedTransaction) Savepoint

func (mtx *ManagedTransaction) Savepoint(name string) error

Savepoint creates a savepoint within the transaction

type MemoryCache

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

MemoryCache is a simple in-memory cache backend

func NewMemoryCache

func NewMemoryCache(maxSize int64) *MemoryCache

NewMemoryCache creates a new in-memory cache

func (*MemoryCache) Clear

func (mc *MemoryCache) Clear(ctx context.Context) error

Clear removes all entries

func (*MemoryCache) Delete

func (mc *MemoryCache) Delete(ctx context.Context, key string) error

Delete removes a value from memory cache

func (*MemoryCache) DeletePattern

func (mc *MemoryCache) DeletePattern(ctx context.Context, pattern string) error

DeletePattern removes all entries matching pattern

func (*MemoryCache) Exists

func (mc *MemoryCache) Exists(ctx context.Context, key string) (bool, error)

Exists checks if a key exists

func (*MemoryCache) Get

func (mc *MemoryCache) Get(ctx context.Context, key string) ([]byte, error)

Get retrieves a value from memory cache

func (*MemoryCache) Set

func (mc *MemoryCache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error

Set stores a value in memory cache

type MetricsCollector

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

MetricsCollector collects and aggregates database metrics

func GetMetricsCollector

func GetMetricsCollector() *MetricsCollector

GetMetricsCollector returns the global metrics collector

func NewMetricsCollector

func NewMetricsCollector() *MetricsCollector

NewMetricsCollector creates a new metrics collector

func (*MetricsCollector) EnableLogging

func (mc *MetricsCollector) EnableLogging(enable bool)

EnableLogging enables or disables query logging

func (*MetricsCollector) EnableMetrics

func (mc *MetricsCollector) EnableMetrics(enable bool)

EnableMetrics enables or disables metrics collection

func (*MetricsCollector) GetAllMetrics

func (mc *MetricsCollector) GetAllMetrics() map[DBType]*QueryMetrics

GetAllMetrics returns metrics for all database types

func (*MetricsCollector) GetMetrics

func (mc *MetricsCollector) GetMetrics(dbType DBType) *QueryMetrics

GetMetrics returns metrics for a specific database type

func (*MetricsCollector) GetRecentLogs

func (mc *MetricsCollector) GetRecentLogs(limit int) []QueryLog

GetRecentLogs returns the most recent query logs

func (*MetricsCollector) GetSlowQueries

func (mc *MetricsCollector) GetSlowQueries(limit int) []QueryLog

GetSlowQueries returns recent slow queries

func (*MetricsCollector) RecordExec

func (mc *MetricsCollector) RecordExec(dbType DBType, query string, args []interface{}, duration time.Duration, err error, rowsAffected int64)

RecordExec records an exec operation

func (*MetricsCollector) RecordQuery

func (mc *MetricsCollector) RecordQuery(dbType DBType, query string, args []interface{}, duration time.Duration, err error, rowsAffected int64)

RecordQuery records a query execution

func (*MetricsCollector) ResetMetrics

func (mc *MetricsCollector) ResetMetrics()

ResetMetrics resets all metrics

func (*MetricsCollector) SetMaxLogSize

func (mc *MetricsCollector) SetMaxLogSize(size int)

SetMaxLogSize sets the maximum number of query logs to keep

func (*MetricsCollector) SetSlowQueryThreshold

func (mc *MetricsCollector) SetSlowQueryThreshold(threshold time.Duration)

SetSlowQueryThreshold sets the threshold for slow query detection

type Migration

type Migration struct {
	Version     int
	Description string
	UpSQL       string
	DownSQL     string
	Checksum    string
}

Migration represents a schema migration

type MigrationRecord

type MigrationRecord struct {
	Version     int
	Description string
	Applied     bool
	AppliedAt   time.Time
}

MigrationRecord represents a migration history record

type MySQLDialect

type MySQLDialect struct{}

MySQLDialect implements MySQL-specific SQL operations

func NewMySQLDialect

func NewMySQLDialect() *MySQLDialect

func (*MySQLDialect) AddColumnDDL

func (d *MySQLDialect) AddColumnDDL(tableName string, column *ColumnInfo) string

func (*MySQLDialect) AlterColumnDDL

func (d *MySQLDialect) AlterColumnDDL(tableName string, column *ColumnInfo) string

func (*MySQLDialect) ConvertJSONQuery

func (d *MySQLDialect) ConvertJSONQuery(query string) string

func (*MySQLDialect) ConvertValue

func (d *MySQLDialect) ConvertValue(value interface{}, targetType string) (interface{}, error)

func (*MySQLDialect) CreateIndexDDL

func (d *MySQLDialect) CreateIndexDDL(tableName string, index *IndexInfo) string

func (*MySQLDialect) CreateTableDDL

func (d *MySQLDialect) CreateTableDDL(schema *TableSchema) string

func (*MySQLDialect) DataTypeMapping

func (d *MySQLDialect) DataTypeMapping(genericType string) string

func (*MySQLDialect) DropColumnDDL

func (d *MySQLDialect) DropColumnDDL(tableName, columnName string) string

func (*MySQLDialect) DropIndexDDL

func (d *MySQLDialect) DropIndexDDL(tableName, indexName string) string

func (*MySQLDialect) LimitOffset

func (d *MySQLDialect) LimitOffset(limit, offset int) string

func (*MySQLDialect) Placeholder

func (d *MySQLDialect) Placeholder(n int) string

func (*MySQLDialect) QuoteIdentifier

func (d *MySQLDialect) QuoteIdentifier(name string) string

func (*MySQLDialect) SupportsCTE

func (d *MySQLDialect) SupportsCTE() bool

func (*MySQLDialect) SupportsFullTextSearch

func (d *MySQLDialect) SupportsFullTextSearch() bool

func (*MySQLDialect) SupportsJSON

func (d *MySQLDialect) SupportsJSON() bool

func (*MySQLDialect) SupportsReturning

func (d *MySQLDialect) SupportsReturning() bool

func (*MySQLDialect) SupportsUpsert

func (d *MySQLDialect) SupportsUpsert() bool

func (*MySQLDialect) TranslatePagination

func (d *MySQLDialect) TranslatePagination(query string, limit, offset int) string

func (*MySQLDialect) TranslateUpsert

func (d *MySQLDialect) TranslateUpsert(table string, columns []string, conflictColumns []string) string

type OperationType

type OperationType string

OperationType represents the type of database operation

const (
	OperationRead  OperationType = "read"
	OperationWrite OperationType = "write"
	OperationBulk  OperationType = "bulk"
	OperationAny   OperationType = "any"
)

type OracleDialect

type OracleDialect struct{}

OracleDialect implements Oracle-specific SQL operations

func NewOracleDialect

func NewOracleDialect() *OracleDialect

func (*OracleDialect) AddColumnDDL

func (d *OracleDialect) AddColumnDDL(tableName string, column *ColumnInfo) string

func (*OracleDialect) AlterColumnDDL

func (d *OracleDialect) AlterColumnDDL(tableName string, column *ColumnInfo) string

func (*OracleDialect) ConvertJSONQuery

func (d *OracleDialect) ConvertJSONQuery(query string) string

func (*OracleDialect) ConvertValue

func (d *OracleDialect) ConvertValue(value interface{}, targetType string) (interface{}, error)

func (*OracleDialect) CreateIndexDDL

func (d *OracleDialect) CreateIndexDDL(tableName string, index *IndexInfo) string

func (*OracleDialect) CreateTableDDL

func (d *OracleDialect) CreateTableDDL(schema *TableSchema) string

func (*OracleDialect) DataTypeMapping

func (d *OracleDialect) DataTypeMapping(genericType string) string

func (*OracleDialect) DropColumnDDL

func (d *OracleDialect) DropColumnDDL(tableName, columnName string) string

func (*OracleDialect) DropIndexDDL

func (d *OracleDialect) DropIndexDDL(tableName, indexName string) string

func (*OracleDialect) LimitOffset

func (d *OracleDialect) LimitOffset(limit, offset int) string

func (*OracleDialect) Placeholder

func (d *OracleDialect) Placeholder(n int) string

func (*OracleDialect) QuoteIdentifier

func (d *OracleDialect) QuoteIdentifier(name string) string

func (*OracleDialect) SupportsCTE

func (d *OracleDialect) SupportsCTE() bool

func (*OracleDialect) SupportsFullTextSearch

func (d *OracleDialect) SupportsFullTextSearch() bool

func (*OracleDialect) SupportsJSON

func (d *OracleDialect) SupportsJSON() bool

func (*OracleDialect) SupportsReturning

func (d *OracleDialect) SupportsReturning() bool

func (*OracleDialect) SupportsUpsert

func (d *OracleDialect) SupportsUpsert() bool

func (*OracleDialect) TranslatePagination

func (d *OracleDialect) TranslatePagination(query string, limit, offset int) string

func (*OracleDialect) TranslateUpsert

func (d *OracleDialect) TranslateUpsert(table string, columns []string, conflictColumns []string) string

type PoolInfo

type PoolInfo struct {
	Name     string
	Type     PoolType
	DBType   DBType
	Host     string
	Database string
	Active   bool
	Priority int
	Weight   int
}

PoolInfo contains information about a connection pool

type PoolManager

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

PoolManager manages multiple database connection pools

func GetPoolManager

func GetPoolManager() *PoolManager

GetPoolManager returns the global pool manager instance

func NewPoolManager

func NewPoolManager() *PoolManager

NewPoolManager creates a new pool manager

func (*PoolManager) AddBackup

func (pm *PoolManager) AddBackup(name string, config *DBConfig) error

AddBackup adds a backup database connection

func (*PoolManager) AddReplica

func (pm *PoolManager) AddReplica(name string, config *DBConfig, weight int) error

AddReplica adds a replica database connection

func (*PoolManager) CloseAll

func (pm *PoolManager) CloseAll() error

CloseAll closes all database connections

func (*PoolManager) GetByName

func (pm *PoolManager) GetByName(name string) (RelationalDB, error)

GetByName returns a connection pool by name

func (*PoolManager) GetForRead

func (pm *PoolManager) GetForRead() (RelationalDB, error)

GetForRead returns a database connection for read operations (prefers replicas)

func (*PoolManager) GetForWrite

func (pm *PoolManager) GetForWrite() (RelationalDB, error)

GetForWrite returns a database connection for write operations (always primary)

func (*PoolManager) GetPoolInfo

func (pm *PoolManager) GetPoolInfo() []PoolInfo

GetPoolInfo returns information about all pools

func (*PoolManager) GetPrimary

func (pm *PoolManager) GetPrimary() (RelationalDB, error)

GetPrimary returns the primary database connection

func (*PoolManager) GetReplica

func (pm *PoolManager) GetReplica() (RelationalDB, error)

GetReplica returns a replica database connection using round-robin load balancing

func (*PoolManager) GetStats

func (pm *PoolManager) GetStats() map[string]ConnectionStats

GetStats returns statistics for all connection pools

func (*PoolManager) SetPrimary

func (pm *PoolManager) SetPrimary(config *DBConfig) error

SetPrimary sets the primary database connection

func (*PoolManager) StartHealthCheck

func (pm *PoolManager) StartHealthCheck(ctx context.Context)

StartHealthCheck starts periodic health checks for all connections

func (*PoolManager) StopHealthCheck

func (pm *PoolManager) StopHealthCheck()

StopHealthCheck stops the health check goroutine

type PoolType

type PoolType string

PoolType represents the type of connection pool

const (
	PoolTypePrimary PoolType = "primary"
	PoolTypeReplica PoolType = "replica"
	PoolTypeBackup  PoolType = "backup"
)

type PostgreSQLDialect

type PostgreSQLDialect struct{}

PostgreSQLDialect implements PostgreSQL-specific SQL operations

func NewPostgreSQLDialect

func NewPostgreSQLDialect() *PostgreSQLDialect

func (*PostgreSQLDialect) AddColumnDDL

func (d *PostgreSQLDialect) AddColumnDDL(tableName string, column *ColumnInfo) string

func (*PostgreSQLDialect) AlterColumnDDL

func (d *PostgreSQLDialect) AlterColumnDDL(tableName string, column *ColumnInfo) string

func (*PostgreSQLDialect) ConvertJSONQuery

func (d *PostgreSQLDialect) ConvertJSONQuery(query string) string

func (*PostgreSQLDialect) ConvertValue

func (d *PostgreSQLDialect) ConvertValue(value interface{}, targetType string) (interface{}, error)

func (*PostgreSQLDialect) CreateIndexDDL

func (d *PostgreSQLDialect) CreateIndexDDL(tableName string, index *IndexInfo) string

func (*PostgreSQLDialect) CreateTableDDL

func (d *PostgreSQLDialect) CreateTableDDL(schema *TableSchema) string

func (*PostgreSQLDialect) DataTypeMapping

func (d *PostgreSQLDialect) DataTypeMapping(genericType string) string

func (*PostgreSQLDialect) DropColumnDDL

func (d *PostgreSQLDialect) DropColumnDDL(tableName, columnName string) string

func (*PostgreSQLDialect) DropIndexDDL

func (d *PostgreSQLDialect) DropIndexDDL(tableName, indexName string) string

func (*PostgreSQLDialect) LimitOffset

func (d *PostgreSQLDialect) LimitOffset(limit, offset int) string

func (*PostgreSQLDialect) Placeholder

func (d *PostgreSQLDialect) Placeholder(n int) string

func (*PostgreSQLDialect) QuoteIdentifier

func (d *PostgreSQLDialect) QuoteIdentifier(name string) string

func (*PostgreSQLDialect) SupportsCTE

func (d *PostgreSQLDialect) SupportsCTE() bool

func (*PostgreSQLDialect) SupportsFullTextSearch

func (d *PostgreSQLDialect) SupportsFullTextSearch() bool

func (*PostgreSQLDialect) SupportsJSON

func (d *PostgreSQLDialect) SupportsJSON() bool

func (*PostgreSQLDialect) SupportsReturning

func (d *PostgreSQLDialect) SupportsReturning() bool

func (*PostgreSQLDialect) SupportsUpsert

func (d *PostgreSQLDialect) SupportsUpsert() bool

func (*PostgreSQLDialect) TranslatePagination

func (d *PostgreSQLDialect) TranslatePagination(query string, limit, offset int) string

func (*PostgreSQLDialect) TranslateUpsert

func (d *PostgreSQLDialect) TranslateUpsert(table string, columns []string, conflictColumns []string) string

type ProxyConfig

type ProxyConfig struct {
	// MaxConnections is the maximum number of connections
	MaxConnections int

	// IdleTimeout is how long idle connections are kept
	IdleTimeout time.Duration

	// QueryTimeout is the default query timeout
	QueryTimeout time.Duration

	// EnableQueryRewrite enables query rewriting
	EnableQueryRewrite bool

	// EnableMonitoring enables query monitoring
	EnableMonitoring bool

	// EnableLoadBalancing enables load balancing across replicas
	EnableLoadBalancing bool

	// SlowQueryThreshold for logging slow queries
	SlowQueryThreshold time.Duration
}

ProxyConfig configures the database proxy

func DefaultProxyConfig

func DefaultProxyConfig() *ProxyConfig

DefaultProxyConfig returns default configuration

type ProxyMetrics

type ProxyMetrics struct {
	TotalQueries       int64
	SlowQueries        int64
	FailedQueries      int64
	CacheHits          int64
	AverageDuration    time.Duration
	SlowQueryThreshold time.Duration
}

ProxyMetrics contains proxy statistics

type QueryCache

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

QueryCache provides query result caching

func NewQueryCache

func NewQueryCache(config *QueryCacheConfig, backend CacheBackend) *QueryCache

NewQueryCache creates a new query cache

func (*QueryCache) Clear

func (qc *QueryCache) Clear(ctx context.Context) error

Clear removes all cached entries

func (*QueryCache) Get

func (qc *QueryCache) Get(ctx context.Context, query string, args ...interface{}) ([]byte, error)

Get retrieves a cached query result

func (*QueryCache) GetMetrics

func (qc *QueryCache) GetMetrics() CacheMetrics

GetMetrics returns cache metrics

func (*QueryCache) GetOrSet

func (qc *QueryCache) GetOrSet(
	ctx context.Context,
	query string,
	fetcher func() ([]byte, error),
	args ...interface{},
) ([]byte, error)

GetOrSet retrieves from cache or executes query and caches result

func (*QueryCache) Invalidate

func (qc *QueryCache) Invalidate(ctx context.Context, query string, args ...interface{}) error

Invalidate removes a specific cache entry

func (*QueryCache) InvalidatePattern

func (qc *QueryCache) InvalidatePattern(ctx context.Context, pattern string) error

InvalidatePattern removes cache entries matching a pattern

func (*QueryCache) InvalidateTable

func (qc *QueryCache) InvalidateTable(ctx context.Context, tableName string) error

InvalidateTable invalidates all queries related to a table

func (*QueryCache) ResetMetrics

func (qc *QueryCache) ResetMetrics()

ResetMetrics resets all metrics counters

func (*QueryCache) Set

func (qc *QueryCache) Set(ctx context.Context, query string, result []byte, args ...interface{}) error

Set stores a query result in cache

type QueryCacheConfig

type QueryCacheConfig struct {
	// Enabled enables/disables caching
	Enabled bool

	// DefaultTTL is the default time-to-live for cached queries
	DefaultTTL time.Duration

	// MaxCacheSize is the maximum size of cached values (in bytes)
	MaxCacheSize int

	// CacheKeyPrefix is prepended to all cache keys
	CacheKeyPrefix string

	// EnableMetrics enables cache hit/miss metrics
	EnableMetrics bool

	// InvalidationRules defines cache invalidation rules
	InvalidationRules []InvalidationRule
}

QueryCacheConfig configures the query cache

func DefaultQueryCacheConfig

func DefaultQueryCacheConfig() *QueryCacheConfig

DefaultQueryCacheConfig returns default configuration

type QueryLog

type QueryLog struct {
	Timestamp    time.Time
	Query        string
	Args         []interface{}
	Duration     time.Duration
	Error        error
	DBType       DBType
	Operation    string
	RowsAffected int64
}

QueryLog represents a single query execution log

type QueryLogger

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

QueryLogger logs all queries

func NewQueryLogger

func NewQueryLogger(maxLogs int) *QueryLogger

NewQueryLogger creates a new query logger

func (*QueryLogger) Clear

func (ql *QueryLogger) Clear()

Clear clears all query logs

func (*QueryLogger) GetRecentQueries

func (ql *QueryLogger) GetRecentQueries(n int) []QueryLog

GetRecentQueries returns recent query logs

func (*QueryLogger) Log

func (ql *QueryLogger) Log(query string, duration time.Duration, err error, args ...interface{})

Log logs a query

type QueryMetrics

type QueryMetrics struct {
	TotalQueries       int64
	TotalExecs         int64
	TotalErrors        int64
	SlowQueries        int64
	TotalDuration      time.Duration
	SlowQueryThreshold time.Duration

	// Query type breakdown
	SelectQueries int64
	InsertQueries int64
	UpdateQueries int64
	DeleteQueries int64
	OtherQueries  int64
	// contains filtered or unexported fields
}

QueryMetrics tracks query execution metrics

func (*QueryMetrics) GetAverageQueryTime

func (qm *QueryMetrics) GetAverageQueryTime() time.Duration

GetAverageQueryTime returns the average query execution time

func (*QueryMetrics) GetErrorRate

func (qm *QueryMetrics) GetErrorRate() float64

GetErrorRate returns the error rate as a percentage

func (*QueryMetrics) GetSlowQueryRate

func (qm *QueryMetrics) GetSlowQueryRate() float64

GetSlowQueryRate returns the slow query rate as a percentage

type QueryRewriter

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

QueryRewriter rewrites queries for optimization

func NewQueryRewriter

func NewQueryRewriter() *QueryRewriter

NewQueryRewriter creates a new query rewriter

func (*QueryRewriter) AddRule

func (qr *QueryRewriter) AddRule(rule RewriteRule)

AddRule adds a rewrite rule

func (*QueryRewriter) Rewrite

func (qr *QueryRewriter) Rewrite(query string) string

Rewrite applies rewrite rules to a query

type RateLimiter

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

RateLimiter provides basic rate limiting for database operations

func NewRateLimiter

func NewRateLimiter(maxQueriesPerSecond int) *RateLimiter

NewRateLimiter creates a new rate limiter

func (*RateLimiter) AllowQuery

func (rl *RateLimiter) AllowQuery() bool

AllowQuery checks if a query is allowed based on rate limits

type ReadWriteSplitter

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

ReadWriteSplitter splits read and write operations

func GetGlobalSplitter

func GetGlobalSplitter() *ReadWriteSplitter

GetGlobalSplitter returns the global read/write splitter

func NewReadWriteSplitter

func NewReadWriteSplitter(selector *DatabaseSelector) *ReadWriteSplitter

NewReadWriteSplitter creates a new read/write splitter

func (*ReadWriteSplitter) ForRead

func (rws *ReadWriteSplitter) ForRead(ctx context.Context) (RelationalDB, error)

ForRead returns a database connection for read operations

func (*ReadWriteSplitter) ForWrite

func (rws *ReadWriteSplitter) ForWrite(ctx context.Context) (RelationalDB, error)

ForWrite returns a database connection for write operations

type RelationalDB

type RelationalDB interface {
	// Connection Management
	Connect(config *DBConfig) error
	Close() error
	Ping() error
	DB() *sql.DB

	// Transaction Management
	BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)

	// Query Operations
	Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
	QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row
	Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

	// Database Information
	GetDialect() Dialect
	GetType() DBType
	SupportsFeature(feature Feature) bool

	// Health and Monitoring
	Stats() sql.DBStats
	IsConnected() bool

	// Schema Operations
	ListTables(ctx context.Context, schema string) ([]string, error)
	TableExists(ctx context.Context, schema, tableName string) (bool, error)
	GetTableSchema(ctx context.Context, schema, tableName string) (*TableSchema, error)
}

RelationalDB defines the interface for relational database operations This interface abstracts database-specific operations to support multiple database types

func GetDBInstance

func GetDBInstance(name string) (RelationalDB, error)

GetDBInstance retrieves a database instance using the global factory

func GetDatabase

func GetDatabase(ctx context.Context) (RelationalDB, bool)

GetDatabase retrieves database from context.Context

func GetOrCreateDB

func GetOrCreateDB(name string, config *DBConfig) (RelationalDB, error)

GetOrCreateDB gets or creates a database instance using the global factory

func NewRelationalDB

func NewRelationalDB(config *DBConfig) (RelationalDB, error)

NewRelationalDB creates a new relational database instance using the global factory

type ReplicaHealth

type ReplicaHealth struct {
	Name             string
	Active           bool
	Lag              *ReplicaLag
	ResponseTime     time.Duration
	ErrorCount       int
	LastError        error
	LastSuccessTime  time.Time
	ConsecutiveFails int
	Weight           int
	EffectiveWeight  int // Adjusted based on health
}

ReplicaHealth represents the health status of a replica

type ReplicaLag

type ReplicaLag struct {
	ReplicaName string
	LagSeconds  float64
	LastChecked time.Time
	IsHealthy   bool
	Error       error
}

ReplicaLag represents replication lag information for a replica

type ReplicaManager

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

ReplicaManager manages read replica connections with advanced features

func NewReplicaManager

func NewReplicaManager(config *ReplicaManagerConfig) *ReplicaManager

NewReplicaManager creates a new replica manager

func (*ReplicaManager) CheckReplicationLag

func (rm *ReplicaManager) CheckReplicationLag(ctx context.Context, db *sql.DB, dbType string) (float64, error)

CheckReplicationLag checks replication lag for a specific database type

func (*ReplicaManager) GetHealthyReplicaCount

func (rm *ReplicaManager) GetHealthyReplicaCount() int

GetHealthyReplicaCount returns the number of healthy replicas

func (*ReplicaManager) GetReplicaHealth

func (rm *ReplicaManager) GetReplicaHealth() map[string]*ReplicaHealth

GetReplicaHealth returns health information for all replicas

func (*ReplicaManager) GetStats

func (rm *ReplicaManager) GetStats() ReplicaManagerStats

GetStats returns statistics about replica manager

func (*ReplicaManager) RecordFailure

func (rm *ReplicaManager) RecordFailure(replicaName string, err error)

RecordFailure records a failed operation on a replica

func (*ReplicaManager) RecordSuccess

func (rm *ReplicaManager) RecordSuccess(replicaName string, responseTime time.Duration)

RecordSuccess records a successful operation on a replica

func (*ReplicaManager) RegisterReplica

func (rm *ReplicaManager) RegisterReplica(name string, weight int)

RegisterReplica registers a replica for monitoring

func (*ReplicaManager) SelectReplica

func (rm *ReplicaManager) SelectReplica() (string, error)

SelectReplica selects a replica based on the configured strategy

func (*ReplicaManager) StartMonitoring

func (rm *ReplicaManager) StartMonitoring(ctx context.Context, dbGetter func(string) (*sql.DB, string, error))

StartMonitoring starts background monitoring of replicas

func (*ReplicaManager) StopMonitoring

func (rm *ReplicaManager) StopMonitoring()

StopMonitoring stops background monitoring

func (*ReplicaManager) UnregisterReplica

func (rm *ReplicaManager) UnregisterReplica(name string)

UnregisterReplica removes a replica from monitoring

func (*ReplicaManager) UpdateReplicaLag

func (rm *ReplicaManager) UpdateReplicaLag(replicaName string, lagSeconds float64, err error)

UpdateReplicaLag updates the replication lag for a replica

type ReplicaManagerConfig

type ReplicaManagerConfig struct {
	// Strategy for load balancing across replicas
	Strategy LoadBalancingStrategy

	// MaxReplicaLag is the maximum acceptable replication lag in seconds
	MaxReplicaLag float64

	// LagCheckInterval is how often to check replication lag
	LagCheckInterval time.Duration

	// FailoverThreshold is how many consecutive failures before marking unhealthy
	FailoverThreshold int

	// RecoveryCheckInterval is how often to check if failed replicas recovered
	RecoveryCheckInterval time.Duration

	// EnableAutoRecovery automatically marks replicas as active when they recover
	EnableAutoRecovery bool

	// PreferLocalReplica prefers replicas in the same region/zone
	PreferLocalReplica bool

	// LocalRegion is the local region/zone identifier
	LocalRegion string
}

ReplicaManagerConfig configures the replica manager

func DefaultReplicaManagerConfig

func DefaultReplicaManagerConfig() *ReplicaManagerConfig

DefaultReplicaManagerConfig returns default configuration

type ReplicaManagerStats

type ReplicaManagerStats struct {
	TotalReplicas   int
	HealthyReplicas int
	TotalRequests   int64
	FailedRequests  int64
	LagChecks       int64
	Strategy        string
}

ReplicaManagerStats contains statistics about the replica manager

type RestoreOptions

type RestoreOptions struct {
	// DropExisting drops existing database before restore
	DropExisting bool

	// CreateDatabase creates database if it doesn't exist
	CreateDatabase bool

	// PointInTime restores to specific point in time
	PointInTime *time.Time

	// SkipVerification skips backup verification
	SkipVerification bool

	// TargetDatabase is the database to restore to (if different)
	TargetDatabase string
}

RestoreOptions configures restore operations

type RewriteRule

type RewriteRule struct {
	Name    string
	Pattern string
	Replace string
	Enabled bool
}

RewriteRule defines a query rewrite rule

type RoutingRule

type RoutingRule struct {
	Name     string
	Match    func(context.Context) bool
	Route    string
	Priority int
}

RoutingRule represents a routing rule

type SchemaManager

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

SchemaManager provides database-agnostic schema management operations It uses the dialect system to generate appropriate DDL for different databases

func NewSchemaManager

func NewSchemaManager(db *sql.DB, user string) (*SchemaManager, error)

NewSchemaManager creates a new SchemaManager instance It automatically detects the database type and uses the appropriate dialect

func (*SchemaManager) AddColumn

func (sm *SchemaManager) AddColumn(ctx context.Context, tableName string, column *ColumnInfo) error

AddColumn adds a new column to an existing table

func (*SchemaManager) AlterColumn

func (sm *SchemaManager) AlterColumn(ctx context.Context, tableName string, column *ColumnInfo) error

AlterColumn modifies an existing column's definition

func (*SchemaManager) CreateIndex

func (sm *SchemaManager) CreateIndex(ctx context.Context, tableName string, index *IndexInfo) error

CreateIndex creates a new index on a table

func (*SchemaManager) CreateTable

func (sm *SchemaManager) CreateTable(ctx context.Context, schema *TableSchema) error

CreateTable creates a new table based on the schema definition Works across all supported database types (MySQL, PostgreSQL, MSSQL, Oracle)

func (*SchemaManager) DropColumn

func (sm *SchemaManager) DropColumn(ctx context.Context, tableName, columnName string) error

DropColumn removes a column from a table

func (*SchemaManager) DropIndex

func (sm *SchemaManager) DropIndex(ctx context.Context, tableName, indexName string) error

DropIndex removes an index from a table

func (*SchemaManager) DropTable

func (sm *SchemaManager) DropTable(ctx context.Context, tableName string) error

DropTable removes a table from the database

func (*SchemaManager) MigrateSchema

func (sm *SchemaManager) MigrateSchema(ctx context.Context, desiredSchema *TableSchema) error

MigrateSchema compares current schema with desired schema and applies changes This is useful for schema evolution without manual DDL management

func (*SchemaManager) TableExists

func (sm *SchemaManager) TableExists(ctx context.Context, tableName string) (bool, error)

TableExists checks if a table exists in the database

type SecurityConfig

type SecurityConfig struct {
	EnforceSSL          bool   // Enforce SSL/TLS connections
	ValidateIdentifiers bool   // Validate schema/table/column names
	LogQueries          bool   // Log all queries (be careful with sensitive data)
	LogParameters       bool   // Log query parameters (disable in production)
	MaxQueryDuration    int    // Maximum query duration in seconds
	EnableAuditLog      bool   // Enable audit logging
	RateLimitQPS        int    // Queries per second limit (0 = unlimited)
	Environment         string // Environment (production, staging, development)
}

SecurityConfig holds security configuration options

func DefaultSecurityConfig

func DefaultSecurityConfig() *SecurityConfig

DefaultSecurityConfig returns default security configuration

type SelectionRule

type SelectionRule struct {
	Name      string
	Priority  int
	Condition func(*DatabaseContext) bool
	Action    func(*DatabaseContext) (string, error)
}

SelectionRule represents a rule for database selection

type SelectionStrategy

type SelectionStrategy string

SelectionStrategy represents the strategy for selecting a database

const (
	StrategyRoundRobin     SelectionStrategy = "round_robin"
	StrategyLeastConn      SelectionStrategy = "least_conn"
	StrategyPriority       SelectionStrategy = "priority"
	StrategyRandom         SelectionStrategy = "random"
	StrategyConsistentHash SelectionStrategy = "consistent_hash"
)

type Shard

type Shard struct {
	ID     int
	Name   string
	DB     *sql.DB
	DBType string
	Config *DBConfig
	Active bool
	Weight int
	Region string

	// For range sharding
	MinRange interface{}
	MaxRange interface{}

	// Statistics
	QueryCount int64
	ErrorCount int64
	// contains filtered or unexported fields
}

Shard represents a single database shard

type ShardManager

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

ShardManager manages database sharding

func NewShardManager

func NewShardManager(config *ShardManagerConfig) *ShardManager

NewShardManager creates a new shard manager

func (*ShardManager) AddLookupMapping

func (sm *ShardManager) AddLookupMapping(key string, shardID int)

AddLookupMapping adds a lookup mapping for lookup-based sharding

func (*ShardManager) AddRangeMapping

func (sm *ShardManager) AddRangeMapping(shardID int, minValue, maxValue interface{})

AddRangeMapping adds a range mapping for range-based sharding

func (*ShardManager) AddShard

func (sm *ShardManager) AddShard(shard *Shard) error

AddShard adds a shard to the manager

func (*ShardManager) ExecuteOnAllShards

func (sm *ShardManager) ExecuteOnAllShards(ctx context.Context, query string, args ...interface{}) ([]*ShardQueryResult, error)

ExecuteOnAllShards executes a query on all shards (cross-shard query)

func (*ShardManager) ExecuteOnShard

func (sm *ShardManager) ExecuteOnShard(ctx context.Context, shardKey string, query string, args ...interface{}) (*sql.Rows, error)

ExecuteOnShard executes a query on a specific shard

func (*ShardManager) ExecuteOnShardTx

func (sm *ShardManager) ExecuteOnShardTx(ctx context.Context, shardKey string, fn func(*sql.Tx) error) error

ExecuteOnShardTx executes a query within a transaction on a shard

func (*ShardManager) GetActiveShardCount

func (sm *ShardManager) GetActiveShardCount() int

GetActiveShardCount returns the number of active shards

func (*ShardManager) GetAllShards

func (sm *ShardManager) GetAllShards() []*Shard

GetAllShards returns all active shards

func (*ShardManager) GetShard

func (sm *ShardManager) GetShard(shardKey string) (*Shard, error)

GetShard returns the shard for a given shard key

func (*ShardManager) GetShardCount

func (sm *ShardManager) GetShardCount() int

GetShardCount returns the number of shards

func (*ShardManager) GetShardStats

func (sm *ShardManager) GetShardStats() []ShardStats

GetShardStats returns statistics for all shards

func (*ShardManager) MigrateShard

func (sm *ShardManager) MigrateShard(ctx context.Context, key string, targetShardID int) error

MigrateShard migrates a shard key from one shard to another

func (*ShardManager) RebalanceShards

func (sm *ShardManager) RebalanceShards(ctx context.Context) error

RebalanceShards rebalances data across shards (placeholder for complex logic)

func (*ShardManager) RemoveShard

func (sm *ShardManager) RemoveShard(shardID int) error

RemoveShard removes a shard from the manager

func (*ShardManager) ShardDistribution

func (sm *ShardManager) ShardDistribution(keys []string) map[int]int

ShardDistribution calculates the distribution of keys across shards

type ShardManagerConfig

type ShardManagerConfig struct {
	// Strategy for sharding
	Strategy ShardingStrategy

	// HashFunc for hash-based strategies
	HashFunc HashFunction

	// VirtualNodes for consistent hashing
	VirtualNodes int

	// EnableCrossShard allows cross-shard queries
	EnableCrossShard bool

	// MaxCrossShardQueries limits concurrent cross-shard queries
	MaxCrossShardQueries int

	// CrossShardTimeout for cross-shard query timeout
	CrossShardTimeout int // seconds
}

ShardManagerConfig configures the shard manager

func DefaultShardManagerConfig

func DefaultShardManagerConfig() *ShardManagerConfig

DefaultShardManagerConfig returns default configuration

type ShardQueryResult

type ShardQueryResult struct {
	ShardID   int
	ShardName string
	Rows      *sql.Rows
	Error     error
}

ShardQueryResult represents the result of a query on a shard

type ShardRange

type ShardRange struct {
	ShardID  int
	MinValue interface{}
	MaxValue interface{}
}

ShardRange represents a range for range-based sharding

type ShardStats

type ShardStats struct {
	ShardID    int
	ShardName  string
	Active     bool
	QueryCount int64
	ErrorCount int64
	Region     string
}

ShardStats represents statistics for a shard

type ShardingStrategy

type ShardingStrategy string

ShardingStrategy defines the strategy for shard key selection

const (
	// HashModulo uses hash(key) % shard_count
	HashModulo ShardingStrategy = "hash_modulo"

	// ConsistentHash uses consistent hashing
	ConsistentHash ShardingStrategy = "consistent_hash"

	// RangeSharding uses range-based sharding
	RangeSharding ShardingStrategy = "range"

	// LookupSharding uses a lookup table
	LookupSharding ShardingStrategy = "lookup"
)

type TableSchema

type TableSchema struct {
	Schema      string
	TableName   string
	Columns     []ColumnInfo
	PrimaryKeys []string
	Indexes     []IndexInfo
}

TableSchema represents database table schema information

type TrackedDB

type TrackedDB struct {
	RelationalDB
	// contains filtered or unexported fields
}

TrackedDB wraps a RelationalDB with query tracking

func NewTrackedDB

func NewTrackedDB(db RelationalDB, dbType DBType) *TrackedDB

NewTrackedDB creates a new tracked database wrapper

func (*TrackedDB) Exec

func (t *TrackedDB) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

Exec executes a statement with tracking

func (*TrackedDB) Query

func (t *TrackedDB) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

Query executes a query with tracking

type TransactionManager

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

TransactionManager manages database transactions

func NewTransactionManager

func NewTransactionManager(db RelationalDB) *TransactionManager

NewTransactionManager creates a new transaction manager

func (*TransactionManager) Begin

Begin starts a new transaction

func (*TransactionManager) ExecuteInTransaction

func (tm *TransactionManager) ExecuteInTransaction(ctx context.Context, opts *TransactionOptions, fn func(*sql.Tx) error) error

ExecuteInTransaction executes a function within a transaction

func (*TransactionManager) GetActiveTxnCount

func (tm *TransactionManager) GetActiveTxnCount() int

GetActiveTxnCount returns the number of active transactions

func (*TransactionManager) GetActiveTxnIDs

func (tm *TransactionManager) GetActiveTxnIDs() []string

GetActiveTxnIDs returns IDs of all active transactions

func (*TransactionManager) SetDefaultIsolation

func (tm *TransactionManager) SetDefaultIsolation(isolation sql.IsolationLevel)

SetDefaultIsolation sets the default isolation level

func (*TransactionManager) SetMaxRetries

func (tm *TransactionManager) SetMaxRetries(maxRetries int)

SetMaxRetries sets the maximum number of retries for retryable errors

func (*TransactionManager) SetRetryDelay

func (tm *TransactionManager) SetRetryDelay(delay time.Duration)

SetRetryDelay sets the delay between retries

type TransactionOptions

type TransactionOptions struct {
	Isolation  sql.IsolationLevel
	ReadOnly   bool
	MaxRetries int
	RetryDelay time.Duration
	Timeout    time.Duration
}

TransactionOptions configures transaction behavior

type Version

type Version struct {
	Number      int
	Description string
	AppliedAt   time.Time
	Applied     bool
	Checksum    string
}

Version represents a database schema version

type VersionManager

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

VersionManager manages database schema versions

func NewVersionManager

func NewVersionManager(db *sql.DB, dbType string, config *VersionManagerConfig) (*VersionManager, error)

NewVersionManager creates a new version manager

func (*VersionManager) CheckCompatibility

func (vm *VersionManager) CheckCompatibility(ctx context.Context, minVersion, maxVersion int) error

CheckCompatibility checks if application is compatible with database version

func (*VersionManager) GetAppliedVersions

func (vm *VersionManager) GetAppliedVersions(ctx context.Context) ([]*Version, error)

GetAppliedVersions returns all applied versions

func (*VersionManager) GetCurrentVersion

func (vm *VersionManager) GetCurrentVersion(ctx context.Context) (int, error)

GetCurrentVersion returns the current database version

func (*VersionManager) GetMigrationHistory

func (vm *VersionManager) GetMigrationHistory(ctx context.Context) ([]MigrationRecord, error)

GetMigrationHistory returns full migration history

func (*VersionManager) GetMigrations

func (vm *VersionManager) GetMigrations() []*Migration

GetMigrations returns all registered migrations

func (*VersionManager) GetPendingMigrations

func (vm *VersionManager) GetPendingMigrations(ctx context.Context) ([]*Migration, error)

GetPendingMigrations returns migrations not yet applied

func (*VersionManager) GetVersionDiff

func (vm *VersionManager) GetVersionDiff(version1, version2 int) ([]*Migration, error)

GetVersionDiff returns the difference between two versions

func (*VersionManager) MarkAsApplied

func (vm *VersionManager) MarkAsApplied(ctx context.Context, version int, description string) error

MarkAsApplied manually marks a version as applied (for legacy databases)

func (*VersionManager) Migrate

func (vm *VersionManager) Migrate(ctx context.Context) error

Migrate applies all pending migrations

func (*VersionManager) MigrateTo

func (vm *VersionManager) MigrateTo(ctx context.Context, targetVersion int) error

MigrateTo migrates to a specific version

func (*VersionManager) RegisterMigration

func (vm *VersionManager) RegisterMigration(migration *Migration) error

RegisterMigration registers a migration

func (*VersionManager) Reset

func (vm *VersionManager) Reset(ctx context.Context) error

Reset removes all version records (dangerous!)

type VersionManagerConfig

type VersionManagerConfig struct {
	// VersionTable is the name of the version tracking table
	VersionTable string

	// AutoMigrate enables automatic migration on startup
	AutoMigrate bool

	// ValidateChecksums verifies migration checksums
	ValidateChecksums bool

	// AllowOutOfOrder allows out-of-order migrations
	AllowOutOfOrder bool
}

VersionManagerConfig configures version management

func DefaultVersionManagerConfig

func DefaultVersionManagerConfig() *VersionManagerConfig

DefaultVersionManagerConfig returns default configuration

Directories

Path Synopsis
orm
The original package is migrated from beego and modified, you can find orignal from following link:
The original package is migrated from beego and modified, you can find orignal from following link:

Jump to

Keyboard shortcuts

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