Documentation ¶
Index ¶
- func GenerateSliceIn[T any](srcItems []T) (string, []any)
- func GenerateSliceInEx[T any](fieldName string, srcItems []T) (string, []any)
- func WhereIntArray[T int | int64 | int32](items []int64) string
- func WhereStringArray(items []string) string
- type GoDB
- func (s *GoDB) AutoMigrate(values ...interface{}) error
- func (s *GoDB) BeginTransaction() *GoDB
- func (s *GoDB) Commit() error
- func (s *GoDB) Create(value interface{}) (tx *gorm.DB)
- func (s *GoDB) Delete(value interface{}, conds ...interface{}) (tx *gorm.DB)
- func (s *GoDB) Exe1c(table string, dest interface{}, where string, args ...interface{}) (tx *gorm.DB)
- func (s *GoDB) Exec(sql string, values ...interface{}) (tx *gorm.DB)
- func (s *GoDB) Find(value interface{}, conds ...interface{}) (tx *gorm.DB)
- func (s *GoDB) FindOne(value interface{}, conds ...interface{}) (tx *gorm.DB)
- func (s *GoDB) First(value interface{}, conds ...interface{}) (tx *gorm.DB)
- func (s *GoDB) FirstOrCreate(value interface{}, conds ...interface{}) (tx *gorm.DB)
- func (s *GoDB) Get(key string) (interface{}, bool)
- func (s *GoDB) Init(config *GoDbConfig) error
- func (s *GoDB) InsertSpecified(fields []string, exclude bool, value interface{}) (tx *gorm.DB)
- func (s *GoDB) Last(value interface{}, conds ...interface{}) (tx *gorm.DB)
- func (s *GoDB) Model(value interface{}) *gorm.DB
- func (s *GoDB) Raw(sql string, dest interface{}, values ...interface{}) (tx *gorm.DB)
- func (s *GoDB) Rollback()
- func (s *GoDB) RollbackTo(name string)
- func (s *GoDB) Save(value interface{}) (tx *gorm.DB)
- func (s *GoDB) SavePoint(name string)
- func (s *GoDB) Select(value interface{}, conds ...interface{}) (tx *gorm.DB)
- func (s *GoDB) Session(config *gorm.Session) *gorm.DB
- func (s *GoDB) Set(key string, value interface{}) (tx *gorm.DB)
- func (s *GoDB) Update(model interface{}, column string, value interface{}) (tx *gorm.DB)
- func (s *GoDB) Updates(model interface{}, value interface{}) (tx *gorm.DB)
- func (s *GoDB) UpdatesByMap(model interface{}, value map[string]interface{}) (tx *gorm.DB)
- type GoDbConfig
- type NumberRangeController
- type OrderItem
- type Page
- type SelectController
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GenerateSliceIn ¶
func GenerateSliceInEx ¶
func WhereStringArray ¶
Types ¶
type GoDB ¶
func InitClickHouse ¶
func InitClickHouse(dataSource string, config GoDbConfig) (*GoDB, error)
初始化CLICKHOUSE
func InitSqlite3 ¶
func InitSqlite3(dbFilePath string, config GoDbConfig) (*GoDB, error)
初始化sqlite3
Example: dbFilePath : /user/db/sqlite3.db
func (*GoDB) AutoMigrate ¶
package main
import (
"gorm.io/gorm" "gorm.io/driver/sqlite"
)
type Product struct { gorm.Model Code string Price uint } func main() { db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) if err != nil { panic("failed to connect database") } // 迁移 schema db.AutoMigrate(&Product{}) // Create db.Create(&Product{Code: "D42", Price: 100}) // Read var product Product db.First(&product, 1) // 根据整型主键查找 db.First(&product, "code = ?", "D42") // 查找 code 字段值为 D42 的记录 // Update - 将 product 的 price 更新为 200 db.Model(&product).Update("Price", 200) // Update - 更新多个字段 db.Model(&product).Updates(Product{Price: 200, Code: "F42"}) // 仅更新非零值字段 db.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"}) // Delete - 删除 product db.Delete(&product, 1) }
db.AutoMigrate(&User{})
db.AutoMigrate(&User{}, &Product{}, &Order{})
// Add table suffix when creating tables db.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(&User{})
func (*GoDB) BeginTransaction ¶ added in v1.1.0
事物开始
func CreateAnimals(db *gorm.DB) error { // 再唠叨一下,事务一旦开始,你就应该使用 tx 处理数据 tx := db.Begin() defer func() { if r := recover(); r != nil { tx.Rollback() } }() if err := tx.Error; err != nil { return err } if err := tx.Create(&Animal{Name: "Giraffe"}).Error; err != nil { tx.Rollback() return err } if err := tx.Create(&Animal{Name: "Lion"}).Error; err != nil { tx.Rollback() return err } return tx.Commit().Error }
func (*GoDB) Create ¶ added in v1.1.1
Insert or Batch Insert
user := User{Name: "Jinzhu", Age: 18, Birthday: time.Now()}
users := []*User{ {Name: "Jinzhu", Age: 18, Birthday: time.Now()}, {Name: "Jackson", Age: 19, Birthday: time.Now()}, }
result := db.Create(&user) pass pointer of data to Create
user.ID returns inserted data's primary key
result.Error returns error
result.RowsAffected returns inserted records count
Create Hooks
func (u *User) BeforeCreate(tx *gorm.DB) (err error) { u.UUID = uuid.New() if u.Role == "admin" { return errors.New("invalid role") } return }
Default Values
type User struct { ID int64 Name string `gorm:"default:galeone"` Age int64 `gorm:"default:18"` }
func (*GoDB) Delete ¶
如果你的模型包含了 gorm.DeletedAt字段(该字段也被包含在gorm.Model中),那么该模型将会自动获得软删除的能力!
当调用Delete时,GORM并不会从数据库中删除该记录,而是将该记录的DeleteAt设置为当前时间,而后的一般查询方法将无法查找到此条记录。
func (*GoDB) Exec ¶
db.Exec("DROP TABLE users") db.Exec("UPDATE orders SET shipped_at = ? WHERE id IN ?", time.Now(), []int64{1, 2, 3})
// Exec with SQL Expression db.Exec("UPDATE users SET money = ? WHERE name = ?", gorm.Expr("money * ? + ?", 10000, 1), "jinzhu")
func (*GoDB) Find ¶
func (u *User) AfterFind(tx *gorm.DB) (err error) { // Custom logic after finding a user if u.Role == "" { u.Role = "user" // Set default role if not specified } return }
func (*GoDB) FindOne ¶
Get one record, no specified order SELECT * FROM users LIMIT 1;
check error ErrRecordNotFound
errors.Is(result.Error, gorm.ErrRecordNotFound)
func (*GoDB) First ¶
Get the first record ordered by primary key SELECT * FROM users ORDER BY id LIMIT 1;
var product Product db.First(&product, 1) // find product with integer primary key db.First(&product, "code = ?", "D42") // find product with code D42
func (*GoDB) FirstOrCreate ¶
func (*GoDB) Init ¶
func (s *GoDB) Init(config *GoDbConfig) error
func (*GoDB) InsertSpecified ¶
特殊字段处理 Insert or Batch Insert
func (*GoDB) Last ¶
Get last record, ordered by primary key desc
SELECT * FROM users ORDER BY id DESC LIMIT 1;
func (*GoDB) Raw ¶
type Result struct { ID int Name string Age int }
var result Result db.Raw("SELECT id, name, age FROM users WHERE id = ?", 3).Scan(&result)
db.Raw("SELECT id, name, age FROM users WHERE name = ?", "jinzhu").Scan(&result)
var age int db.Raw("SELECT SUM(age) FROM users WHERE role = ?", "admin").Scan(&age)
var users []User db.Raw("UPDATE users SET name = ? WHERE age = ? RETURNING id, name", "jinzhu", 20).Scan(&users)
func (*GoDB) RollbackTo ¶ added in v1.1.0
事物回滚到name的点击
tx := db.Begin() tx.Create(&user1)
tx.SavePoint("sp1") tx.Create(&user2) tx.RollbackTo("sp1") // Rollback user2
tx.Commit() // Commit user1
func (*GoDB) Session ¶ added in v1.1.1
更新用户并完全更新其所有关联
db.Session(&gorm.Session{FullSaveAssociations: true}).Updates(&user)
SQL:完全更新地址、用户、电子邮件表,包括现有的关联记录
func (*GoDB) Set ¶
clickhouse Set table options after AutoMigrate
db.Set("gorm:table_options", "ENGINE=Distributed(cluster, default, hits)").AutoMigrate(&User{})
type GoDbConfig ¶
type GoDbConfig struct { //AutoPing bool Config *gorm.Config MaxIdleCount int // zero means defaultMaxIdleConns; negative means 0 MaxOpen int // <= 0 means unlimited MaxLifetime time.Duration // maximum amount of time a connection may be reused }
数据初始化属性这里扩展
type NumberRangeController ¶
type Page ¶
type Page struct { PageNo int64 `json:"page_no,optional"` PageSize int64 `json:"page_size,optional"` StartTime int64 `json:"start_time,optional"` EndTime int64 `json:"end_time,optional"` SortBy []*OrderItem `json:"sort_by,optional"` GroupBy []string `json:"group_by,optional"` IgnoreTotal bool `json:"ignore_total,optional"` OnlyTotal bool `json:"only_total,optional"` Ids []int64 `json:"ids,optional"` States []int64 `json:"ids,optional"` }
func (*Page) GroupByStr ¶
func (*Page) OrderByExt ¶
type SelectController ¶
type SelectController[T int64 | string] struct { Values []T `json:"values,optional"` Exclude bool `json:"exclude,optional"` }
func (*SelectController[T]) ClickHouseWhere ¶
func (c *SelectController[T]) ClickHouseWhere(column string) (string, []T)
func (*SelectController[T]) MysqlWhere ¶
func (c *SelectController[T]) MysqlWhere(column string) (string, []any)