lgorm

package module
v0.0.0-...-c5b56c5 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2022 License: MIT Imports: 8 Imported by: 0

README

lgorm

将gorm封装了一层,可以实现getAttr和setAttr

gorm地址 https://github.com/go-gorm/gorm

用法

可以完全按照gorm的方法去实现功能(模型都用&符号才能完全兼容AfterFind,BeforeSave,BeforeCreate等钩子)

优化了链式调用时,需要重新赋值,如:db = db.Where("id = ?", id),避免多次调用时的冲突

Get{structFieldName}Attr可以在获取数据时处理输出的数据

Set{structFieldName}Attr可以在添加和修改的时候处理添加的数据

两个方法传入的参数类型和返回类型都应该是结构体field的类型

可调用原本的gorm方法

调用方式为实例化对象调用DB

例如:

db.Find(&model.bank)调用处理attr后的方法

db.DB.Find(&model.bank)则调用gorm原来的方法

已修改的方法

  1. Transaction方法参数的匿名方法fc的参数从gorm.DB改为lgorm.Db
  2. FindInBatches方法参数的匿名方法fc的参数从gorm.DB改为lgorm.Db,且如果未设置主键修改为offiset查询

用法实例

package main

import (
	"github.com/goodluckxu/lgorm"
)

func main() {
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second, // 慢 SQL 阈值
			LogLevel:      logger.Info, // Log level
			Colorful:      false,       // 禁用彩色打印
		},
	)
	db, err := lgorm.Open(mysql.Open("root:root@tcp(127.0.0.1:3306)/backend_api?charset=utf8mb4&parseTime=True&loc=Local"), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
		Logger: newLogger,
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	var bank model.Bank
	db.Model(&bank).Where("id = 80").Update("name", "aaa")
	db.First(&bank)
	fmt.Println(bank)
}
package model

import (
	"time"
)

type Bank struct {
	Id           int       `json:"id"`
	Name         string    `json:"name"`
	ShortName    string    `json:"short_name"`
	EnglishName  string    `json:"english_name"`
	EnglishAbbr  string    `json:"english_abbr"`
	Remark       string    `json:"remark"`
	OptionStatus int       `json:"option_status"`
	Sort         int       `json:"sort"`
	CreatedAt    time.Time `json:"created_at"`
	UpdatedAt    time.Time `json:"updated_at"`
}

func (b Bank) GetRemarkAttr(value string) string {
	return value + "abc"
}

func (b Bank) GetCreatedAtAttr(value time.Time) time.Time {
	return time.Now()
}

func (b Bank) SetNameAttr(value string) string {
	return value + "_abc"
}

控制台输出:

2021/05/12 09:03:08 C:/Users/luckyxu/sdk/go1.16.3/src/reflect/value.go:476
[10.841ms] [rows:1] UPDATE `bank` SET `name`='aaa_abc',`updated_at`='2021-05-12 09:03:08.748' WHERE id = 80

2021/05/12 09:03:08 C:/Users/luckyxu/sdk/go1.16.3/src/reflect/value.go:476
[0.503ms] [rows:1] SELECT * FROM `bank` ORDER BY `bank`.`id` LIMIT 1
{63 测试添加 测试 你好 hello 描述abc 0 0 2021-05-12 09:03:08.7611426 +0800 CST m=+0.021322101 2021-05-11 09:49:16 +0800 CST}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ChainAblePool

type ChainAblePool struct {
	IsCall bool
	Params []interface{}
}

type ConnPool

type ConnPool struct {
	Dialector gorm.Dialector
	Opts      []gorm.Option
	Err       error
}

type Db

type Db struct {
	*gorm.DB
	Statement Statement
	ConnPool  ConnPool
	// contains filtered or unexported fields
}

func Open

func Open(dialector gorm.Dialector, opts ...gorm.Option) (*Db, error)

func (*Db) Assign

func (db *Db) Assign(attrs ...interface{}) (tx *Db)

func (*Db) Attrs

func (db *Db) Attrs(attrs ...interface{}) (tx *Db)

func (*Db) Begin

func (db *Db) Begin(opts ...*sql.TxOptions) (tx *Db)

Begin begins a transaction

func (*Db) Clauses

func (db *Db) Clauses(conds ...clause.Expression) (tx *Db)

Clauses Add clauses

func (*Db) Commit

func (db *Db) Commit() (tx *Db)

Commit commit a transaction

