db

package
v1.0.14 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

建议:不要直接使用本包中的 db.DB / db.Table 操作数据库,推荐使用 model.EntryModel 或 model.Model, 它们提供了类型安全、更高层级的 CRUD 封装,代码更简洁且不易出错。

Recommendation: Prefer model.EntryModel or model.Model over raw db.DB / db.Table. They provide type-safe, higher-level CRUD operations — less boilerplate and fewer mistakes.

推奨: 本パッケージの生の db.DB / db.Table ではなく model.EntryModel または model.Model を使用してください。 型安全で抽象度の高い CRUD 操作が提供され、コードが簡潔になりミスも減ります。

권장: 이 패키지의 raw db.DB / db.Table 대신 model.EntryModel 또는 model.Model 을 사용하세요. 타입 안전하고 더 높은 수준의 CRUD 연산을 제공하므로 코드가 간결해지고 실수가 줄어듭니다.

Рекомендация: используйте model.EntryModel или model.Model вместо прямого db.DB / db.Table из этого пакета. Они предоставляют типобезопасные CRUD-операции высокого уровня — меньше шаблонного кода и ошибок.

Index

Constants

View Source
const (
	MYSQL      = "mysql"
	POSTGRES   = "postgres"
	POSTGRESQL = "postgresql"
	SQLITE     = "sqlite"
)
View Source
const ConfigKey = "web.db"

Variables

View Source
var NoConfigDBError = &noConfigDBError{}

NoConfigDBError is returned when no database configuration is found.

Functions

func ApplyConnectionPool added in v0.5.1

func ApplyConnectionPool(db *gorm.DB, cfg ConnectionPoolConfig) error

ApplyConnectionPool applies connection pool settings to the underlying sql.DB

func RegisterDB added in v1.0.9

func RegisterDB(typeName string, dbConfig IConfig)

RegisterDB 注册自定义数据库驱动,typeName 为配置中的类型名称,dbConfig 为对应的配置实现。

Types

type Config added in v0.1.3

type Config struct {
	Type string
}

Config holds the basic database configuration.

type ConnectionPoolConfig added in v0.5.1

type ConnectionPoolConfig interface {
	GetMaxOpenConns() int
	GetMaxIdleConns() int
	GetConnMaxLifetime() int
}

ConnectionPoolConfig defines the interface for database connection pool configuration

type DB

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

建议:不要直接使用 db.DB / db.Table 操作数据库,推荐使用 model.EntryModel 或 model.Model, 它们提供了类型安全、更高层级的 CRUD 封装,代码更简洁且不易出错。

Recommendation: Prefer model.EntryModel or model.Model over raw db.DB / db.Table. They provide type-safe, higher-level CRUD operations — less boilerplate and fewer mistakes.

推奨: 生の db.DB / db.Table ではなく model.EntryModel または model.Model を使用してください。 型安全で抽象度の高い CRUD 操作が提供され、コードが簡潔になりミスも減ります。

권장: raw db.DB / db.Table 대신 model.EntryModel 또는 model.Model 을 사용하세요. 타입 안전하고 더 높은 수준의 CRUD 연산을 제공하므로 코드가 간결해지고 실수가 줄어듭니다.

Рекомендация: используйте model.EntryModel или model.Model вместо прямого db.DB / db.Table. Они предоставляют типобезопасные CRUD-операции высокого уровня — меньше шаблонного кода и ошибок.

func ConnectionMysql added in v0.1.4

func ConnectionMysql(host string, port int, username string, password string, dbname string, charset string) (db *DB, err error)

ConnectionMysql creates a new MySQL database connection.

func ConnectionPostgres added in v0.5.1

func ConnectionPostgres(host string, port int, username, password, database string, sslMode string) (db *DB, err error)

ConnectionPostgres creates a new PostgreSQL connection with given parameters

func ConnectionSQLite added in v0.1.4

func ConnectionSQLite(FilePath string) (db *DB, err error)

ConnectionSQLite creates a new SQLite database connection.

func CreateDB added in v0.1.3

func CreateDB(c config.IConfig) (*DB, error)

CreateDB 根据配置创建数据库连接。

func (*DB) GetGorm added in v1.0.10

func (d *DB) GetGorm() *gorm.DB

func (*DB) Migrator added in v0.1.3

func (d *DB) Migrator() gorm.Migrator

Migrator returns the GORM migrator for schema management.

func (*DB) New added in v0.1.4

func (d *DB) New() *DB

New creates a fresh DB instance with the original GORM connection.

func (*DB) Table added in v0.1.3

func (d *DB) Table(name string) *Table

Table returns a Table instance for the given table name.

func (*DB) Transaction added in v0.1.3

func (d *DB) Transaction(fc func(tx *DB) error) error

Transaction executes fc within a database transaction. The transaction is committed if fc returns nil, rolled back otherwise.

func (*DB) WithContext added in v0.9.4

func (d *DB) WithContext(ctx context.Context) *DB

WithContext returns a new DB whose underlying *gorm.DB carries the given context. The original DB instance is unchanged; safe for concurrent use across requests.

type IConfig added in v0.1.3

type IConfig interface {
	Connection() (*DB, error)
}

