db

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2025 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Builder

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

Builder helps build complex SQL queries

func NewBuilder

func NewBuilder(table string) *Builder

NewBuilder creates a new query builder SECURITY: The table parameter must be a validated, trusted identifier. Do NOT pass user input directly - validate/whitelist table names first.

func (*Builder) AddSubquery

func (b *Builder) AddSubquery(name string, subquery *Builder) *Builder

AddSubquery adds a named subquery

func (*Builder) BuildDelete

func (b *Builder) BuildDelete(whereField string) string

BuildDelete builds a DELETE query

func (*Builder) BuildInsert

func (b *Builder) BuildInsert(columns []string) (string, int)

BuildInsert builds an INSERT query

func (*Builder) BuildSelect

func (b *Builder) BuildSelect() (string, []interface{})

BuildSelect builds a SELECT query

func (*Builder) BuildUpdate

func (b *Builder) BuildUpdate(columns []string, whereField string) (string, int)

BuildUpdate builds an UPDATE query

func (*Builder) Distinct

func (b *Builder) Distinct() *Builder

Distinct enables DISTINCT selection

func (*Builder) GroupBy

func (b *Builder) GroupBy(columns ...string) *Builder

GroupBy adds GROUP BY columns

func (*Builder) Having

func (b *Builder) Having(field string, operator Operator, value interface{}) *Builder

Having adds a HAVING condition

func (*Builder) InnerJoin

func (b *Builder) InnerJoin(table, condition string) *Builder

InnerJoin adds an INNER JOIN

func (*Builder) Join

func (b *Builder) Join(joinType JoinType, table, condition string) *Builder

Join adds a JOIN clause

func (*Builder) LeftJoin

func (b *Builder) LeftJoin(table, condition string) *Builder

LeftJoin adds a LEFT JOIN

func (*Builder) Limit

func (b *Builder) Limit(limit int) *Builder

Limit sets the LIMIT clause Negative values are normalized to 0

func (*Builder) Offset

func (b *Builder) Offset(offset int) *Builder

Offset sets the OFFSET clause Negative values are normalized to 0

func (*Builder) OrWhere

func (b *Builder) OrWhere(field string, operator Operator, value interface{}) *Builder

OrWhere adds an OR WHERE condition For predictable behavior, this wraps the existing conditions in an OR group

func (*Builder) OrderBy

func (b *Builder) OrderBy(field string, desc bool) *Builder

OrderBy adds an ORDER BY clause

func (*Builder) RightJoin

func (b *Builder) RightJoin(table, condition string) *Builder

RightJoin adds a RIGHT JOIN

func (*Builder) Select

func (b *Builder) Select(cols ...string) *Builder

Select sets the columns to select SECURITY: Column names are NOT escaped. Only pass validated, trusted identifiers. User input should NOT be passed to this method.

func (*Builder) Where

func (b *Builder) Where(field string, operator Operator, value interface{}) *Builder

Where adds a WHERE condition SECURITY: Field name is NOT escaped - must be a validated identifier. User input should be passed via the 'value' parameter, which is properly parameterized.

func (*Builder) WhereGroup

func (b *Builder) WhereGroup(operator LogicalOperator, fn func(*ConditionGroup)) *Builder

WhereGroup adds a grouped WHERE condition

type Condition

type Condition struct {
	Field    string
	Operator Operator
	Value    interface{}
}

Condition represents a WHERE/HAVING clause condition

type ConditionGroup

type ConditionGroup struct {
	Conditions []interface{} // Can be Condition or nested ConditionGroup
	Operator   LogicalOperator
}

ConditionGroup represents grouped conditions with logical operators

func (*ConditionGroup) Group

func (g *ConditionGroup) Group(operator LogicalOperator, fn func(*ConditionGroup)) *ConditionGroup

Helper method to add nested condition groups

func (*ConditionGroup) Where

func (g *ConditionGroup) Where(field string, operator Operator, value interface{}) *ConditionGroup

Helper method to add conditions to a condition group

type Config

type Config struct {
	// Connection Settings
	Host     string `json:"host" yaml:"host"`
	Port     int    `json:"port" yaml:"port"`
	Database string `json:"database" yaml:"database"`
	Username string `json:"username" yaml:"username"`
	Password string `json:"password" yaml:"password"`

	// Connection Pool Settings
	MaxOpenConns    int           `json:"max_open_conns" yaml:"max_open_conns"`
	MaxIdleConns    int           `json:"max_idle_conns" yaml:"max_idle_conns"`
	ConnMaxLifetime time.Duration `json:"conn_max_lifetime" yaml:"conn_max_lifetime"`
	ConnMaxIdleTime time.Duration `json:"conn_max_idle_time" yaml:"conn_max_idle_time"`

	// MySQL Specific Settings
	Charset   string `json:"charset" yaml:"charset"`     // Default: utf8mb4
	Collation string `json:"collation" yaml:"collation"` // Default: utf8mb4_unicode_ci
	TimeZone  string `json:"timezone" yaml:"timezone"`   // Default: UTC

	// GORM Settings
	DisableForeignKeyConstraintWhenMigrating bool          `json:"disable_foreign_key_constraint_when_migrating" yaml:"disable_foreign_key_constraint_when_migrating"`
	SkipDefaultTransaction                   bool          `json:"skip_default_transaction" yaml:"skip_default_transaction"`
	PrepareStmt                              bool          `json:"prepare_stmt" yaml:"prepare_stmt"`
	QueryTimeout                             time.Duration `json:"query_timeout" yaml:"query_timeout"`

	// SSL Configuration
	SSL SSLConfig `json:"ssl" yaml:"ssl"`

	// Logging Configuration
	Logging LoggingConfig `json:"logging" yaml:"logging"`
}

