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
- Variables
- func ApplyConnectionPool(db *gorm.DB, cfg ConnectionPoolConfig) error
- func RegisterDB(typeName string, dbConfig IConfig)
- type Config
- type ConnectionPoolConfig
- type DB
- func ConnectionMysql(host string, port int, username string, password string, dbname string, ...) (db *DB, err error)
- func ConnectionPostgres(host string, port int, username, password, database string, sslMode string) (db *DB, err error)
- func ConnectionSQLite(FilePath string) (db *DB, err error)
- func CreateDB(c config.IConfig) (*DB, error)
- type IConfig
- type MysqlConfig
- type PostgresConfig
- type SQLiteConfig
- type Session
- type Source
- type Table
- func (t *Table) AutoMigrate(v ...any) error
- func (t *Table) Count(i *int64) error
- func (t *Table) Create(value any) error
- func (t *Table) CreateMapWithPk(mapValue map[string]any, keyName string) (any, error)
- func (t *Table) CreateMapWithUintPk(mapValue map[string]any, keyName string) (uint, error)
- func (t *Table) CreateWithPk(value any, keyName string, kind reflect.Kind) (any, error)
- func (t *Table) Delete(value any, conds ...any) error
- func (t *Table) Distinct(args ...any) *Table
- func (t *Table) Find(dest any, conds ...any) error
- func (t *Table) First(dest any, conds ...any) error
- func (t *Table) Group(name string) *Table
- func (t *Table) Having(query any, args ...any) *Table
- func (t *Table) Joins(query string, args ...any) *Table
- func (t *Table) Limit(size int) *Table
- func (t *Table) Model(value any) *Table
- func (t *Table) NewTable() *Table
- func (t *Table) Offset(i int) *Table
- func (t *Table) Order(query any) *Table
- func (t *Table) Preload(query string, args ...any) *Table
- func (t *Table) Raw(sql string, args ...any) *Table
- func (t *Table) Save(entry any) error
- func (t *Table) Scan(dest any) error
- func (t *Table) Select(query any, args ...any) *Table
- func (t *Table) Session(g *gorm.Session) *Session
- func (t *Table) UpdateColumn(column string, value any) error
- func (t *Table) Updates(values any) error
- func (t *Table) Where(query any, args ...any) *Table
- func (t *Table) WithContext(ctx context.Context) *Table
- type ZeroTimePlugin
Constants ¶
const ( MYSQL = "mysql" POSTGRES = "postgres" POSTGRESQL = "postgresql" SQLITE = "sqlite" )
const ConfigKey = "web.db"
Variables ¶
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
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
ConnectionSQLite creates a new SQLite database connection.
func (*DB) Transaction ¶ added in v0.1.3
Transaction executes fc within a database transaction. The transaction is committed if fc returns nil, rolled back otherwise.
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.
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
AutoMigrate runs auto migration for the given models.
func (*Table) CreateMapWithPk ¶ added in v0.1.4
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
CreateMapWithUintPk creates a record from a map and returns the primary key as uint
func (*Table) CreateWithPk ¶ added in v0.1.4
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
Delete deletes records matching the conditions from the table.
func (*Table) Joins ¶ added in v0.5.1
Joins performs a join operation (GORM join support) Usage: db.Table("users").Joins("Profile").Find(&users)
func (*Table) Model ¶ added in v1.0.12
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
NewTable creates a fresh Table instance with the original GORM connection.
func (*Table) Offset ¶ added in v0.1.3
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) Preload ¶ added in v0.5.1
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
Raw executes a raw SQL query and returns a Table for further chaining (e.g., with Scan)
func (*Table) UpdateColumn ¶ added in v0.1.3
UpdateColumn updates a single column for matching records.
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.