IConfig defines the interface for database configuration sources.

type MysqlConfig added in v0.1.1

type MysqlConfig struct {
	Dbname   string
	Database string
	Charset  string
	Username string
	User     string
	Password string
	Host     string
	Port     int
	// Connection pool settings
	MaxOpenConns    int `mapstructure:"max_open_conns"`
	MaxIdleConns    int `mapstructure:"max_idle_conns"`
	ConnMaxLifetime int `mapstructure:"conn_max_lifetime"` // in seconds
}

MysqlConfig holds MySQL connection configuration.

func (*MysqlConfig) Connection added in v0.1.3

func (mysqlConfig *MysqlConfig) Connection() (db *DB, err error)

Connection creates a MySQL database connection from this config.

func (*MysqlConfig) GetConnMaxLifetime added in v0.5.1

func (mysqlConfig *MysqlConfig) GetConnMaxLifetime() int

func (*MysqlConfig) GetMaxIdleConns added in v0.5.1

func (mysqlConfig *MysqlConfig) GetMaxIdleConns() int

func (*MysqlConfig) GetMaxOpenConns added in v0.5.1

func (mysqlConfig *MysqlConfig) GetMaxOpenConns() int

type PostgresConfig added in v0.5.1

type PostgresConfig struct {
	Host     string
	Port     int
	Username string
	User     string
	Password string
	Database string
	Dbname   string
	SSLMode  string // disable, require, verify-ca, verify-full

	// Connection pool settings
	MaxOpenConns    int `mapstructure:"max_open_conns"`
	MaxIdleConns    int `mapstructure:"max_idle_conns"`
	ConnMaxLifetime int `mapstructure:"conn_max_lifetime"` // in seconds
}

PostgresConfig holds PostgreSQL connection configuration

func (*PostgresConfig) Connection added in v0.5.1

func (c *PostgresConfig) Connection() (db *DB, err error)

Connection creates a new PostgreSQL database connection

func (*PostgresConfig) GetConnMaxLifetime added in v0.5.1

func (c *PostgresConfig) GetConnMaxLifetime() int

GetConnMaxLifetime implements ConnectionPoolConfig

func (*PostgresConfig) GetMaxIdleConns added in v0.5.1

func (c *PostgresConfig) GetMaxIdleConns() int

GetMaxIdleConns implements ConnectionPoolConfig

func (*PostgresConfig) GetMaxOpenConns added in v0.5.1

func (c *PostgresConfig) GetMaxOpenConns() int

GetMaxOpenConns implements ConnectionPoolConfig

type SQLiteConfig added in v0.1.2

type SQLiteConfig struct {
	FilePath string `mapstructure:"path"`
	// Connection pool settings
	MaxOpenConns    int `mapstructure:"max_open_conns"`
	MaxIdleConns    int `mapstructure:"max_idle_conns"`
	ConnMaxLifetime int `mapstructure:"conn_max_lifetime"` // in seconds
}

SQLiteConfig holds SQLite connection configuration.

func (*SQLiteConfig) Connection added in v0.1.3

func (sqliteConfig *SQLiteConfig) Connection() (db *DB, err error)

Connection creates a SQLite database connection from this config.

func (*SQLiteConfig) GetConnMaxLifetime added in v0.5.1

func (sqliteConfig *SQLiteConfig) GetConnMaxLifetime() int

func (*SQLiteConfig) GetMaxIdleConns added in v0.5.1

func (sqliteConfig *SQLiteConfig) GetMaxIdleConns() int

func (*SQLiteConfig) GetMaxOpenConns added in v0.5.1

func (sqliteConfig *SQLiteConfig) GetMaxOpenConns() int

type Session added in v0.1.3

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

Session wraps a GORM database session for direct operations.

func (*Session) Delete added in v0.1.3

func (s *Session) Delete(value any, conds ...any) error

Delete deletes records matching the given conditions.

type Source added in v0.1.3

type Source interface {
	Connection(cfg config.IConfig) (db *gorm.DB, err error)
}

Source defines the interface for database connection sources.

type Table added in v0.1.3

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

建议:不要直接使用 db.Table,推荐使用 model.EntryModel 或 model.Model, 它们提供了类型安全、更高层级的 CRUD 封装,代码更简洁且不易出错。

Recommendation: Prefer model.EntryModel or model.Model over raw db.Table. They provide type-safe, higher-level CRUD operations — less boilerplate and fewer mistakes.

推奨: 生の db.Table ではなく model.EntryModel または model.Model を使用してください。 型安全で抽象度の高い CRUD 操作が提供され、コードが簡潔になりミスも減ります。

권장: raw db.Table 대신 model.EntryModel 또는 model.Model 을 사용하세요. 타입 안전하고 더 높은 수준의 CRUD 연산을 제공하므로 코드가 간결해지고 실수가 줄어듭니다.

Рекомендация: используйте model.EntryModel или model.Model вместо прямого db.Table. Они предоставляют типобезопасные CRUD-операции высокого уровня — меньше шаблонного кода и ошибок.

func (*Table) AutoMigrate added in v0.1.3

func (t *Table) AutoMigrate(v ...any) error

