gorm

package
v0.0.0-...-278a4e6 Latest Latest
Warning

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

Go to latest
Published: Jul 27, 2022 License: Apache-2.0 Imports: 9 Imported by: 5

README

Mysql

基本信息

  • Autowire 类型:normal

  • SDID:Mysql-Impl

  • 参数来源:定制化参数加载方式

    ​ 标签 + 配置文件。需要同时设定好注入标签与配置文件。

参数说明:

type Config struct {
	Host         string `yaml:"host"` // 数据库地址:从配置文件读入
	Port         string `yaml:"port"` // 端口号:从配置文件读入
	Username     string `yaml:"username"` // 用户名:从配置文件读入
	Password     string `yaml:"password"` // 密码:从配置文件读入
	DBName       string `yaml:"dbname"` // db 名:从配置文件读入
	TableName    string // 表名:从标签读入
}

注入示例

通过依赖注入

标签

// +ioc:autowire=true
// +ioc:autowire:type=singleton

type App struct {
	MyDataTable normalMysql.Mysql `normal:"Impl,my-mysql,mydata"` // Impl,配置key,表明
}

配置

autowire:
  normal:
    github.com/alibaba/ioc-golang/extension/db/gorm.GORMDB:
        param:
          my-mysql:
            host: "127.0.0.1"
            port: 3306
            username: "root"
            password: "root"
            dbname: "test"

标签中 Impl 为固定值。mysql 为

可获取到参数:

type Config struct {
	Host         string // 127.0.0.1
	Port         string // 3306
	Username     string // root
	Password     string // root
	DBName       string // test
	TableName    string // mydata
}
通过 API 获取
import (
  normalMysql "github.com/alibaba/ioc-golang/extension/db/gorm"
)


mysqlImpl, err := normalMysql.GetMysql(&normalMysql.Config{
		Host: "127.0.0.1",
		Port: "3306",
		...
})
if err != nil{
  panic(err)
}

方法说明

