gogorm

package
v1.2.48 Latest Latest
Warning

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

Go to latest
Published: Aug 16, 2024 License: Apache-2.0 Imports: 8 Imported by: 0

README

go-db 数据操作

目前已封装

  • mysql
  • sqlite3
  • clickhouse
  • postgresql
  • sqlserver
  • tidb
func testSqlite3() {
    db, err := gogorm.InitSqlite3("./test.db", gogorm.GoDbConfig{
        MaxOpen:      100,
        MaxIdleCount: 10,
    })
    if err != nil {
        golog.WithTag("godb").Error(err.Error())
        return
    }
    err = db.AutoMigrate(&Product{})
    if err != nil {
        golog.WithTag("godb").Error(err.Error())
        return
    }
    
    // Create
    insertProduct := &Product{Code: "D42", Price: 100}
    db.Insert(insertProduct)
    fmt.Println(insertProduct.ID)
    // Read
    var product Product
    tx := db.First(&product, 1) // find product with integer primary key
    if tx.Error != nil {
    fmt.Println("not found first ", tx.Error.Error())
    }
    db.First(&product, "code = ?", "D42")
    // Delete - delete product
    db.Delete(&product, 1)
    
    err = goutils.RemoveFile("./test.db")
    if err != nil {
        golog.WithTag("godb").Error(err.Error())
    }
}
func mysqlTest() {
	db, err := gogorm.InitMysql("root:223238@tcp(127.0.0.1:33060)/gromdb?charset=utf8mb4&parseTime=True&loc=Local", gogorm.GoDbConfig{})
	if err != nil {
		golog.WithTag("godb").Error(err.Error())
		return
	}
	err = db.AutoMigrate(&Product{})
	if err != nil {
		golog.WithTag("godb").Error(err.Error())
		return
	}

	// Create
	insertProduct := &Product{Code: "D42", Price: 100}
	db.Insert(insertProduct)
	fmt.Println(insertProduct.ID)
	// Read
	var product Product
	tx := db.First(&product, 1) // find product with integer primary key
	if tx.Error != nil {
		fmt.Println("not found first ", tx.Error.Error())
	}
	db.First(&product, "code = ?", "D42")
	// Delete - delete product
	db.Delete(&product, 1)

}
func testClickhouse() {
	dsn := "tcp://localhost:9000?database=gorm&username=gorm&password=gorm&read_timeout=10&write_timeout=20"
	db, err := gogorm.InitMysql(dsn, gogorm.GoDbConfig{})
	if err != nil {
		golog.WithTag("godb").Error(err.Error())
		return
	}
	err = db.Set("gorm:table_options", "ENGINE=Distributed(cluster, default, hits)").AutoMigrate(&Product{})
	if err != nil {
		golog.WithTag("godb").Error(err.Error())
		return
	}
	// Set table options

	// Create
	insertProduct := &Product{Code: "D42", Price: 100}
	db.Insert(insertProduct)
	fmt.Println(insertProduct.ID)
	// Read
	var product Product
	tx := db.First(&product, 1) // find product with integer primary key
	if tx.Error != nil {
		fmt.Println("not found first ", tx.Error.Error())
	}
	db.First(&product, "code = ?", "D42")
	// Delete - delete product
	db.Delete(&product, 1)
}
mongodb 不是关系性数据库 暂时不支持

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type GormDB

type GormDB struct {
	DB *gorm.DB
}

func InitClickHouse

func InitClickHouse(dataSource string, config GormDbConfig) (*GormDB, error)

初始化CLICKHOUSE

func InitMysql

func InitMysql(dataSource string, config GormDbConfig) (*GormDB, error)

初始化MySQL OR TiDB(TiDB is compatible with MySQL protocol.)

func InitPostgreSql added in v1.2.23

func InitPostgreSql(dsn string, config GormDbConfig) (*GormDB, error)

初始化 dsn := "host=localhost user=gorm password=gorm dbname=gorm port=9920 sslmode=disable TimeZone=Asia/Shanghai"

func InitSqlServer added in v1.2.23

func InitSqlServer(dsn string, config GormDbConfig) (*GormDB, error)

初始化 dsn := "sqlserver://gorm:LoremIpsum86@localhost:9930?database=gorm"

func InitSqlite3

func InitSqlite3(dbFilePath string, config GormDbConfig) (*GormDB, error)

初始化sqlite3

Example: dbFilePath : /user/db/sqlite3.db

func (*GormDB) AutoMigrate

func (s *GormDB) AutoMigrate(values ...interface{}) error

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 (*GormDB) BeginTransaction