AutoMigrate runs auto migration for the given models.

func (*Table) Count added in v0.1.3

func (t *Table) Count(i *int64) error

Count returns the number of matching records.

func (*Table) Create added in v0.1.3

func (t *Table) Create(value any) error

Create inserts a new record into the table.

func (*Table) CreateMapWithPk added in v0.1.4

func (t *Table) CreateMapWithPk(mapValue map[string]any, keyName string) (any, error)

CreateMapWithPk creates a record from a map and returns the generated primary key If keyName is empty, it will try common ID field names (ID, Id, id)

func (*Table) CreateMapWithUintPk added in v0.1.4

func (t *Table) CreateMapWithUintPk(mapValue map[string]any, keyName string) (uint, error)

CreateMapWithUintPk creates a record from a map and returns the primary key as uint

func (*Table) CreateWithPk added in v0.1.4

func (t *Table) CreateWithPk(value any, keyName string, kind reflect.Kind) (any, error)

CreateWithPk creates a record and returns the generated primary key If keyName is empty, it will try common ID field names (ID, Id, id) If kind is reflect.Invalid, it will try to determine the type automatically

func (*Table) Delete added in v0.1.3

func (t *Table) Delete(value any, conds ...any) error

Delete deletes records matching the conditions from the table.

func (*Table) Distinct added in v1.0.12

func (t *Table) Distinct(args ...any) *Table

func (*Table) Find added in v0.1.3

func (t *Table) Find(dest any, conds ...any) error

Find retrieves all matching records into dest.

func (*Table) First added in v0.1.3

func (t *Table) First(dest any, conds ...any) error

First retrieves the first matching record into dest.

func (*Table) Group added in v1.0.12

func (t *Table) Group(name string) *Table

func (*Table) Having added in v1.0.12

func (t *Table) Having(query any, args ...any) *Table

func (*Table) Joins added in v0.5.1

func (t *Table) Joins(query string, args ...any) *Table

Joins performs a join operation (GORM join support) Usage: db.Table("users").Joins("Profile").Find(&users)

func (*Table) Limit added in v0.1.3

func (t *Table) Limit(size int) *Table

Limit sets the maximum number of records to return.

func (*Table) Model added in v1.0.12

func (t *Table) Model(value any) *Table

Model sets the model struct on the underlying GORM chain, which is required for Preload to resolve associations correctly.

func (*Table) NewTable added in v0.1.4

func (t *Table) NewTable() *Table

NewTable creates a fresh Table instance with the original GORM connection.

func (*Table) Offset added in v0.1.3

func (t *Table) Offset(i int) *Table
func (t *Table) Set(column string, value any) *Table {
	tx := t.db.Set(column, value)
	return &Table{db: tx}
}

Offset sets the number of records to skip.

func (*Table) Order added in v0.1.3

func (t *Table) Order(query any) *Table

Order adds an ORDER BY clause.

func (*Table) Preload added in v0.5.1

func (t *Table) Preload(query string, args ...any) *Table

Preload preloads associations for the query (GORM foreign key support) Usage: db.Table("users").Preload("Profile").Preload("Role").Find(&users)

func (*Table) Raw added in v0.5.1

func (t *Table) Raw(sql string, args ...any) *Table

Raw executes a raw SQL query and returns a Table for further chaining (e.g., with Scan)

func (*Table) Save added in v0.1.3

func (t *Table) Save(entry any) error

Save creates or updates a record in the table.

func (*Table) Scan added in v0.5.1

func (t *Table) Scan(dest any) error

Scan scans query results into dest

func (*Table) Select added in v1.0.12

func (t *Table) Select(query any, args ...any) *Table

func (*Table) Session added in v0.1.3

func (t *Table) Session(g *gorm.Session) *Session

Session creates a GORM session with the given options.

func (*Table) UpdateColumn added in v0.1.3

func (t *Table) UpdateColumn(column string, value any) error

UpdateColumn updates a single column for matching records.

func (*Table) Updates added in v0.1.3

func (t *Table) Updates(values any) error

Updates applies the given values to matching records.

func (*Table) Where added in v0.1.3

func (t *Table) Where(query any, args ...any) *Table

Where adds a WHERE condition to the query chain.

func (*Table) WithContext added in v0.9.4

func (t *Table) WithContext(ctx context.Context) *Table

WithContext returns a new Table whose underlying *gorm.DB carries the given context. The original Table is unchanged; safe for concurrent use.

type ZeroTimePlugin added in v0.9.7

type ZeroTimePlugin struct{}

ZeroTimePlugin is a GORM plugin that automatically converts zero time.Time values to the current time before Create and Update operations. This prevents MySQL strict mode from rejecting '0000-00-00' datetime values.

func (*ZeroTimePlugin) Initialize added in v0.9.7

func (p *ZeroTimePlugin) Initialize(db *gorm.DB) error

Initialize registers the BeforeCreate and BeforeUpdate callbacks.

func (*ZeroTimePlugin) Name added in v0.9.7

func (p *ZeroTimePlugin) Name() string

Name returns the plugin name for GORM registration.

Jump to

Keyboard shortcuts

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