func (*Db) Count

func (db *Db) Count(count *int64) (tx *Db)

func (*Db) Create

func (db *Db) Create(value interface{}) (tx *Db)

Create insert the value into database

func (*Db) CreateInBatches

func (db *Db) CreateInBatches(value interface{}, batchSize int) (tx *Db)

CreateInBatches insert the value in batches into database

func (*Db) Delete

func (db *Db) Delete(value interface{}, conds ...interface{}) (tx *Db)

Delete delete value match given conditions, if the value has primary key, then will including the primary key as condition

func (*Db) Distinct

func (db *Db) Distinct(args ...interface{}) (tx *Db)

Distinct specify distinct fields that you want querying

func (*Db) Exec

func (db *Db) Exec(sql string, values ...interface{}) (tx *Db)

Exec execute raw sql

func (*Db) Find

func (db *Db) Find(dest interface{}, conds ...interface{}) (tx *Db)

Find find records that match given conditions

func (*Db) FindInBatches

func (db *Db) FindInBatches(dest interface{}, batchSize int, fc func(tx *Db, batch int) error) *Db

FindInBatches find records in batches

func (*Db) First

func (db *Db) First(dest interface{}, conds ...interface{}) (tx *Db)

First find first record that match given conditions, order by primary key

func (*Db) FirstOrCreate

func (db *Db) FirstOrCreate(dest interface{}, conds ...interface{}) (tx *Db)

func (*Db) FirstOrInit

func (db *Db) FirstOrInit(dest interface{}, conds ...interface{}) (tx *Db)

func (*Db) Group

func (db *Db) Group(name string) (tx *Db)

Group specify the group method on the find

func (*Db) Having

func (db *Db) Having(query interface{}, args ...interface{}) (tx *Db)

Having specify HAVING conditions for GROUP BY

func (*Db) Joins

func (db *Db) Joins(query string, args ...interface{}) (tx *Db)

Joins specify Joins conditions

db.Joins("Account").Find(&user)
db.Joins("JOIN emails ON emails.user_id = users.id AND emails.email = ?", "jinzhu@example.org").Find(&user)

func (*Db) Last

func (db *Db) Last(dest interface{}, conds ...interface{}) (tx *Db)

Last find last record that match given conditions, order by primary key

func (*Db) Limit

func (db *Db) Limit(limit int) (tx *Db)

Limit specify the number of records to be retrieved

func (*Db) Model

func (db *Db) Model(value interface{}) (tx *Db)

Model specify the model you would like to run db operations

// update all users's name to `hello`
db.Model(&User{}).Update("name", "hello")
// if user's primary key is non-blank, will use it as condition, then will only update the user's name to `hello`
db.Model(&user).Update("name", "hello")

func (*Db) Not

func (db *Db) Not(query interface{}, args ...interface{}) (tx *Db)

Not add NOT conditions

func (*Db) Offset

func (db *Db) Offset(offset int) (tx *Db)

Offset specify the number of records to skip before starting to return the records

func (*Db) Omit

func (db *Db) Omit(columns ...string) (tx *Db)

Omit specify fields that you want to ignore when creating, updating and querying

func (*Db) Or

func (db *Db) Or(query interface{}, args ...interface{}) (tx *Db)

Or add OR conditions

func (*Db) Order

func (db *Db) Order(value interface{}) (tx *Db)

Order specify order when retrieve records from database

db.Order("name DESC")
db.Order(clause.OrderByColumn{Column: clause.Column{Name: "name"}, Desc: true})

func (*Db) Pluck

func (db *Db) Pluck(column string, dest interface{}) (tx *Db)

Pluck used to query single column from a model as a map

var ages []int64
db.Find(&users).Pluck("age", &ages)

func (*Db) Preload

func (db *Db) Preload(query string, args ...interface{}) (tx *Db)

Preload preload associations with given conditions

db.Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users)

func (*Db) Raw

func (db *Db) Raw(sql string, values ...interface{}) (tx *Db)

func (*Db) Rollback

func (db *Db) Rollback() (tx *Db)

Rollback rollback a transaction

func (*Db) RollbackTo

func (db *Db) RollbackTo(name string) (tx *Db)

func (*Db) Row

func (db *Db) Row() *sql.Row

func (*Db) Rows

func (db *Db) Rows() (*sql.Rows, error)

func (*Db) RunFinisher

func (db *Db) RunFinisher()

func (*Db) Save