func (s *GormDB) BeginTransaction() *GormDB

事物开始

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 (*GormDB) Commit

func (s *GormDB) Commit() error

提交事物

func (*GormDB) Create

func (s *GormDB) Create(value interface{}) (tx *gorm.DB)

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 (*GormDB) Delete

func (s *GormDB) Delete(value interface{}, conds ...interface{}) (tx *gorm.DB)

如果你的模型包含了 gorm.DeletedAt字段(该字段也被包含在gorm.Model中),那么该模型将会自动获得软删除的能力!

当调用Delete时,GORM并不会从数据库中删除该记录,而是将该记录的DeleteAt设置为当前时间,而后的一般查询方法将无法查找到此条记录。

func (*GormDB) Exe1c

func (s *GormDB) Exe1c(table string, dest interface{}, where string, args ...interface{}) (tx *gorm.DB)

func (*GormDB) Exec

func (s *GormDB) Exec(sql string, values ...interface{}) (tx *gorm.DB)

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 (*GormDB) Find

func (s *GormDB) Find(value interface{}, conds ...interface{}) (tx *gorm.DB)
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 (*GormDB) FindOne

func (s *GormDB) FindOne(value interface{}, conds ...interface{}) (tx *gorm.DB)

Get one record, no specified order SELECT * FROM users LIMIT 1;

check error ErrRecordNotFound

errors.Is(result.Error, gorm.ErrRecordNotFound)

func (*GormDB) First

func (s *GormDB) First(value interface{}, conds ...interface{}) (tx *gorm.DB)

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 (*GormDB) FirstOrCreate

func (s *GormDB) FirstOrCreate(value interface{}, conds ...interface{}) (tx *gorm.DB)

func (*GormDB) Get

func (s *GormDB) Get(key string) (interface{}, bool)

func (*GormDB) Init

func (s *GormDB) Init(config *GormDbConfig) error

func (*GormDB) InsertSpecified

func (s *GormDB) InsertSpecified(fields []string, exclude bool, value interface{}) (tx *gorm.DB)

特殊字段处理 Insert or Batch Insert

func (*GormDB) Last

func (s *GormDB) Last(value interface{}, conds ...interface{}) (tx *gorm.DB)

Get last record, ordered by primary key desc

SELECT * FROM users ORDER BY id DESC LIMIT 1;

func (*GormDB) Model

func (s *GormDB) Model(value interface{}) *gorm.DB

func (*GormDB) Raw

func (s *GormDB) Raw(sql string, dest interface{}, values ...interface{}) (tx *gorm.DB)
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 (*GormDB) Rollback

func (s *GormDB) Rollback()

事物回滚

func (*GormDB) RollbackTo

func (s *GormDB) RollbackTo(name string)

事物回滚到name的点击

tx := db.Begin() tx.Create(&user1)

tx.SavePoint("sp1") tx.Create(&user2) tx.RollbackTo("sp1") // Rollback user2

tx.Commit() // Commit user1

func (*GormDB) Save

func (s *GormDB) Save(value interface{}) (tx *gorm.DB)

func (*GormDB) SavePoint

func (s *GormDB) SavePoint(name string)

保存回滚点

func (*GormDB) Select

func (s *GormDB) Select(value interface{}, conds ...interface{}) (tx *gorm.DB)

func (*GormDB) Session

func (s *GormDB) Session(config *gorm.Session) *gorm.DB

更新用户并完全更新其所有关联

db.Session(&gorm.Session{FullSaveAssociations: true}).Updates(&user)

SQL:完全更新地址、用户、电子邮件表,包括现有的关联记录

func (*GormDB) Set

func (s *GormDB) Set(key string, value interface{}) (tx *gorm.DB)

clickhouse Set table options after AutoMigrate

db.Set("gorm:table_options", "ENGINE=Distributed(cluster, default, hits)").AutoMigrate(&User{})

func (*GormDB) Update

func (s *GormDB) Update(model interface{}, column string, value interface{}) (tx *gorm.DB)

func (*GormDB) Updates

func (s *GormDB) Updates(model interface{}, value interface{}) (tx *gorm.DB)

db.Model(&product).Updates(Product{Price: 200, Code: "F42"}) // non-zero fields

func (*GormDB) UpdatesByMap

func (s *GormDB) UpdatesByMap(model interface{}, value map[string]interface{}) (tx *gorm.DB)

db.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"})

type GormDbConfig

type GormDbConfig 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
}

数据初始化属性这里扩展

Jump to

Keyboard shortcuts

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