Documentation
¶
Overview ¶
Package xdb provides functionality for creating and managing database connections using the GORM library. It supports multiple database types including MySQL, PostgreSQL, SQLite, SQL Server, and ClickHouse. It uses the functional options pattern for flexible configuration of database connections with customizable connection pool settings.
Index ¶
- func Close(db *gorm.DB) error
- func CloseAll(dbs map[string]*gorm.DB) error
- func New(opts ...Option) (*gorm.DB, error)
- func NewLog(manager *sklogger.Manager, opts ...LoggerOption) gormlogger.Interface
- func NewMulti(configs ...[]Option) (map[string]*gorm.DB, error)
- func Ping(db *gorm.DB) error
- func Stats(db *gorm.DB) (sql.DBStats, error)
- type DBConfig
- type Driver
- type LoggerOption
- type Option
- func WithCharset(charset string) Option
- func WithConnMaxIdleTime(d time.Duration) Option
- func WithConnMaxLifetime(d time.Duration) Option
- func WithDBConfig(cfg DBConfig) Option
- func WithDBName(name string) Option
- func WithDriver(driver Driver) Option
- func WithGormConfig(cfg gorm.Config) Option
- func WithHost(host string) Option
- func WithMaxIdleConns(n int) Option
- func WithMaxOpenConns(n int) Option
- func WithPassword(password string) Option
- func WithPort(port int) Option
- func WithSSLMode(mode string) Option
- func WithTimezone(tz string) Option
- func WithUser(user string) Option
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Close ¶
Close closes the database connection.
Example:
if err := Close(db); err != nil {
log.Error("failed to close connection:", err)
}
func CloseAll ¶
CloseAll closes all database connections in the map.
Example:
if err := CloseAll(dbs); err != nil {
log.Error("failed to close connections:", err)
}
func New ¶
New initializes and returns a database connection instance.
Example:
db, err := New(
WithDriver(MySQL),
WithHost("localhost"),
WithPort(3306),
WithUser("root"),
WithPassword("secret"),
WithDBName("mydb"),
WithMaxIdleConns(10),
WithMaxOpenConns(100),
)
func NewLog ¶
func NewLog(manager *sklogger.Manager, opts ...LoggerOption) gormlogger.Interface
NewLog creates and returns a new logger instance with the given options.
Parameters:
- manager: A pointer to the sklogger.Manager to use for logging.
- opts: A variadic list of LoggerOption functions to configure the logger.
Returns:
- A new gormlogger.Interface configured with the provided options.
Example:
logger := NewLog(manager, WithLevel("info"), WithSlowThreshold(300*time.Millisecond))
func NewMulti ¶
NewMulti creates multiple database connections and returns them as a map. Each connection is identified by its dbName from the Options.
Example:
dbs, err := NewMulti(
[]Option{
WithHost("localhost"),
WithDBName("master_db"),
},
[]Option{
WithHost("localhost"),
WithDBName("slave_db"),
},
)
masterDB := dbs["master_db"]
slaveDB := dbs["slave_db"]
Types ¶
type DBConfig ¶
type DBConfig struct {
Driver Driver // Database driver type
Host string // Database host (for SQLite, this is the file path)
Port int // Database port
User string // Database user
Password string // Database password
DBName string // Database name
SSLMode string // SSL mode (for PostgreSQL)
Timezone string // Timezone (for PostgreSQL and ClickHouse)
Charset string // Character set (for MySQL)
MaxIdleConns int // Maximum number of idle connections
MaxOpenConns int // Maximum number of open connections
ConnMaxLifetime time.Duration // Maximum connection lifetime
ConnMaxIdleTime time.Duration // Maximum idle time for connections
GormConfig *gorm.Config // GORM configuration
}
DBConfig holds all the configuration options for database connections. Use this with WithDBConfig to set multiple options at once.
Example:
db, err := New(WithDBConfig(DBConfig{
Driver: MySQL,
Host: "localhost",
Port: 3306,
User: "root",
Password: "secret",
DBName: "mydb",
MaxIdleConns: 10,
MaxOpenConns: 100,
}))
type LoggerOption ¶
type LoggerOption func(*logger)
LoggerOption is a function type used to configure the logger.
func WithIgnoreRecordNotFoundError ¶
func WithIgnoreRecordNotFoundError(ignore bool) LoggerOption
WithIgnoreRecordNotFoundError returns a LoggerOption that sets whether to ignore "record not found" errors.
Parameters:
- ignore: A boolean indicating whether to ignore "record not found" errors.
Returns:
- A LoggerOption function that sets the ignore flag when applied.
Example:
logger := NewLog(manager, WithIgnoreRecordNotFoundError(true))
func WithLevel ¶
func WithLevel(level string) LoggerOption
WithLevel returns a LoggerOption that sets the log level for the logger.
Parameters:
- level: A string representing the desired log level ("debug", "info", "warn", or "silent").
Returns:
- A LoggerOption function that sets the log level when applied.
Example:
logger := NewLog(manager, WithLevel("info"))
func WithSlowThreshold ¶
func WithSlowThreshold(threshold time.Duration) LoggerOption
WithSlowThreshold returns a LoggerOption that sets the threshold for slow query logging.
Parameters:
- threshold: A time.Duration representing the slow query threshold.
Returns:
- A LoggerOption function that sets the slow threshold when applied.
Example:
logger := NewLog(manager, WithSlowThreshold(500 * time.Millisecond))
type Option ¶
type Option func(*option)
Option is a function type used to apply configuration options.
func WithCharset ¶
WithCharset sets the character set (for MySQL, default: utf8mb4).
Example:
db, err := New(WithCharset("utf8mb4"), ...)
func WithConnMaxIdleTime ¶
WithConnMaxIdleTime sets the maximum amount of time a connection may be idle.
Example:
db, err := New(WithConnMaxIdleTime(10 * time.Minute), ...)
func WithConnMaxLifetime ¶
WithConnMaxLifetime sets the maximum amount of time a connection may be reused.
Example:
db, err := New(WithConnMaxLifetime(time.Hour), ...)
func WithDBConfig ¶
WithDBConfig sets multiple database options from a DBConfig struct. Only non-zero values will be applied.
Example:
db, err := New(WithDBConfig(DBConfig{
Driver: MySQL,
Host: "localhost",
Port: 3306,
User: "root",
Password: "secret",
DBName: "mydb",
MaxIdleConns: 10,
MaxOpenConns: 100,
}))
func WithDBName ¶
WithDBName sets the database name.
Example:
db, err := New(WithDBName("mydb"), ...)
func WithDriver ¶
WithDriver sets the database driver type.
Example:
db, err := New(WithDriver(MySQL), WithHost("localhost"), ...)
func WithGormConfig ¶
WithGormConfig sets the GORM configuration.
Example:
db, err := New(WithGormConfig(gorm.Config{SkipDefaultTransaction: true}), ...)
func WithHost ¶
WithHost sets the database host address. For SQLite, this should be the file path.
Example:
db, err := New(WithHost("localhost"), ...)
func WithMaxIdleConns ¶
WithMaxIdleConns sets the maximum number of idle connections in the pool.
Example:
db, err := New(WithMaxIdleConns(10), ...)
func WithMaxOpenConns ¶
WithMaxOpenConns sets the maximum number of open connections to the database.
Example:
db, err := New(WithMaxOpenConns(100), ...)
func WithPassword ¶
WithPassword sets the database password.
Example:
db, err := New(WithPassword("secret"), ...)
func WithPort ¶
WithPort sets the database port. If not specified, the default port for the driver will be used.
Example:
db, err := New(WithPort(3306), ...)
func WithSSLMode ¶
WithSSLMode sets the SSL mode (for PostgreSQL). Valid values: disable, require, verify-ca, verify-full
Example:
db, err := New(WithDriver(PostgreSQL), WithSSLMode("require"), ...)
func WithTimezone ¶
WithTimezone sets the timezone (for PostgreSQL and ClickHouse).
Example:
db, err := New(WithTimezone("Asia/Shanghai"), ...)