func (db *Db) Save(value interface{}) (tx *Db)

Save update value in database, if the value doesn't have primary key, will insert it

func (*Db) SavePoint

func (db *Db) SavePoint(name string) (tx *Db)

func (*Db) Scan

func (db *Db) Scan(dest interface{}) (tx *Db)

Scan scan value to a struct

func (*Db) ScanRows

func (db *Db) ScanRows(rows *sql.Rows, dest interface{}) error

func (*Db) Scopes

func (db *Db) Scopes(funcs ...func(*Db) *Db) (tx *Db)

Scopes pass current database connection to arguments `func(Db) Db`, which could be used to add conditions dynamically

func AmountGreaterThan1000(db *gorm.Db) *gorm.Db {
    return db.Where("amount > ?", 1000)
}

func OrderStatus(status []string) func (db *gorm.Db) *gorm.Db {
    return func (db *gorm.Db) *gorm.Db {
        return db.Scopes(AmountGreaterThan1000).Where("status in (?)", status)
    }
}

db.Scopes(AmountGreaterThan1000, OrderStatus([]string{"paid", "shipped"})).Find(&orders)

func (*Db) Select

func (db *Db) Select(query interface{}, args ...interface{}) (tx *Db)

Select specify fields that you want when querying, creating, updating

func (*Db) Table

func (db *Db) Table(name string, args ...interface{}) (tx *Db)

Table specify the table you would like to run db operations

func (*Db) Take

func (db *Db) Take(dest interface{}, conds ...interface{}) (tx *Db)

Take return a record that match given conditions, the order will depend on the database implementation

func (*Db) Transaction

func (db *Db) Transaction(fc func(tx *Db) error, opts ...*sql.TxOptions) (err error)

Transaction start a transaction as a block, return error will rollback, otherwise to commit.

func (*Db) Unscoped

func (db *Db) Unscoped() (tx *Db)

func (*Db) Update

func (db *Db) Update(column string, value interface{}) (tx *Db)

Update update attributes with callbacks, refer: https://gorm.io/docs/update.html#Update-Changed-Fields

func (*Db) UpdateColumn

func (db *Db) UpdateColumn(column string, value interface{}) (tx *Db)

func (*Db) UpdateColumns

func (db *Db) UpdateColumns(values interface{}) (tx *Db)

func (*Db) Updates

func (db *Db) Updates(values interface{}) (tx *Db)

Updates update attributes with callbacks, refer: https://gorm.io/docs/update.html#Update-Changed-Fields

func (*Db) Where

func (db *Db) Where(query interface{}, args ...interface{}) (tx *Db)

Where add conditions

type FinisherPool

type FinisherPool struct {
	IsCall            bool
	Params            []interface{}
	HandleType        string
	HandleParamsIndex []int
}

type Statement

type Statement struct {
	Table           ChainAblePool
	Model           ChainAblePool
	Clauses         []ChainAblePool
	Select          []ChainAblePool
	Distinct        []ChainAblePool
	Omit            []ChainAblePool
	Where           []ChainAblePool
	Not             []ChainAblePool
	Or              []ChainAblePool
	Joins           []ChainAblePool
	Group           []ChainAblePool
	Having          []ChainAblePool
	Order           []ChainAblePool
	Limit           ChainAblePool
	Offset          ChainAblePool
	Scopes          []ChainAblePool
	Preload         []ChainAblePool
	Attrs           []ChainAblePool
	Assign          []ChainAblePool
	Unscoped        ChainAblePool
	Raw             []ChainAblePool
	Create          []FinisherPool
	CreateInBatches []FinisherPool
	Save            []FinisherPool
	First           []FinisherPool
	Take            []FinisherPool
	Last            []FinisherPool
	Find            []FinisherPool
	FirstOrInit     []FinisherPool
	FirstOrCreate   []FinisherPool
	Update          []FinisherPool
	Updates         []FinisherPool
	UpdateColumn    []FinisherPool
	UpdateColumns   []FinisherPool
	Delete          []FinisherPool
	Count           []FinisherPool
	Row             FinisherPool
	Rows            FinisherPool
	Scan            []FinisherPool
	Pluck           []FinisherPool
	ScanRows        FinisherPool
	Begin           []FinisherPool
	Commit          []FinisherPool
	Rollback        []FinisherPool
	SavePoint       []FinisherPool
	RollbackTo      []FinisherPool
	Exec            []FinisherPool
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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