type Mysql interface {
	GetDB() *gorm.DB // 获取 gorm 数据库连接
  
  // 包装 API 
	SelectWhere(queryStr string, result interface{}, args ...interface{}) error
	Insert(toInsertLines UserDefinedModel) error
	Delete(toDeleteTarget UserDefinedModel) error
	First(queryStr string, findTarget UserDefinedModel, args ...interface{}) error
	Update(queryStr, field string, target interface{}, args ...interface{}) error
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type GORMDB

type GORMDB struct {
	// contains filtered or unexported fields
}

func GetGORMDB

func GetGORMDB(p *Param) (*GORMDB, error)

func GetGORMDBSingleton

func GetGORMDBSingleton(p *Param) (*GORMDB, error)

func (*GORMDB) AddError

func (db *GORMDB) AddError(err error) error

AddError add error to db

func (*GORMDB) Assign

func (db *GORMDB) Assign(attrs ...interface{}) GORMDBIOCInterface

func (*GORMDB) Association

func (db *GORMDB) Association(column string) *gorm.Association

func (*GORMDB) Attrs

func (db *GORMDB) Attrs(attrs ...interface{}) GORMDBIOCInterface

func (*GORMDB) AutoMigrate

func (db *GORMDB) AutoMigrate(dst ...interface{}) error

func (*GORMDB) Begin

func (db *GORMDB) Begin(opts ...*sql.TxOptions) GORMDBIOCInterface

Begin begins a transaction

func (*GORMDB) Clauses

func (db *GORMDB) Clauses(conds ...clause.Expression) GORMDBIOCInterface

Clauses Add clauses

func (*GORMDB) Commit

func (db *GORMDB) Commit() GORMDBIOCInterface

Commit commit a transaction

func (*GORMDB) Connection

func (db *GORMDB) Connection(fc func(db *gorm.DB) error) (err error)

Connection use a db conn to execute Multiple commands,this conn will put conn pool after it is executed.

func (*GORMDB) Count

func (db *GORMDB) Count(count *int64) GORMDBIOCInterface

func (*GORMDB) Create

func (db *GORMDB) Create(value interface{}) GORMDBIOCInterface

Create insert the value into database

func (*GORMDB) CreateInBatches

func (db *GORMDB) CreateInBatches(value interface{}, batchSize int) GORMDBIOCInterface

CreateInBatches insert the value in batches into database

func (*GORMDB) DB

func (db *GORMDB) DB() (*sql.DB, error)

DB returns `*sql.DB`

func (*GORMDB) Debug

func (db *GORMDB) Debug() GORMDBIOCInterface

Debug start debug mode

func (*GORMDB) Delete

func (db *GORMDB) Delete(value interface{}, conds ...interface{}) GORMDBIOCInterface

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

func (*GORMDB) Distinct

func (db *GORMDB) Distinct(args ...interface{}) GORMDBIOCInterface

Distinct specify distinct fields that you want querying

func (*GORMDB) Error

func (db *GORMDB) Error() error

func (*GORMDB) Exec

func (db *GORMDB) Exec(sql string, values ...interface{}) GORMDBIOCInterface

Exec execute raw sql

func (*GORMDB) Find

func (db *GORMDB) Find(dest interface{}, conds ...interface{}) GORMDBIOCInterface

Find find records that match given conditions

func (*GORMDB) FindInBatches

func (db *GORMDB) FindInBatches(dest interface{}, batchSize int, fc func(tx *gorm.DB, batch int) error) GORMDBIOCInterface

FindInBatches find records in batches

func (*GORMDB) First

func (db *GORMDB) First(dest interface{}, conds ...interface{}) GORMDBIOCInterface

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

func (*GORMDB) FirstOrCreate

func (db *GORMDB) FirstOrCreate(dest interface{}, conds ...interface{}) GORMDBIOCInterface

FirstOrCreate gets the first matched record or create a new one with given conditions (only works with struct, map conditions)

func (*GORMDB) FirstOrInit

func (db *GORMDB) FirstOrInit(dest interface{}, conds ...interface{}) GORMDBIOCInterface

FirstOrInit gets the first matched record or initialize a new instance with given conditions (only works with struct or map conditions)

func (*GORMDB) Get

func (db *GORMDB) Get(key string) (interface{}, bool)

Get get value with key from current db instance's context

func (*GORMDB) Group

func (db *GORMDB) Group(name string) GORMDBIOCInterface

Group specify the group method on the find

func (*GORMDB) Having

func (db *GORMDB) Having(query interface{}, args ...interface{}) GORMDBIOCInterface

Having specify HAVING conditions for GROUP BY

func (*GORMDB) InstanceGet

func (db *GORMDB) InstanceGet(key string) (interface{}, bool)

InstanceGet get value with key from current db instance's context

func (*GORMDB) InstanceSet

func (db *GORMDB) InstanceSet(key string, value interface{}) GORMDBIOCInterface

InstanceSet store value with key into current db instance's context

func (*GORMDB) Joins

func (db *GORMDB) Joins(query string, args ...interface{}) GORMDBIOCInterface

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)
db.Joins("Account", DB.Select("id").Where("user_id = users.id AND name = ?", "someName").Model(&Account{}))

func (*GORMDB) Last

func (db *GORMDB) Last(dest interface{}, conds ...interface{}) GORMDBIOCInterface

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

func (*GORMDB) Limit

func (db *GORMDB) Limit(limit int) GORMDBIOCInterface

Limit specify the number of records to be retrieved

func (*GORMDB) Migrator

func (db *GORMDB) Migrator() gorm.Migrator

func (*GORMDB) Model

func (db *GORMDB) Model(value interface{}) GORMDBIOCInterface

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 (*GORMDB) Not

func (db *GORMDB) Not(query interface{}, args ...interface{}) GORMDBIOCInterface

Not add NOT conditions

func (*GORMDB) Offset

func (db *GORMDB) Offset(offset int) GORMDBIOCInterface

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

func (*GORMDB) Omit

func (db *GORMDB) Omit(columns ...string) GORMDBIOCInterface

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

func (*GORMDB) Or

func (db *GORMDB) Or(query interface{}, args ...interface{}) GORMDBIOCInterface

Or add OR conditions

func (*GORMDB) Order

func (db *GORMDB) Order(value interface{}) GORMDBIOCInterface

Order specify order when retrieve records from database

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

func (*GORMDB) Pluck

func (db *GORMDB) Pluck(column string, dest interface{}) GORMDBIOCInterface

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

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

func (*GORMDB) Preload