Config holds MySQL/GORM database configuration

func (*Config) GetDSN

func (c *Config) GetDSN() string

GetDSN returns the MySQL Data Source Name using the official MySQL driver config builder

func (*Config) Validate

func (c *Config) Validate() error

Validate checks if the database configuration is valid

type JoinClause

type JoinClause struct {
	Type      JoinType
	Table     string
	Condition string
}

JoinClause represents a JOIN operation

type JoinType

type JoinType string

JoinType represents SQL JOIN types

const (
	InnerJoin JoinType = "INNER JOIN"
	LeftJoin  JoinType = "LEFT JOIN"
	RightJoin JoinType = "RIGHT JOIN"
	FullJoin  JoinType = "FULL OUTER JOIN"
	CrossJoin JoinType = "CROSS JOIN"
)

type LoggingConfig

type LoggingConfig struct {
	// General Logging
	Level  string `json:"level" yaml:"level"`   // debug, info, warn, error
	Format string `json:"format" yaml:"format"` // json, text

	// Database Logging
	LogQueries         bool          `json:"log_queries" yaml:"log_queries"`
	LogSlowQueries     bool          `json:"log_slow_queries" yaml:"log_slow_queries"`
	SlowQueryThreshold time.Duration `json:"slow_query_threshold" yaml:"slow_query_threshold"`
	LogQueryParameters bool          `json:"log_query_parameters" yaml:"log_query_parameters"`

	// Performance Logging
	LogPerformanceMetrics bool          `json:"log_performance_metrics" yaml:"log_performance_metrics"`
	MetricsInterval       time.Duration `json:"metrics_interval" yaml:"metrics_interval"`
}

LoggingConfig controls database logging behavior

type LogicalOperator

type LogicalOperator string

LogicalOperator for combining conditions

const (
	And LogicalOperator = "AND"
	Or  LogicalOperator = "OR"
)

type Manager

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

Manager manages database connections

func NewDefaultManager

func NewDefaultManager(host, database, username, password string) (*Manager, error)

NewDefaultManager creates a database manager with minimal configuration

func NewManager

func NewManager(config *Config) (*Manager, error)

NewManager creates a new database manager instance with full configuration

func NewSingletonManager

func NewSingletonManager(config *Config) (*Manager, error)

NewSingletonManager returns the singleton database manager instance

IMPORTANT: Singleton Initialization Behavior

  • The first call to NewSingletonManager initializes the singleton instance
  • If the first call fails, the singleton remains uninitialized permanently
  • Subsequent calls return the error from the first failed attempt
  • There is no automatic retry mechanism - this is by design for production stability
  • Once successfully initialized, subsequent calls ignore the config parameter

Error Recovery:

  • For testing: Use NewManager(config) directly instead of the singleton
  • For production: Ensure the first call uses valid configuration
  • To reset in tests: Call ResetSingleton() (if implemented) or restart the application

Thread-Safety:

  • This function is safe for concurrent calls
  • The initialization only happens once, protected by sync.Once

func (*Manager) Close

func (m *Manager) Close() error

Close closes the database connection

func (*Manager) Config

func (m *Manager) Config() *Config

Config returns the manager's configuration

func (*Manager) DB

func (m *Manager) DB() *gorm.DB

DB returns the GORM database instance

func (*Manager) Ping

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

Ping tests the database connection

func (*Manager) SqlDB

func (m *Manager) SqlDB() (*sql.DB, error)

SqlDB returns the underlying sql.DB instance

func (*Manager) Stats

func (m *Manager) Stats() (sql.DBStats, error)

Stats returns database connection statistics

type Operator

type Operator string

Operator represents SQL comparison operators

const (
	Equal              Operator = "="
	NotEqual           Operator = "!="
	GreaterThan        Operator = ">"
	GreaterThanOrEqual Operator = ">="
	LessThan           Operator = "<"
	LessThanOrEqual    Operator = "<="
	Like               Operator = "LIKE"
	NotLike            Operator = "NOT LIKE"
	In                 Operator = "IN"
	NotIn              Operator = "NOT IN"
	IsNull             Operator = "IS NULL"
	IsNotNull          Operator = "IS NOT NULL"
	Between            Operator = "BETWEEN"
	NotBetween         Operator = "NOT BETWEEN"
)

type SSLConfig

type SSLConfig struct {
	Enabled    bool   `json:"enabled" yaml:"enabled"`
	CertFile   string `json:"cert_file" yaml:"cert_file"`
	KeyFile    string `json:"key_file" yaml:"key_file"`
	CAFile     string `json:"ca_file" yaml:"ca_file"`
	SkipVerify bool   `json:"skip_verify" yaml:"skip_verify"` // Skip certificate verification (not recommended for production)
	ServerName string `json:"server_name" yaml:"server_name"`
	MinVersion string `json:"min_version" yaml:"min_version"` // TLS1.2, TLS1.3
}

SSLConfig holds SSL/TLS configuration for MySQL

Jump to

Keyboard shortcuts

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