godb

package
v1.2.3 Latest Latest
Warning

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

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

README

go-db 数据操作

基于 https://github.com/go-gorm/gorm 的封装,更多用法到官方

目前已封装

  • mysql
  • sqlite3
  • clickhouse
func testSqlite3() {
    db, err := godb.InitSqlite3("./test.db", godb.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 := godb.InitMysql("root:223238@tcp(127.0.0.1:33060)/gromdb?charset=utf8mb4&parseTime=True&loc=Local", godb.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 := godb.InitMysql(dsn, godb.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

func GenerateSliceIn

func GenerateSliceIn[T any](srcItems []T) (string, []any)

func GenerateSliceInEx

func GenerateSliceInEx[T any](fieldName string, srcItems []T) (string, []any)

func WhereIntArray

func WhereIntArray[T int | int64 | int32](items []int64) string

func WhereStringArray

func WhereStringArray(items []string) string

Types

type GoDB

type GoDB struct {
	DB *gorm.DB
}

func InitClickHouse

func InitClickHouse(dataSource string, config GoDbConfig) (*GoDB, error)

初始化CLICKHOUSE

func InitMysql

func InitMysql(dataSource string, config GoDbConfig) (*GoDB, error)

初始化MySQL

func InitSqlite3

func InitSqlite3(dbFilePath string, config GoDbConfig) (*GoDB, error)

初始化sqlite3

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

func (*GoDB) AutoMigrate

func (s *GoDB) 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 (*GoDB) BeginTransaction added in v1.1.0

func (s *GoDB) BeginTransaction() *GoDB

事物开始

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) Commit added in v1.1.0

func (s *GoDB) Commit() error

提交事物

func (*GoDB) Create added in v1.1.1

func (s *GoDB) 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 (*GoDB) Delete

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

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

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

func (*GoDB) Exe1c

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

func (*GoDB) Exec

func (s *GoDB) 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 (*GoDB) Find

func (s *GoDB) 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 (*GoDB) FindOne

func (s *GoDB) 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 (*GoDB) First

func (s *GoDB) 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 (*GoDB) FirstOrCreate

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

func (*GoDB) Get

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

func (*GoDB) Init

func (s *GoDB) Init(config *GoDbConfig) error

func (*GoDB) InsertSpecified

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

特殊字段处理 Insert or Batch Insert

func (*GoDB) Last

func (s *GoDB) 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 (*GoDB) Model added in v1.1.1

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

func (*GoDB) Raw

func (s *GoDB) 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 (*GoDB) Rollback added in v1.1.0

func (s *GoDB) Rollback()

事物回滚

func (*GoDB) RollbackTo added in v1.1.0

func (s *GoDB) 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 (*GoDB) Save

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

func (*GoDB) SavePoint added in v1.1.0

func (s *GoDB) SavePoint(name string)

保存回滚点

func (*GoDB) Select added in v1.1.1

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

func (*GoDB) Session added in v1.1.1

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

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

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

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

func (*GoDB) Set

func (s *GoDB) 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 (*GoDB) Update

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

func (*GoDB) Updates

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

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

func (*GoDB) UpdatesByMap

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

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

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 NumberRangeController[T int64 | int | float64] struct {
	Min *T `json:"min,optional"`
	Max *T `json:"max,optional"`
}

func (*NumberRangeController[T]) Where

func (c *NumberRangeController[T]) Where(column string) (string, []any)

type OrderItem

type OrderItem struct {
	Column string `json:"column"`
	Asc    bool   `json:"asc"`
}

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 (p *Page) GroupByStr() string

func (*Page) OrderBy

func (p *Page) OrderBy() string

func (*Page) OrderByExt

func (p *Page) OrderByExt() string

func (*Page) PageLimit

func (p *Page) PageLimit() string

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)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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