func (db *GORMDB) Preload(query string, args ...interface{}) GORMDBIOCInterface

Preload preload associations with given conditions

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

func (*GORMDB) Raw

func (db *GORMDB) Raw(sql string, values ...interface{}) GORMDBIOCInterface

func (*GORMDB) Rollback

func (db *GORMDB) Rollback()

Rollback rollback a transaction

func (*GORMDB) RollbackTo

func (db *GORMDB) RollbackTo(name string) GORMDBIOCInterface

func (*GORMDB) Row

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

func (*GORMDB) Rows

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

func (*GORMDB) Save

func (db *GORMDB) Save(value interface{}) GORMDBIOCInterface

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

func (*GORMDB) SavePoint

func (db *GORMDB) SavePoint(name string) GORMDBIOCInterface

func (*GORMDB) Scan

func (db *GORMDB) Scan(dest interface{}) GORMDBIOCInterface

Scan scan value to a struct

func (*GORMDB) ScanRows

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

func (*GORMDB) Scopes

func (db *GORMDB) Scopes(funcs ...func(db *gorm.DB) *gorm.DB) GORMDBIOCInterface

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 (*GORMDB) Select

func (db *GORMDB) Select(query interface{}, args ...interface{}) GORMDBIOCInterface

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

func (*GORMDB) Session

func (db *GORMDB) Session(config *gorm.Session) GORMDBIOCInterface

Session create new db session

func (*GORMDB) Set

func (db *GORMDB) Set(key string, value interface{}) GORMDBIOCInterface

Set store value with key into current db instance's context

func (*GORMDB) SetupJoinTable

func (db *GORMDB) SetupJoinTable(model interface{}, field string, joinTable interface{}) error

SetupJoinTable setup join table schema

func (*GORMDB) Table

func (db *GORMDB) Table(name string, args ...interface{}) GORMDBIOCInterface

Table specify the table you would like to run db operations

func (*GORMDB) Take

func (db *GORMDB) Take(dest interface{}, conds ...interface{}) GORMDBIOCInterface

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

func (*GORMDB) ToSQL

func (db *GORMDB) ToSQL(queryFn func(tx *gorm.DB) *gorm.DB) string

func (*GORMDB) Transaction

func (db *GORMDB) Transaction(fc func(db *gorm.DB) error, opts ...*sql.TxOptions) (err error)

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

func (*GORMDB) Unscoped

func (db *GORMDB) Unscoped() GORMDBIOCInterface

func (*GORMDB) Update

func (db *GORMDB) Update(column string, value interface{}) GORMDBIOCInterface

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

func (*GORMDB) UpdateColumn

func (db *GORMDB) UpdateColumn(column string, value interface{}) GORMDBIOCInterface

func (*GORMDB) UpdateColumns

func (db *GORMDB) UpdateColumns(values interface{}) GORMDBIOCInterface

func (*GORMDB) Updates

func (db *GORMDB) Updates(values interface{}) GORMDBIOCInterface

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

func (*GORMDB) Use

func (db *GORMDB) Use(plugin gorm.Plugin) error

Use use plugin

func (*GORMDB) Where

func (db *GORMDB) Where(query interface{}, args ...interface{}) GORMDBIOCInterface

Where add conditions

func (*GORMDB) WithContext

func (db *GORMDB) WithContext(ctx context.Context) GORMDBIOCInterface

WithContext change current instance db's context to ctx

type GORMDBIOCInterface

type GORMDBIOCInterface interface {
	Session(config *gorm_iogormx.Session) GORMDBIOCInterface
	WithContext(ctx contextx.Context) GORMDBIOCInterface
	Debug() GORMDBIOCInterface
	Set(key string, value interface{}) GORMDBIOCInterface
	Get(key string) (interface{}, bool)
	InstanceSet(key string, value interface{}) GORMDBIOCInterface
	InstanceGet(key string) (interface{}, bool)
	AddError(err error) error
	DB() (*sql.DB, error)
	SetupJoinTable(model interface{}, field string, joinTable interface{}) error
	Use(plugin gorm_iogormx.Plugin) error
	ToSQL(queryFn func(tx *gorm_iogormx.DB) *gorm_iogormx.DB) string
	Model(value interface{}) GORMDBIOCInterface
	Clauses(conds ...clause.Expression) GORMDBIOCInterface
	Table(name string, args ...interface{}) GORMDBIOCInterface
	Distinct(args ...interface{}) GORMDBIOCInterface
	Select(query interface{}, args ...interface{}) GORMDBIOCInterface
	Omit(columns ...string) GORMDBIOCInterface
	Where(query interface{}, args ...interface{}) GORMDBIOCInterface
	Not(query interface{}, args ...interface{}) GORMDBIOCInterface
	Or(query interface{}, args ...interface{}) GORMDBIOCInterface
	Joins(query string, args ...interface{}) GORMDBIOCInterface
	Group(name string) GORMDBIOCInterface
	Having(query interface{}, args ...interface{}) GORMDBIOCInterface
	Order(value interface{}) GORMDBIOCInterface
	Limit(limit int) GORMDBIOCInterface
	Offset(offset int) GORMDBIOCInterface
	Scopes(funcs ...func(db *gorm_iogormx.DB) *gorm_iogormx.DB) GORMDBIOCInterface
	Preload(query string, args ...interface{}) GORMDBIOCInterface
	Attrs(attrs ...interface{}) GORMDBIOCInterface
	Assign(attrs ...interface{}) GORMDBIOCInterface
	Unscoped() GORMDBIOCInterface
	Raw(sql string, values ...interface{}) GORMDBIOCInterface
	Error() error
	Create(value interface{}) GORMDBIOCInterface
	CreateInBatches(value interface{}, batchSize int) GORMDBIOCInterface
	Save(value interface{}) GORMDBIOCInterface
	First(dest interface{}, conds ...interface{}) GORMDBIOCInterface
	Take(dest interface{}, conds ...interface{}) GORMDBIOCInterface
	Last(dest interface{}, conds ...interface{}) GORMDBIOCInterface
	Find(dest interface{}, conds ...interface{}) GORMDBIOCInterface
	FindInBatches(dest interface{}, batchSize int, fc func(tx *gorm_iogormx.DB, batch int) error) GORMDBIOCInterface
	FirstOrInit(dest interface{}, conds ...interface{}) GORMDBIOCInterface
	FirstOrCreate(dest interface{}, conds ...interface{}) GORMDBIOCInterface
	Update(column string, value interface{}) GORMDBIOCInterface
	Updates(values interface{}) GORMDBIOCInterface
	UpdateColumn(column string, value interface{}) GORMDBIOCInterface
	UpdateColumns(values interface{}) GORMDBIOCInterface
	Delete(value interface{}, conds ...interface{}) GORMDBIOCInterface
	Count(count *int64) GORMDBIOCInterface
	Row() *sql.Row
	Rows() (*sql.Rows, error)
	Scan(dest interface{}) GORMDBIOCInterface
	Pluck(column string, dest interface{}) GORMDBIOCInterface
	ScanRows(rows *sql.Rows, dest interface{}) error
	Connection(fc func(db *gorm_iogormx.DB) error) (err error)
	Transaction(fc func(db *gorm_iogormx.DB) error, opts ...*sql.TxOptions) (err error)
	Begin(opts ...*sql.TxOptions) GORMDBIOCInterface
	Commit() GORMDBIOCInterface
	Rollback()
	SavePoint(name string) GORMDBIOCInterface
	RollbackTo(name string) GORMDBIOCInterface
	Exec(sql string, values ...interface{}) GORMDBIOCInterface
	Migrator() gorm_iogormx.Migrator
	AutoMigrate(dst ...interface{}) error
	Association(column string) *gorm_iogormx.Association
}

func GetGORMDBIOCInterface

func GetGORMDBIOCInterface(p *Param) (GORMDBIOCInterface, error)

func GetGORMDBIOCInterfaceSingleton

func GetGORMDBIOCInterfaceSingleton(p *Param) (GORMDBIOCInterface, error)

type Param

type Param struct {
	Host     string `yaml:"host"`
	Port     string `yaml:"port"`
	Username string `yaml:"username"`
	Password string `yaml:"password"`
	DBName   string `yaml:"dbname"`
}

func (*Param) New

func (c *Param) New(mysqlImpl *GORMDB) (*GORMDB, error)

Jump to

Keyboard shortcuts

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