gorose

package module
v2.2.1-0...-3c1ecb4 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2020 License: MIT Imports: 16 Imported by: 0

README

GoRose ORM

GoDoc Go Report Card GitHub release Gitter GitHub GitHub All Releases gorose-orm

  _______   ______   .______        ______        _______. _______ 
 /  _____| /  __  \  |   _  \      /  __  \      /       ||   ____|
|  |  __  |  |  |  | |  |_)  |    |  |  |  |    |   (----`|  |__   
|  | |_ | |  |  |  | |      /     |  |  |  |     \   \    |   __|  
|  |__| | |  `--'  | |  |\  \----.|  `--'  | .----)   |   |  |____ 
 \______|  \______/  | _| `._____| \______/  |_______/    |_______|

翻译(translation)

English readme | 中文 readme

文档

最新版2.x文档 | 1.x文档 | 0.x文档

简介

gorose是一个golang orm框架, 借鉴自laravel的eloquent. gorose 2.0 采用模块化架构, 通过interface的api通信,严格的上层依赖下层.每一个模块都可以拆卸, 甚至可以自定义为自己喜欢的样子.
模块关系图如下: gorose-2.0-design

安装

  • go.mod
require github.com/gohouse/gorose/v2 v2.1.8

重要的事情说三遍!
重要的事情说三遍!
重要的事情说三遍!
使用的时候必须import "github.com/gohouse/gorose/v2"方可正常使用.
千万不要漏掉末尾的v2,这个是vgo的规定

如果使用最新更新,没有tag的话,可以使用require github.com/gohouse/gorose/v2 master,执行go mod tidy后,会自动获取最新提交的版本hash最为版本号,最终效果如:github.com/gohouse/gorose/v2 v2.1.6-0.20200403045240-167d9094d7bd

  • docker
docker run -it --rm ababy/gorose sh -c "go run main.go"

docker 镜像: ababy/gorose, docker镜像包含了gorose所必须的包和运行环境, 查看Dockerfile

  • go get
go get -u github.com/gohouse/gorose/v2

支持驱动

api预览

db.Table().Fields().Where().GroupBy().Having().OrderBy().Limit().Select()
db.Table().Data().Insert()
db.Table().Data().Where().Update()
db.Table().Where().Delete()

简单用法示例

package main
import (
	"fmt"
	"github.com/gohouse/gorose/v2"
	_ "github.com/mattn/go-sqlite3"
)
var err error
var engin *gorose.Engin
func init() {
    // 全局初始化数据库,并复用
    // 这里的engin需要全局保存,可以用全局变量,也可以用单例
    // 配置&gorose.Config{}是单一数据库配置
    // 如果配置读写分离集群,则使用&gorose.ConfigCluster{}
	engin, err = gorose.Open(&gorose.Config{Driver: "sqlite3", Dsn: "./db.sqlite"})
    // mysql示例, 记得导入mysql驱动 github.com/go-sql-driver/mysql
	// engin, err = gorose.Open(&gorose.Config{Driver: "mysql", Dsn: "root:root@tcp(localhost:3306)/test?charset=utf8mb4&parseTime=true"})
}
func DB() gorose.IOrm {
	return engin.NewOrm()
}
func main() {
    // 原生sql, 直接返回结果集
    res,err := DB().Query("select * from users where uid>? limit 2", 1)
    fmt.Println(res)
    affected_rows,err := DB().Execute("delete from users where uid=?", 1)
    fmt.Println(affected_rows, err)

    // orm链式操作,查询单条数据
    res, err = DB().Table("users").First()
    // res 类型为 map[string]interface{}
    fmt.Println(res)
    
    // orm链式操作,查询多条数据
    res2, _ := DB().Table("users").Get()
    // res2 类型为 []map[string]interface{}
    fmt.Println(res2)
}

使用建议

gorose提供数据对象绑定(map, struct), 同时支持字符串表名和map数据返回. 提供了很大的灵活性
建议优先采用数据绑定的方式来完成查询操作, 做到数据源类型可控
gorose提供了默认的 gorose.Mapgorose.Data 类型, 用来方便初始化绑定和data

配置和链接初始化

简单配置

var configSimple = &gorose.Config{
	Driver: "sqlite3", 
	Dsn: "./db.sqlite",
}

更多配置, 可以配置集群,甚至可以同时配置不同数据库在一个集群中, 数据库会随机选择集群的数据库来完成对应的读写操作, 其中master是写库, slave是读库, 需要自己做好主从复制, 这里只负责读写

var config1 = gorose.Config{Dsn: "./db.sqlite"}
var config2 = gorose.Config{Dsn: "./db2.sqlite"}
var config3 = gorose.Config{Dsn: "./db3.sqlite"}
var config4 = gorose.Config{Dsn: "./db4.sqlite"}
var configCluster = &gorose.ConfigCluster{
    Master:  []gorose.Config{config3, config4},
    Slave: []gorose.Config{config1, config2},
    Driver: "sqlite3",
}

初始化使用

var engin *gorose.Engin
engin, err := Open(config)
//engin, err := Open(configCluster)

if err != nil {
    panic(err.Error())
}

原生sql操作(增删改查), session的使用

创建用户表 users

DROP TABLE IF EXISTS "users";
CREATE TABLE "users" (
	 "uid" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
	 "name" TEXT NOT NULL,
	 "age" integer NOT NULL
);

INSERT INTO "users" VALUES (1, 'gorose', 18);
INSERT INTO "users" VALUES (2, 'goroom', 18);
INSERT INTO "users" VALUES (3, 'fizzday', 18);

定义表struct

type Users struct {
	Uid  int    `gorose:"uid"`
	Name string `gorose:"name"`
	Age  int    `gorose:"age"`
}
// 设置表名, 如果没有设置, 默认使用struct的名字
func (u *Users) TableName() string {
	return "users"
}

原生查询操作
除了上边的直接返回结果集外, 还支持绑定结果到给定对象上

// 这里是要绑定的结构体对象
// 如果你没有定义结构体, 则可以直接使用map, map示例
// var u = gorose.Data{}
// var u = gorose.Map{}  这两个都是可以的
var u Users
session := engin.NewSession()
// 这里Bind()是为了存放结果的, 如果你使用的是NewOrm()初始化,则可以直接使用 NewOrm().Table().Query()
_,err := session.Bind(&u).Query("select * from users where uid=? limit 2", 1)
fmt.Println(err)
fmt.Println(u)
fmt.Println(session.LastSql())

原生增删改操作

session.Execute("insert into users(name,age) values(?,?)(?,?)", "gorose",18,"fizzday",19)
session.Execute("update users set name=? where uid=?","gorose",1)
session.Execute("delete from users where uid=?", 1)

对象关系映射, orm的使用

    1. 基本链式使用
var u Users
db := engin.NewOrm()
err := db.Table(&u).Fields("name").AddFields("uid","age").Distinct().Where("uid",">",0).OrWhere("age",18).
	Group("age").Having("age>1").OrderBy("uid desc").Limit(10).Offset(1).Select()
    1. 如果不想定义struct, 又想绑定指定类型的map结果, 则可以定义map类型, 如
type user gorose.Map
// 或者 以下的type定义, 都是可以正常解析的
type user2 map[string]interface{}
type users3 []user
type users4 []map[string]string
type users5 []gorose.Map
type users6 []gorose.Data
  • 2.1 开始使用map绑定
db.Table(&user).Select()
db.Table(&users4).Limit(5).Select()

注意: 如果使用的不是slice数据结构, 则只能获取到一条数据


这里使用的 gorose.Data , 实际上就是 map[string]interface{} 类型.
gorose.Map, 实际上是 t.MapStringT 类型, 这里出现了一个 t 包, 是一个golang基本数据类型的相互转换包, 请看详细介绍 http://github.com/gohouse/t

    1. laravel的First(),Get(), 用来返回结果集
      也就是说, 你甚至可以不用传入各种绑定的struct和map, 直接传入表名, 返回两个参数, 一个是 []gorose.Map结果集, 第二个是error,堪称简单粗暴
      用法就是把上边的 Select() 方法换成 Get,First 即可, 只不过, Select() 只返回一个参数
    1. orm的增删改查
db.Table(&user2).Limit(10.Select()
db.Table(&user2).Where("uid", 1).Data(gorose.Data{"name","gorose"}).Update()
db.Table(&user2).Data(gorose.Data{"name","gorose33"}).Insert()
db.Table(&user2).Data([]gorose.Data{{"name","gorose33"},"name","gorose44"}).Insert()
db.Table(&user2).Where("uid", 1).Delete()

最终sql构造器, builder构造不同数据库的sql

目前支持 mysql, sqlite3, postgres, oracle, mssql, clickhouse等符合 database/sql 接口支持的数据库驱动
这一部分, 用户基本无感知, 分理出来, 主要是为了开发者可以自由添加和修改相关驱动以达到个性化的需求

binder, 数据绑定对象

这一部分也是用户无感知的, 主要是传入的绑定对象解析和数据绑定, 同样是为了开发者个性化定制而独立出来的

模块化

gorose2.0 完全模块化, 每一个模块都封装了interface接口api, 模块间调用, 都是通过接口, 上层依赖下层

  • 主模块
    • engin
      gorose 初始化配置模块, 可以全局保存并复用
    • session
      真正操作数据库底层模块, 所有的操作, 最终都会走到这里来获取或修改数据
    • orm
      对象关系映射模块, 所有的orm操作, 都在这里完成
    • builder
      构建终极执行的sql模块, 可以构建任何数据库的sql, 但要符合database/sql包的接口
  • 子模块
    • driver
      数据库驱动模块, 被engin和builder依赖, 根据驱动来搞事情
    • binder
      结果集绑定模块, 所有的返回结果集都在这里

以上主模块, 都相对独立, 可以个性化定制和替换, 只要实现相应模块的接口即可.

最佳实践

sql

DROP TABLE IF EXISTS "users";
CREATE TABLE "users" (
	 "uid" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
	 "name" TEXT NOT NULL,
	 "age" integer NOT NULL
);

INSERT INTO "users" VALUES (1, 'gorose', 18);
INSERT INTO "users" VALUES (2, 'goroom', 18);
INSERT INTO "users" VALUES (3, 'fizzday', 18);

实战代码

package main

import (
	"fmt"
	"github.com/gohouse/gorose/v2"
	_ "github.com/mattn/go-sqlite3"
)

type Users struct {
    Uid int64 `gorose:"uid"`
    Name string `gorose:"name"`
    Age int64 `gorose:"age"`
    Xxx interface{} `gorose:"-"` // 这个字段在orm中会忽略
}

func (u *Users) TableName() string {
	return "users"
}

var err error
var engin *gorose.Engin

func init() {
    // 全局初始化数据库,并复用
    // 这里的engin需要全局保存,可以用全局变量,也可以用单例
    // 配置&gorose.Config{}是单一数据库配置
    // 如果配置读写分离集群,则使用&gorose.ConfigCluster{}
	engin, err = gorose.Open(&gorose.Config{Driver: "sqlite3", Dsn: "./db.sqlite"})
}
func DB() gorose.IOrm {
	return engin.NewOrm()
}
func main() {
	// 这里定义一个变量db, 是为了复用db对象, 可以在最后使用 db.LastSql() 获取最后执行的sql
	// 如果不复用 db, 而是直接使用 DB(), 则会新建一个orm对象, 每一次都是全新的对象
	// 所以复用 db, 一定要在当前会话周期内
	db := DB()
	
	// 查询一条
	var u Users
	// 查询数据并绑定到 user{} 上
	err = db.Table(&u).Fields("uid,name,age").Where("age",">",0).OrderBy("uid desc").Select()
	if err!=nil {
		fmt.Println(err)
	}
	fmt.Println(u, u.Name)
	fmt.Println(db.LastSql())
	
	// 查询多条
	// 查询数据并绑定到 []Users 上, 这里复用了 db 及上下文条件参数
	// 如果不想复用,则可以使用DB()就会开启全新会话,或者使用db.Reset()
	// db.Reset()只会清除上下文参数干扰,不会更换链接,DB()则会更换链接
	var u2 []Users
	err = db.Table(&u2).Limit(10).Offset(1).Select()
	fmt.Println(u2)
	
	// 统计数据
	var count int64
	// 这里reset清除上边查询的参数干扰, 可以统计所有数据, 如果不清除, 则条件为上边查询的条件
	// 同时, 可以新调用 DB(), 也不会产生干扰
	count,err = db.Reset().Count()
	// 或
	count, err = DB().Table(&u).Count()
	fmt.Println(count, err)
}

高级用法

  • Chunk 数据分片 大量数据批量处理 (累积处理)

    当需要操作大量数据的时候, 一次性取出再操作, 不太合理, 就可以使用chunk方法 chunk的第一个参数是指定一次操作的数据量, 根据业务量, 取100条或者1000条都可以 chunk的第二个参数是一个回调方法, 用于书写正常的数据处理逻辑 目的是做到, 无感知处理大量数据 实现原理是, 每一次操作, 自动记录当前的操作位置, 下一次重复取数据的时候, 从当前位置开始取

    User := db.Table("users")
    User.Fields("id, name").Where("id",">",2).Chunk(2, func(data []gorose.Data) error {
        // for _,item := range data {
        // 	   fmt.Println(item)
        // }
        fmt.Println(data)
    
        // 这里不要忘记返回错误或nil
        return nil
    })
    
    // 打印结果:  
    // map[id:3 name:gorose]
    // map[id:4 name:fizzday]
    // map[id:5 name:fizz3]
    // map[id:6 name:gohouse]
    [map[id:3 name:gorose] map[name:fizzday id:4]]
    [map[id:5 name:fizz3] map[id:6 name:gohouse]]
    
  • Loop 数据分片 大量数据批量处理 (从头处理)

    类似 chunk 方法, 实现原理是, 每一次操作, 都是从头开始取数据 原因: 当我们更改数据时, 更改的结果可能作为where条件会影响我们取数据的结果,所以, 可以使用Loop

    User := db.Table("users")
    User.Fields("id, name").Where("id",">",2).Loop(2, func(data []gorose.Data) error {
        // for _,item := range data {
        // 	   fmt.Println(item)
        // }
        // 这里执行update / delete  等操作
    
        // 这里不要忘记返回错误或nil
        return nil
    })
    
  • 嵌套where

    // SELECT  * FROM users  
    //     WHERE  id > 1 
    //         and ( name = 'fizz' 
    //             or ( name = 'fizz2' 
    //                 and ( name = 'fizz3' or website like 'fizzday%')
    //                 )
    //             ) 
    //     and job = 'it' LIMIT 1
    User := db.Table("users")
    User.Where("id", ">", 1).Where(func() {
            User.Where("name", "fizz").OrWhere(func() {
                User.Where("name", "fizz2").Where(func() {
                    User.Where("name", "fizz3").OrWhere("website", "like", "fizzday%")
                })
            })
        }).Where("job", "it").First()
    
  • 嵌入原生sql示例
    以下几种操作是等效的

db.Table("users").WhereRegexp("name","\w+").BuildSql()
db.Table("users").Where("name","regexp","\w+").BuildSql()
db.Table("users").Where([]interface{}{"name","regexp","\w+"}).BuildSql()
db.Table("users").Where(gorose.Data{"name regexp","\w+"}).BuildSql()

升级日志

  • v2.1.5-master:

    • 增加regexp表达式在where中的使用
  • v2.1.4:

    • logger修正
    • 事物改进
    • 依赖包改为 gohouse/golib(gohouse/t,gohouse/gocar)
  • v2.1.x:

    • join表自动加前缀,不需要再手动加前缀
    • 原生sql的query()方法,增加返回结果集[]map[string]interface{}
  • v2.0.0: 船新版本,船新架构

升级指南

从2.0.x升级到2.1.x
  • xxx.Join("pre_tablename")更改为xxx.Join("tablename"),这里不需要手动指定表前缀
  • err:=DB().Bind().Query(),更改为多返回res,err:=DB().Query(),同时保留了Bind()用法
从1.x升级到2.x, 全新安装

Jetbrains 开源支持

gorose 项目一直以来都是在 JetBrains 公司旗下的 GoLand 集成开发环境中进行开发,基于 free JetBrains Open Source license(s) 正版免费授权,在此表达我的谢意。


赞助渠道

微信 支付宝 paypal: click
  • 捐赠列表
total avator
¥100

Documentation

Index

Constants

View Source
const (
	// VERSION_TEXT ...
	VERSION_TEXT = "\ngolang orm of gorose's version : "
	// VERSION_NO ...
	VERSION_NO = "v2.1.5"
	// VERSION ...
	VERSION = VERSION_TEXT + VERSION_NO + GOROSE_IMG
)
View Source
const (
	// DriverClickhouse ...
	DriverClickhouse = "clickhouse"
)
View Source
const (
	// DriverMsSql ...
	DriverMsSql = "mssql"
)
View Source
const (
	// DriverMysql ...
	DriverMysql = "mysql"
)
View Source
const (
	// DriverOracle ...
	DriverOracle = "oci8"
)
View Source
const (
	// DriverPostgres ...
	DriverPostgres = "postgres"
)
View Source
const (
	// DriverSqlite3 ...
	DriverSqlite3 = "sqlite3"
)
View Source
const GOROSE_IMG = `` /* 497-byte string literal not displayed */

GOROSE_IMG ...

Variables

View Source
var BindString = map[BindType]string{
	OBJECT_STRUCT:       "OBJECT_STRUCT",
	OBJECT_STRUCT_SLICE: "OBJECT_STRUCT_SLICE",
	OBJECT_MAP:          "OBJECT_MAP",
	OBJECT_MAP_SLICE:    "OBJECT_MAP_SLICE",
	OBJECT_STRING:       "OBJECT_STRING",
	OBJECT_MAP_T:        "OBJECT_MAP_T",
	OBJECT_MAP_SLICE_T:  "OBJECT_MAP_SLICE_T",
	OBJECT_NIL:          "OBJECT_NIL",
}

BindString ...

View Source
var IGNORE = "-"

IGNORE ...

View Source
var TAGNAME = "gorose"

TAGNAME ...

Functions

func DefaultLogger

func DefaultLogger() func(e *Engin)

DefaultLogger ...

func GetErr

func GetErr(err Error, args ...interface{}) error

GetErr ...

func If

func If(condition bool, trueVal, falseVal interface{}) interface{}

If : ternary operator (三元运算) condition:比较运算 trueVal:运算结果为真时的值 falseVal:运算结果为假时的值 return: 由于不知道传入值的类型, 所有, 必须在接收结果时, 指定对应的值类型

func StructToMap

func StructToMap(obj interface{}) map[string]interface{}

StructToMap ...

Types

type BindType

type BindType int

BindType ...

const (
	// OBJECT_STRUCT 结构体 一条数据	(struct)
	OBJECT_STRUCT BindType = iota
	// OBJECT_STRUCT_SLICE 结构体 多条数据	([]struct)
	OBJECT_STRUCT_SLICE
	// OBJECT_MAP map 一条数据 (map[string]interface{})
	OBJECT_MAP
	// OBJECT_MAP_SLICE map 多条数据 ([]map[string]interface{})
	OBJECT_MAP_SLICE
	// OBJECT_STRING 非结构体 表名字符串 ("users")
	OBJECT_STRING
	// OBJECT_MAP_T map 一条数据 (map[string]t.Type)
	OBJECT_MAP_T
	// OBJECT_MAP_SLICE_T map 多条数据 ([]map[string]t.Type)
	OBJECT_MAP_SLICE_T
	// OBJECT_NIL 默认没有传入任何绑定对象,一般用于query直接返回
	OBJECT_NIL
)

func (BindType) String

func (b BindType) String() string

BindType.String ...

type Binder

type Binder struct {
	// Bind是指传入的对象 [slice]map,[slice]struct
	// 传入的原始对象
	BindOrigin interface{}
	//BindOriginTableName []string
	// 解析出来的对象名字, 或者指定的method(TableName)获取到的名字
	BindName string
	// 一条结果的反射对象
	BindResult interface{}
	// 多条
	BindResultSlice reflect.Value
	// 传入结构体解析出来的字段
	BindFields []string
	// 传入的对象类型判定
	BindType BindType
	// 出入传入得是非slice对象, 则只需要取一条, 取多了也是浪费
	BindLimit  int
	BindPrefix string
	// 多条map结果,传入的是string table时
	BindAll []Data
}

Binder ...

func NewBinder

func NewBinder(o ...interface{}) *Binder

NewBinder ...

func (*Binder) BindParse

func (o *Binder) BindParse(prefix string) error

BindParse ...

func (*Binder) GetBindAll

func (o *Binder) GetBindAll() []Data

GetBindAll ...

func (*Binder) GetBindFields

func (o *Binder) GetBindFields() []string

GetBindFields ...

func (*Binder) GetBindName

func (o *Binder) GetBindName() string

GetBindName ...

func (*Binder) GetBindOrigin

func (o *Binder) GetBindOrigin() interface{}

GetBindOrigin ...

func (*Binder) GetBindPrefix

func (o *Binder) GetBindPrefix() string

GetBindPrefix ...

func (*Binder) GetBindResult

func (o *Binder) GetBindResult() interface{}

GetBindResult ...

func (*Binder) GetBindResultSlice

func (o *Binder) GetBindResultSlice() reflect.Value

GetBindResultSlice ...

func (*Binder) GetBindType

func (o *Binder) GetBindType() BindType

GetBindType ...

func (*Binder) ResetBindResultSlice

func (o *Binder) ResetBindResultSlice()

ResetBindResultSlice ...

func (*Binder) ResetBinder

func (o *Binder) ResetBinder()

ResetBinder ...

func (*Binder) SetBindAll

func (o *Binder) SetBindAll(arg []Data)

SetBindAll ...

func (*Binder) SetBindFields

func (o *Binder) SetBindFields(arg []string)

SetBindFields ...

func (*Binder) SetBindName

func (o *Binder) SetBindName(arg string)

SetBindName ...

func (*Binder) SetBindOrigin

func (o *Binder) SetBindOrigin(arg interface{})

SetBindOrigin ...

func (*Binder) SetBindPrefix

func (o *Binder) SetBindPrefix(arg string)

SetBindPrefix ...

func (*Binder) SetBindResult

func (o *Binder) SetBindResult(arg interface{})

SetBindResult ...

func (*Binder) SetBindResultSlice

func (o *Binder) SetBindResultSlice(arg reflect.Value)

SetBindResultSlice ...

func (*Binder) SetBindType

func (o *Binder) SetBindType(arg BindType)

SetBindType ...

type BuilderClickhouse

type BuilderClickhouse struct {
	FieldQuotesDefault
	// contains filtered or unexported fields
}

BuilderClickhouse ...

func NewBuilderClickhouse

func NewBuilderClickhouse() *BuilderClickhouse

NewBuilderClickhouse ...

func (*BuilderClickhouse) BuildExecute

func (b *BuilderClickhouse) BuildExecute(o IOrm, operType string) (sqlStr string, args []interface{}, err error)

BuildExecut : build execute sql string

func (*BuilderClickhouse) BuildQuery

func (b *BuilderClickhouse) BuildQuery(o IOrm) (sqlStr string, args []interface{}, err error)

BuildQuery : build query sql string

func (*BuilderClickhouse) Clone

func (b *BuilderClickhouse) Clone() IBuilder

Clone : a new obj

type BuilderDefault

type BuilderDefault struct {
	IOrm
	// contains filtered or unexported fields
}

BuilderDefault 默认构造器, 其他的可以继承这个, 重写方法即可

func NewBuilderDefault

func NewBuilderDefault(o IOrm, current IBuilder) *BuilderDefault

NewBuilderDefault 初始化

func (*BuilderDefault) BuildData

func (b *BuilderDefault) BuildData(operType string) (string, string, string)

BuildData : build inert or update data

func (*BuilderDefault) BuildData2

func (b *BuilderDefault) BuildData2(operType string) (string, string, string)

BuildData2 ...

func (*BuilderDefault) BuildDistinct

func (b *BuilderDefault) BuildDistinct() (dis string)

BuildDistinct ...

func (*BuilderDefault) BuildExecute

func (b *BuilderDefault) BuildExecute(operType string) (sqlStr string, args []interface{}, err error)

BuilderDefault.BuildExecut : build execute query string

func (*BuilderDefault) BuildFields

func (b *BuilderDefault) BuildFields() string

BuildFields ...

func (*BuilderDefault) BuildGroup

func (b *BuilderDefault) BuildGroup() string

BuildGroup ...

func (*BuilderDefault) BuildHaving

func (b *BuilderDefault) BuildHaving() string

BuildHaving ...

func (*BuilderDefault) BuildJoin

func (b *BuilderDefault) BuildJoin() (s string, err error)

BuildJoin ...

func (*BuilderDefault) BuildLimit

func (b *BuilderDefault) BuildLimit() string

BuildLimit ...

func (*BuilderDefault) BuildOffset

func (b *BuilderDefault) BuildOffset() string

BuildOffset ...

func (*BuilderDefault) BuildOrder

func (b *BuilderDefault) BuildOrder() string

BuildOrder ...

func (*BuilderDefault) BuildQuery

func (b *BuilderDefault) BuildQuery() (sqlStr string, args []interface{}, err error)

BuildQuery 构造query

func (*BuilderDefault) BuildTable

func (b *BuilderDefault) BuildTable() string

BuildTable ...

func (*BuilderDefault) BuildWhere

func (b *BuilderDefault) BuildWhere() (where string, err error)

BuildWhere ...

func (*BuilderDefault) GetBindValues

func (b *BuilderDefault) GetBindValues() []interface{}

GetBindValues ...

func (*BuilderDefault) GetOperator

func (b *BuilderDefault) GetOperator() []string

GetOperator ...

func (*BuilderDefault) GetPlaceholder

func (b *BuilderDefault) GetPlaceholder() (phstr string)

GetPlaceholder 获取占位符

func (*BuilderDefault) SetBindValues

func (b *BuilderDefault) SetBindValues(bv interface{})

SetBindValues ...

func (*BuilderDefault) SetDriver

func (b *BuilderDefault) SetDriver(dr string) *BuilderDefault

SetDriver 设置驱动, 方便获取占位符使用

type BuilderDriver

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

BuilderDriver ...

func NewBuilderDriver

func NewBuilderDriver() *BuilderDriver

NewBuilderDriver ...

func (*BuilderDriver) Getter

func (b *BuilderDriver) Getter(driver string) IBuilder

Getter ...

func (*BuilderDriver) Register

func (b *BuilderDriver) Register(driver string, val IBuilder)

Register ...

type BuilderMsSql

type BuilderMsSql struct {
	FieldQuotesDefault
	// contains filtered or unexported fields
}

BuilderMsSql ...

func NewBuilderMsSql

func NewBuilderMsSql() *BuilderMsSql

NewBuilderMsSql ...

func (*BuilderMsSql) BuildExecute

func (b *BuilderMsSql) BuildExecute(o IOrm, operType string) (sqlStr string, args []interface{}, err error)

BuildExecut : build execute sql string

func (*BuilderMsSql) BuildQuery

func (b *BuilderMsSql) BuildQuery(o IOrm) (sqlStr string, args []interface{}, err error)

BuildQuery : build query sql string

func (*BuilderMsSql) Clone

func (b *BuilderMsSql) Clone() IBuilder

Clone : a new obj

type BuilderMysql

type BuilderMysql struct {
	FieldQuotesDefault
	// contains filtered or unexported fields
}

BuilderMysql ...

func NewBuilderMysql

func NewBuilderMysql() *BuilderMysql

NewBuilderMysql ...

func (*BuilderMysql) BuildExecute

func (b *BuilderMysql) BuildExecute(o IOrm, operType string) (sqlStr string, args []interface{}, err error)

BuildExecut : build execute sql string

func (*BuilderMysql) BuildQuery

func (b *BuilderMysql) BuildQuery(o IOrm) (sqlStr string, args []interface{}, err error)

BuildQuery : build query sql string

func (*BuilderMysql) Clone

func (b *BuilderMysql) Clone() IBuilder

Clone : a new obj

type BuilderOracle

type BuilderOracle struct {
	FieldQuotesDefault
	BuilderDefault
}

BuilderOracle ...

func NewBuilderOracle

func NewBuilderOracle(o IOrm) *BuilderOracle

NewBuilderOracle ...

func (*BuilderOracle) BuildData

func (b *BuilderOracle) BuildData(operType string) (string, string, string)

BuildData ...

func (*BuilderOracle) BuildData2

func (b *BuilderOracle) BuildData2(operType string) (string, string, string)

BuildData2 ...

func (*BuilderOracle) BuildDistinct

func (b *BuilderOracle) BuildDistinct() (dis string)

BuildDistinct ...

func (*BuilderOracle) BuildExecute

func (b *BuilderOracle) BuildExecute(o IOrm, operType string) (sqlStr string, args []interface{}, err error)

BuildExecut : build execute sql string

func (*BuilderOracle) BuildExecuteOra

func (b *BuilderOracle) BuildExecuteOra(operType string) (sqlStr string, args []interface{}, err error)

BuildExecuteOra ...

func (*BuilderOracle) BuildFields

func (b *BuilderOracle) BuildFields() string

BuildFields ...

func (*BuilderOracle) BuildGroup

func (b *BuilderOracle) BuildGroup() string

BuildGroup ...

func (*BuilderOracle) BuildHaving

func (b *BuilderOracle) BuildHaving() string

BuildHaving ...

func (*BuilderOracle) BuildJoin

func (b *BuilderOracle) BuildJoin() (s string, err error)

BuildJoin ...

func (*BuilderOracle) BuildLimit

func (b *BuilderOracle) BuildLimit() string

BuildLimit ...

func (*BuilderOracle) BuildOffset

func (b *BuilderOracle) BuildOffset() string

BuildOffset ...

func (*BuilderOracle) BuildOrder

func (b *BuilderOracle) BuildOrder() string

BuildOrder ...

func (*BuilderOracle) BuildQuery

func (b *BuilderOracle) BuildQuery(o IOrm) (sqlStr string, args []interface{}, err error)

实现接口 BuildQuery : build query sql string

func (*BuilderOracle) BuildQueryOra

func (b *BuilderOracle) BuildQueryOra() (sqlStr string, args []interface{}, err error)

BuildQueryOra ...

func (*BuilderOracle) BuildTable

func (b *BuilderOracle) BuildTable() string

BuildTable ...

func (*BuilderOracle) BuildWhere

func (b *BuilderOracle) BuildWhere() (where string, err error)

BuildWhere ...

func (*BuilderOracle) Clone

func (b *BuilderOracle) Clone() IBuilder

Clone : a new obj

func (*BuilderOracle) GetOperator

func (b *BuilderOracle) GetOperator() []string

GetOperator ...

func (*BuilderOracle) GetPlaceholder

func (b *BuilderOracle) GetPlaceholder() (phstr string)

GetPlaceholder 获取占位符

func (*BuilderOracle) SetDriver

func (b *BuilderOracle) SetDriver(dr string) *BuilderOracle

SetDriver 设置驱动, 方便获取占位符使用

type BuilderPostgres

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

BuilderPostgres ...

func NewBuilderPostgres

func NewBuilderPostgres() *BuilderPostgres

NewBuilderPostgres ...

func (*BuilderPostgres) AddFieldQuotes

func (*BuilderPostgres) AddFieldQuotes(field string) string

func (*BuilderPostgres) BuildExecute

func (b *BuilderPostgres) BuildExecute(o IOrm, operType string) (sqlStr string, args []interface{}, err error)

BuildExecut : build execute sql string

func (*BuilderPostgres) BuildQuery

func (b *BuilderPostgres) BuildQuery(o IOrm) (sqlStr string, args []interface{}, err error)

BuildQuery : build query sql string

func (*BuilderPostgres) Clone

func (b *BuilderPostgres) Clone() IBuilder

Clone : a new obj

type BuilderSqlite3

type BuilderSqlite3 struct {
	FieldQuotesDefault
	// contains filtered or unexported fields
}

BuilderSqlite3 ...

func NewBuilderSqlite3

func NewBuilderSqlite3() *BuilderSqlite3

NewBuilderSqlite3 ...

func (*BuilderSqlite3) BuildExecute

func (b *BuilderSqlite3) BuildExecute(o IOrm, operType string) (sqlStr string, args []interface{}, err error)

BuildExecut : build execute sql string

func (*BuilderSqlite3) BuildQuery

func (b *BuilderSqlite3) BuildQuery(o IOrm) (sqlStr string, args []interface{}, err error)

BuildQuery : build query sql string

func (*BuilderSqlite3) Clone

func (b *BuilderSqlite3) Clone() IBuilder

Clone : a new obj

type Config

type Config struct {
	Driver string `json:"driver"` // 驱动: mysql/sqlite3/oracle/mssql/postgres/clickhouse, 如果集群配置了驱动, 这里可以省略
	// mysql 示例:
	// root:root@tcp(localhost:3306)/test?charset=utf8mb4&parseTime=true
	Dsn             string `json:"dsn"`             // 数据库链接
	SetMaxOpenConns int    `json:"setMaxOpenConns"` // (连接池)最大打开的连接数,默认值为0表示不限制
	SetMaxIdleConns int    `json:"setMaxIdleConns"` // (连接池)闲置的连接数, 默认0
	Prefix          string `json:"prefix"`          // 表前缀, 如果集群配置了前缀, 这里可以省略
}

Config ...

type ConfigCluster

type ConfigCluster struct {
	Master []Config // 主
	Slave  []Config // 从
	Driver string   // 驱动
	Prefix string   // 前缀
}

ConfigCluster ...

type Data

type Data map[string]interface{}

Data ...

type Engin

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

Engin ...

func NewEngin

func NewEngin(conf ...interface{}) (e *Engin, err error)

NewEngin : init Engin struct pointer NewEngin : 初始化 Engin 结构体对象指针

func Open

func Open(conf ...interface{}) (engin *Engin, err error)

Open ...

func (*Engin) GetDriver

func (c *Engin) GetDriver() string

GetDriver ...

func (*Engin) GetExecuteDB

func (c *Engin) GetExecuteDB() *sql.DB

GetExecuteDB : get a master db for using execute operation GetExecuteDB : 获取一个主库用来做查询之外的操作

func (*Engin) GetLogger

func (c *Engin) GetLogger() ILogger

GetLogger ...

func (*Engin) GetPrefix

func (c *Engin) GetPrefix() string

GetPrefix 获取前缀

func (*Engin) GetQueryDB

func (c *Engin) GetQueryDB() *sql.DB

GetQueryDB : get a slave db for using query operation GetQueryDB : 获取一个从库用来做查询操作

func (*Engin) IgnoreName

func (c *Engin) IgnoreName(arg string)

IgnoreName 自定义结构体对应的orm忽略字段名字,默认-

func (*Engin) NewOrm

func (c *Engin) NewOrm() IOrm

NewOrm 获取orm实例 这是一个语法糖, 为了方便使用(engin.NewOrm())添加的 添加后会让engin和 orm 耦合, 如果不想耦合, 就删掉此方法 删掉这个方法后,可以使用 gorose.NewOrm(gorose.NewSession(gorose.IEngin)) 通过 gorose.ISession 依赖注入的方式, 达到解耦的目的

func (*Engin) NewSession

func (c *Engin) NewSession() ISession

NewSession 获取session实例 这是一个语法糖, 为了方便使用(engin.NewSession())添加的 添加后会让engin和session耦合, 如果不想耦合, 就删掉此方法 删掉这个方法后,可以使用 gorose.NewSession(gorose.IEngin) 通过 gorose.IEngin 依赖注入的方式, 达到解耦的目的

func (*Engin) Ping

func (c *Engin) Ping() error

Ping ...

func (*Engin) SetLogger

func (c *Engin) SetLogger(lg ILogger)

SetLogger ...

func (*Engin) SetPrefix

func (c *Engin) SetPrefix(pre string)

SetPrefix 设置表前缀

func (*Engin) TagName

func (c *Engin) TagName(arg string)

TagName 自定义结构体对应的orm字段,默认gorose

func (*Engin) Use

func (c *Engin) Use(closers ...func(e *Engin))

Use ...

type Err

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

Err ...

func NewErr

func NewErr() *Err

NewErr ...

func (*Err) Default

func (e *Err) Default() map[Error]string

Default ...

func (*Err) Get

func (e *Err) Get(err Error) string

Get ...

func (*Err) GetLang

func (e *Err) GetLang() Lang

GetLang ...

func (*Err) Register

func (e *Err) Register(err map[Error]string)

Register ...

func (*Err) SetLang

func (e *Err) SetLang(l Lang)

SetLang ...

type Error

type Error uint

Error ...

const (
	// ERR_PARAMS_COUNTS ...
	ERR_PARAMS_COUNTS Error = iota
	// ERR_PARAMS_MISSING ...
	ERR_PARAMS_MISSING
	// ERR_PARAMS_FORMAT ...
	ERR_PARAMS_FORMAT
)

type FieldQuotesDefault

type FieldQuotesDefault struct {
}

func (FieldQuotesDefault) AddFieldQuotes

func (FieldQuotesDefault) AddFieldQuotes(field string) string

type IBinder

type IBinder interface {
	SetBindOrigin(arg interface{})
	GetBindOrigin() interface{}
	SetBindName(arg string)
	GetBindName() string
	SetBindResult(arg interface{})
	GetBindResult() interface{}
	SetBindResultSlice(arg reflect.Value)
	GetBindResultSlice() reflect.Value
	SetBindFields(arg []string)
	GetBindFields() []string
	SetBindType(arg BindType)
	GetBindType() BindType
	//SetBindLimit(arg int)
	//GetBindLimit() int
	BindParse(prefix string) error
	SetBindPrefix(arg string)
	GetBindPrefix() string
	ResetBindResultSlice()
	SetBindAll(arg []Data)
	GetBindAll() []Data
	ResetBinder()
}

IBinder 数据绑定对象接口

type IBuilder

type IBuilder interface {
	IFieldQuotes
	BuildQuery(orm IOrm) (sqlStr string, args []interface{}, err error)
	BuildExecute(orm IOrm, operType string) (sqlStr string, args []interface{}, err error)
	Clone() IBuilder
}

IBuilder ...

func NewBuilder

func NewBuilder(driver string) IBuilder

NewBuilder 获取builder

type IEngin

type IEngin interface {
	GetExecuteDB() *sql.DB
	GetQueryDB() *sql.DB
	//EnableSqlLog(e ...bool)
	//IfEnableSqlLog() (e bool)
	//SetPrefix(pre string)
	GetPrefix() (pre string)
	//NewSession() ISession
	//NewOrm() IOrm
	SetLogger(lg ILogger)
	GetLogger() ILogger
	GetDriver() string
}

IEngin ...

type IFieldQuotes

type IFieldQuotes interface {
	AddFieldQuotes(field string) string
}

IFieldQuotes 给系统关键词冲突的字段加引号,如: mysql是反引号, pg是双引号

type ILogger

type ILogger interface {
	Sql(sqlStr string, runtime time.Duration)
	Slow(sqlStr string, runtime time.Duration)
	Error(msg string)
	EnableSqlLog() bool
	EnableErrorLog() bool
	EnableSlowLog() float64
}

ILogger ...

type IOrm

type IOrm interface {
	IOrmApi
	IOrmQuery
	IOrmExecute
	IOrmSession
	//ISession
	Close()
	BuildSql(operType ...string) (string, []interface{}, error)
	Table(tab interface{}) IOrm
	// fields=select
	Fields(fields ...string) IOrm
	AddFields(fields ...string) IOrm
	// distinct 方法允许你强制查询返回不重复的结果集:
	Distinct() IOrm
	Data(data interface{}) IOrm
	// groupBy, orderBy, having
	Group(group string) IOrm
	GroupBy(group string) IOrm
	Having(having string) IOrm
	Order(order string) IOrm
	OrderBy(order string) IOrm
	Limit(limit int) IOrm
	Offset(offset int) IOrm
	Page(page int) IOrm
	// join(=innerJoin),leftJoin,rightJoin,crossJoin
	Join(args ...interface{}) IOrm
	LeftJoin(args ...interface{}) IOrm
	RightJoin(args ...interface{}) IOrm
	CrossJoin(args ...interface{}) IOrm
	// `Where`,`OrWhere`,`WhereNull / WhereNotNull`,`WhereIn / WhereNotIn / OrWhereIn / OrWhereNotIn`,`WhereBetween / WhereBetwee / OrWhereBetween / OrWhereNotBetween`
	Where(args ...interface{}) IOrm
	OrWhere(args ...interface{}) IOrm
	WhereNull(arg string) IOrm
	OrWhereNull(arg string) IOrm
	WhereNotNull(arg string) IOrm
	OrWhereNotNull(arg string) IOrm
	WhereRegexp(arg string, expstr string) IOrm
	OrWhereRegexp(arg string, expstr string) IOrm
	WhereNotRegexp(arg string, expstr string) IOrm
	OrWhereNotRegexp(arg string, expstr string) IOrm
	WhereIn(needle string, hystack []interface{}) IOrm
	OrWhereIn(needle string, hystack []interface{}) IOrm
	WhereNotIn(needle string, hystack []interface{}) IOrm
	OrWhereNotIn(needle string, hystack []interface{}) IOrm
	WhereBetween(needle string, hystack []interface{}) IOrm
	OrWhereBetween(needle string, hystack []interface{}) IOrm
	WhereNotBetween(needle string, hystack []interface{}) IOrm
	OrWhereNotBetween(needle string, hystack []interface{}) IOrm
	// truncate
	//Truncate()
	GetDriver() string
	//GetIBinder() IBinder
	SetBindValues(v interface{})
	GetBindValues() []interface{}
	ClearBindValues()
	Transaction(closers ...func(db IOrm) error) (err error)
	Reset() IOrm
	ResetTable() IOrm
	ResetWhere() IOrm
	GetISession() ISession
	GetOrmApi() *OrmApi
	// 悲观锁使用
	// sharedLock(lock in share mode) 不会阻塞其它事务读取被锁定行记录的值
	SharedLock() *Orm
	// 此外你还可以使用 lockForUpdate 方法。“for update”锁避免选择行被其它共享锁修改或删除:
	// 会阻塞其他锁定性读对锁定行的读取(非锁定性读仍然可以读取这些记录,lock in share mode 和 for update 都是锁定性读)
	LockForUpdate() *Orm
}

IOrm ...

type IOrmApi

type IOrmApi interface {
	GetTable() string
	GetFields() []string
	SetWhere(arg [][]interface{})
	GetWhere() [][]interface{}
	GetOrder() string
	GetLimit() int
	GetOffset() int
	GetJoin() [][]interface{}
	GetDistinct() bool
	GetGroup() string
	GetHaving() string
	GetData() interface{}
	ExtraCols(args ...string) IOrm
	ResetExtraCols() IOrm
	GetExtraCols() []string
	GetPessimisticLock() string
}

IOrmApi ...

type IOrmExecute

type IOrmExecute interface {
	GetForce() bool
	// insert,insertGetId
	Insert(data ...interface{}) (int64, error)
	InsertGetId(data ...interface{}) (int64, error)
	Update(data ...interface{}) (int64, error)

	// increment,decrement
	// 在操作过程中你还可以指定额外的列进行更新:
	Increment(args ...interface{}) (int64, error)
	Decrement(args ...interface{}) (int64, error)
	// delete
	Delete() (int64, error)
	//LastInsertId() int64
	Force() IOrm
}

IOrmExecute ...

type IOrmQuery

type IOrmQuery interface {
	// 获取数据, 依据传入的绑定对象, 选择查询一条或多条数据并绑定到传入对象上
	// 当绑定对象传入的是string类型时, 返回多条结果集, 需要使用 Get() 来获取最终结果
	Select() error
	// 获取一条结果并返回, 只有当传入的table对象是字符串时生效
	First() (Data, error)
	// 获取多条结果并返回, 只有当传入的table对象是字符串时生效
	Get() ([]Data, error)
	// 如果你不需要完整的一行,可以使用 value 方法从结果中获取单个值,该方法会直接返回指定列的值:
	Value(field string) (v interface{}, err error)
	// 如果想要获取包含单个列值的数组,可以使用 pluck 方法
	// 还可以在返回数组中为列值指定自定义键(该自定义键必须是该表的其它字段列名,否则会报错)
	Pluck(field string, fieldKey ...string) (v interface{}, err error)
	// 查询构建器还提供了多个聚合方法,如count, max, min, avg 和 sum,你可以在构造查询之后调用这些方法:
	Count(args ...string) (int64, error)
	Sum(sum string) (interface{}, error)
	Avg(avg string) (interface{}, error)
	Max(max string) (interface{}, error)
	Min(min string) (interface{}, error)
	// 分页, 返回分页需要的基本数据
	Paginate(page ...int) (res Data, err error)
	// 组块结果集
	// 如果你需要处理成千上万或者更多条数据库记录,可以考虑使用 chunk 方法,该方法一次获取结果集的一小块,
	// 然后传递每一小块数据到闭包函数进行处理,该方法在编写处理大量数据库记录的 Artisan 命令的时候非常有用。
	// 例如,我们可以将处理全部 users 表数据分割成一次处理 100 条记录的小组块
	// 你可以通过从闭包函数中返回 err 来终止组块的运行
	Chunk(limit int, callback func([]Data) error) (err error)
	// 跟Chunk类似,只不过callback的是传入的结构体
	ChunkStruct(limit int, callback func() error) (err error)
	Loop(limit int, callback func([]Data) error) (err error)
}

IOrmQuery ...

type IOrmSession

type IOrmSession interface {
	//Close()
	//Table(bind interface{}) IOrm
	//Bind(bind interface{}) ISession
	Begin() (err error)
	Rollback() (err error)
	Commit() (err error)
	//Transaction(closer ...func(session ISession) error) (err error)
	Query(sqlstring string, args ...interface{}) ([]Data, error)
	Execute(sqlstring string, args ...interface{}) (int64, error)
	//GetMasterDriver() string
	//GetSlaveDriver() string
	LastInsertId() int64
	LastSql() string
	//SetIBinder(b IBinder)
	//GetTableName() (string, error)
	GetIBinder() IBinder
	SetUnion(u interface{})
	GetUnion() interface{}
}

IOrmSession ...

type ISession

type ISession interface {
	Close()
	//Table(bind interface{}) IOrm
	Bind(bind interface{}) ISession
	Begin() (err error)
	Rollback() (err error)
	Commit() (err error)
	Transaction(closer ...func(session ISession) error) (err error)
	Query(sqlstring string, args ...interface{}) ([]Data, error)
	Execute(sqlstring string, args ...interface{}) (int64, error)
	//GetDriver() string
	GetIEngin() IEngin
	LastInsertId() int64
	LastSql() string
	//SetIBinder(b IBinder)
	GetTableName() (string, error)
	SetIBinder(ib IBinder)
	GetIBinder() IBinder
	SetUnion(u interface{})
	GetUnion() interface{}
	SetTransaction(b bool)
	GetTransaction() bool
	//ResetBinder()
	GetBindAll() []Data
	GetErr() error
}

ISession ...

type Lang

type Lang uint

Lang ...

const (
	// CHINESE ...
	CHINESE Lang = iota
	// ENGLISH ...
	ENGLISH
	// CHINESE_TRADITIONAL ...
	CHINESE_TRADITIONAL
)

func (Lang) String

func (l Lang) String() string

String ...

type LogLevel

type LogLevel uint

LogLevel ...

const (
	// LOG_SQL ...
	LOG_SQL LogLevel = iota
	// LOG_SLOW ...
	LOG_SLOW
	// LOG_ERROR ...
	LOG_ERROR
)

func (LogLevel) String

func (l LogLevel) String() string

String ...

type LogOption

type LogOption struct {
	FilePath     string
	EnableSqlLog bool
	// 是否记录慢查询, 默认0s, 不记录, 设置记录的时间阀值, 比如 1, 则表示超过1s的都记录
	EnableSlowLog  float64
	EnableErrorLog bool
}

LogOption ...

type Logger

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

Logger ...

func NewLogger

func NewLogger(o *LogOption) *Logger

NewLogger ...

func (*Logger) EnableErrorLog

func (l *Logger) EnableErrorLog() bool

EnableErrorLog ...

func (*Logger) EnableSlowLog

func (l *Logger) EnableSlowLog() float64

EnableSlowLog ...

func (*Logger) EnableSqlLog

func (l *Logger) EnableSqlLog() bool

EnableSqlLog ...

func (*Logger) Error

func (l *Logger) Error(msg string)

Error ...

func (*Logger) Slow

func (l *Logger) Slow(sqlStr string, runtime time.Duration)

Slow ...

func (*Logger) Sql

func (l *Logger) Sql(sqlStr string, runtime time.Duration)

Sql ...

type Map

type Map t.MapStringT

Map ...

type Orm

type Orm struct {
	ISession
	//IBinder
	*OrmApi
	// contains filtered or unexported fields
}

type TransactionHandlerFunc func(db IOrm) error Orm ...

func NewOrm

func NewOrm(e IEngin) *Orm

NewOrm ...

func NewOrmBuilder

func NewOrmBuilder() *Orm

func (*Orm) AddFields

func (dba *Orm) AddFields(fields ...string) IOrm

AddFields : If you already have a query builder instance and you wish to add a column to its existing select clause, you may use the AddFields method:

func (*Orm) Avg

func (dba *Orm) Avg(avg string) (interface{}, error)

Avg : select avg field

func (*Orm) BuildSql

func (dba *Orm) BuildSql(operType ...string) (a string, b []interface{}, err error)

BuildSql operType(select, insert, update, delete)

func (*Orm) Chunk

func (dba *Orm) Chunk(limit int, callback func([]Data) error) (err error)

Chunk : 分块处理数据,当要处理很多数据的时候, 我不需要知道具体是多少数据, 我只需要每次取limit条数据, 然后不断的增加offset去取更多数据, 从而达到分块处理更多数据的目的 TODO 后续增加 gorotine 支持, 提高批量数据处理效率, 预计需要增加获取更多链接的支持

func (*Orm) ChunkStruct

func (dba *Orm) ChunkStruct(limit int, callback func() error) (err error)

ChunkStruct : 同Chunk,只不过不用返回map, 而是绑定数据到传入的对象上 这里一定要传入绑定struct

func (*Orm) ClearBindValues

func (dba *Orm) ClearBindValues()

ClearBindValues ...

func (*Orm) Close

func (dba *Orm) Close()

Close ...

func (*Orm) Count

func (dba *Orm) Count(args ...string) (int64, error)

Count : select count rows

func (*Orm) CrossJoin

func (dba *Orm) CrossJoin(args ...interface{}) IOrm

CrossJoin ...

func (*Orm) Data

func (dba *Orm) Data(data interface{}) IOrm

Data : insert or update data

func (*Orm) Decrement

func (dba *Orm) Decrement(args ...interface{}) (int64, error)

Decrement : auto Decrement -1 default we can define step (such as 2, 3, 6 ...) if give the second params

func (*Orm) Delete

func (dba *Orm) Delete() (int64, error)

Delete : delete data

func (*Orm) Distinct

func (dba *Orm) Distinct() IOrm

Distinct : select distinct

func (*Orm) ExtraCols

func (dba *Orm) ExtraCols(args ...string) IOrm

ExtraCols 额外的字段

func (*Orm) Fields

func (dba *Orm) Fields(fields ...string) IOrm

Fields : select fields

func (*Orm) First

func (dba *Orm) First() (result Data, err error)

First : select one row , relation limit set

func (*Orm) Force

func (dba *Orm) Force() IOrm

Force 强制执行没有where的删除和修改

func (*Orm) Get

func (dba *Orm) Get() (result []Data, err error)

Get : select more rows , relation limit set

func (*Orm) GetBindValues

func (dba *Orm) GetBindValues() []interface{}

GetBindValues ...

func (*Orm) GetData

func (o *Orm) GetData() interface{}

GetData ...

func (*Orm) GetDistinct

func (o *Orm) GetDistinct() bool

GetDistinct ...

func (*Orm) GetDriver

func (dba *Orm) GetDriver() string

GetDriver ...

func (*Orm) GetExtraCols

func (o *Orm) GetExtraCols() []string

GetExtraCols ...

func (*Orm) GetFields

func (o *Orm) GetFields() []string

GetFields ...

func (*Orm) GetForce

func (o *Orm) GetForce() bool

GetForce ...

func (*Orm) GetGroup

func (o *Orm) GetGroup() string

GetGroup ...

func (*Orm) GetHaving

func (o *Orm) GetHaving() string

GetHaving ...

func (*Orm) GetISession

func (dba *Orm) GetISession() ISession

GetISession ...

func (*Orm) GetJoin

func (o *Orm) GetJoin() [][]interface{}

GetJoin ...

func (*Orm) GetLimit

func (o *Orm) GetLimit() int

GetLimit ...

func (*Orm) GetOffset

func (o *Orm) GetOffset() int

GetOffset ...

func (*Orm) GetOrder

func (o *Orm) GetOrder() string

GetOrder ...

func (*Orm) GetOrmApi

func (dba *Orm) GetOrmApi() *OrmApi

GetOrmApi ...

func (*Orm) GetPessimisticLock

func (o *Orm) GetPessimisticLock() string

GetPessimisticLock ...

func (*Orm) GetTable

func (o *Orm) GetTable() string

GetTable ...

func (*Orm) GetWhere

func (o *Orm) GetWhere() [][]interface{}

GetWhere ...

func (*Orm) Group

func (dba *Orm) Group(group string) IOrm

Group : select group by

func (*Orm) GroupBy

func (dba *Orm) GroupBy(group string) IOrm

GroupBy : equals Group()

func (*Orm) Having

func (dba *Orm) Having(having string) IOrm

Having : select having

func (*Orm) Increment

func (dba *Orm) Increment(args ...interface{}) (int64, error)

Increment : auto Increment +1 default we can define step (such as 2, 3, 6 ...) if give the second params we can use this method as decrement with the third param as "-" orm.Increment("top") , orm.Increment("top", 2, "-")=orm.Decrement("top",2)

func (*Orm) Insert

func (dba *Orm) Insert(data ...interface{}) (int64, error)

Insert : insert data and get affected rows

func (*Orm) InsertGetId

func (dba *Orm) InsertGetId(data ...interface{}) (int64, error)

insertGetId : insert data and get id

func (*Orm) Join

func (dba *Orm) Join(args ...interface{}) IOrm

Join : select join query

func (*Orm) LeftJoin

func (dba *Orm) LeftJoin(args ...interface{}) IOrm

LeftJoin ...

func (*Orm) Limit

func (dba *Orm) Limit(limit int) IOrm

Limit : select limit

func (*Orm) LockForUpdate

func (dba *Orm) LockForUpdate() *Orm

LockForUpdate select * from xxx for update

func (*Orm) Loop

func (dba *Orm) Loop(limit int, callback func([]Data) error) (err error)

Loop : 同chunk, 不过, 这个是循环的取前limit条数据, 为什么是循环取这些数据呢 因为, 我们考虑到一种情况, 那就是where条件如果刚好是要修改的值, 那么最后的修改结果因为offset的原因, 只会修改一半, 比如: DB().Where("age", 18) ===> DB().Data(gorose.Data{"age":19}).Where().Update()

func (*Orm) Max

func (dba *Orm) Max(max string) (interface{}, error)

Max : select max field

func (*Orm) Min

func (dba *Orm) Min(min string) (interface{}, error)

Min : select min field

func (*Orm) Offset

func (dba *Orm) Offset(offset int) IOrm

Offset : select offset

func (*Orm) OrWhere

func (dba *Orm) OrWhere(args ...interface{}) IOrm

Where : query or execute where condition, the relation is and

func (*Orm) OrWhereBetween

func (dba *Orm) OrWhereBetween(needle string, hystack []interface{}) IOrm

OrWhereBetween ...

func (*Orm) OrWhereIn

func (dba *Orm) OrWhereIn(needle string, hystack []interface{}) IOrm

OrWhereIn ...

func (*Orm) OrWhereNotBetween

func (dba *Orm) OrWhereNotBetween(needle string, hystack []interface{}) IOrm

OrWhereNotBetween ...

func (*Orm) OrWhereNotIn

func (dba *Orm) OrWhereNotIn(needle string, hystack []interface{}) IOrm

OrWhereNotIn ...

func (*Orm) OrWhereNotNull

func (dba *Orm) OrWhereNotNull(arg string) IOrm

OrWhereNotNull ...

func (*Orm) OrWhereNotRegexp

func (dba *Orm) OrWhereNotRegexp(arg string, expstr string) IOrm

OrWhereNotRegexp ...

func (*Orm) OrWhereNull

func (dba *Orm) OrWhereNull(arg string) IOrm

OrWhereNull ...

func (*Orm) OrWhereRegexp

func (dba *Orm) OrWhereRegexp(arg string, expstr string) IOrm

OrWhereRegexp ...

func (*Orm) Order

func (dba *Orm) Order(order string) IOrm

Order : select order by

func (*Orm) OrderBy

func (dba *Orm) OrderBy(order string) IOrm

OrderBy : equal order

func (*Orm) Page

func (dba *Orm) Page(page int) IOrm

Page : select page

func (*Orm) Paginate

func (dba *Orm) Paginate(page ...int) (res Data, err error)

Paginate 自动分页 @param limit 每页展示数量 @param current_page 当前第几页, 从1开始 以下是laravel的Paginate返回示例

{
	"total": 50,
	"per_page": 15,
	"current_page": 1,
	"lastPage": 4,
	"first_page_url": "http://laravel.app?page=1",
	"lastPage_url": "http://laravel.app?page=4",
	"nextPage_url": "http://laravel.app?page=2",
	"prevPage_url": null,
	"path": "http://laravel.app",
	"from": 1,
	"to": 15,
	"data":[
		{
		// Result Object
		},
		{
		// Result Object
		}
	]
}

func (*Orm) Pluck

func (dba *Orm) Pluck(field string, fieldKey ...string) (v interface{}, err error)

Pluck 获取一列数据, 第二个字段可以指定另一个字段的值作为这一列数据的key

func (*Orm) Pluck_bak

func (dba *Orm) Pluck_bak(field string, fieldKey ...string) (v interface{}, err error)

Pluck_bak ...

func (*Orm) Reset

func (dba *Orm) Reset() IOrm

Reset orm api and bind values reset to init

func (*Orm) ResetExtraCols

func (dba *Orm) ResetExtraCols() IOrm

ResetExtraCols ...

func (*Orm) ResetTable

func (dba *Orm) ResetTable() IOrm

ResetTable ...

func (*Orm) ResetUnion

func (dba *Orm) ResetUnion() IOrm

ResetUnion ...

func (*Orm) ResetWhere

func (dba *Orm) ResetWhere() IOrm

ResetWhere ...

func (*Orm) RightJoin

func (dba *Orm) RightJoin(args ...interface{}) IOrm

RightJoin ...

func (*Orm) Select

func (dba *Orm) Select() error

Select : select one or more rows , relation limit set

func (*Orm) SetBindValues

func (dba *Orm) SetBindValues(v interface{})

SetBindValues ...

func (*Orm) SetISession

func (dba *Orm) SetISession(is ISession)

SetISession ...

func (*Orm) SetWhere

func (o *Orm) SetWhere(arg [][]interface{})

SetWhere ...

func (*Orm) SharedLock

func (dba *Orm) SharedLock() *Orm

SharedLock 共享锁 select * from xxx lock in share mode

func (*Orm) Sum

func (dba *Orm) Sum(sum string) (interface{}, error)

Sum : select sum field

func (*Orm) Table

func (dba *Orm) Table(tab interface{}) IOrm

Fields : select fields

func (*Orm) Transaction

func (dba *Orm) Transaction(closers ...func(db IOrm) error) (err error)

Transaction ...

func (*Orm) Update

func (dba *Orm) Update(data ...interface{}) (int64, error)

Update : update data

func (*Orm) Value

func (dba *Orm) Value(field string) (v interface{}, err error)

Value is get a row of a field value

func (*Orm) Value_bak

func (dba *Orm) Value_bak(field string) (v interface{}, err error)

Value_bak ...

func (*Orm) Where

func (dba *Orm) Where(args ...interface{}) IOrm

Where : query or execute where condition, the relation is and

func (*Orm) WhereBetween

func (dba *Orm) WhereBetween(needle string, hystack []interface{}) IOrm

WhereBetween ...

func (*Orm) WhereIn

func (dba *Orm) WhereIn(needle string, hystack []interface{}) IOrm

WhereIn ...

func (*Orm) WhereNotBetween

func (dba *Orm) WhereNotBetween(needle string, hystack []interface{}) IOrm

WhereNotBetween ...

func (*Orm) WhereNotIn

func (dba *Orm) WhereNotIn(needle string, hystack []interface{}) IOrm

WhereNotIn ...

func (*Orm) WhereNotNull

func (dba *Orm) WhereNotNull(arg string) IOrm

WhereNotNull ...

func (*Orm) WhereNotRegexp

func (dba *Orm) WhereNotRegexp(arg string, expstr string) IOrm

WhereNotRegexp ...

func (*Orm) WhereNull

func (dba *Orm) WhereNull(arg string) IOrm

WhereNull ...

func (*Orm) WhereRegexp

func (dba *Orm) WhereRegexp(arg string, expstr string) IOrm

WhereRegexp ...

type OrmApi

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

OrmApi ...

type Session

type Session struct {
	IEngin
	IBinder
	// contains filtered or unexported fields
}

Session ...

func NewSession

func NewSession(e IEngin) *Session

NewSession : 初始化 Session

func (*Session) Begin

func (s *Session) Begin() (err error)

Begin ...

func (*Session) Bind

func (s *Session) Bind(tab interface{}) ISession

Bind : 传入绑定结果的对象, 参数一为对象, 可以是 struct, gorose.MapRow 或对应的切片

如果是做非query操作,第一个参数也可以仅仅指定为字符串表名

func (*Session) Close

func (s *Session) Close()

func (*Session) Commit

func (s *Session) Commit() (err error)

Commit ...

func (*Session) Execute

func (s *Session) Execute(sqlstring string, args ...interface{}) (rowsAffected int64, err error)

Execute ...

func (*Session) GetErr

func (s *Session) GetErr() error

GetBinder 获取绑定对象

func (*Session) GetIBinder

func (s *Session) GetIBinder() IBinder

GetBinder 获取绑定对象

func (*Session) GetIEngin

func (s *Session) GetIEngin() IEngin

GetIEngin 获取engin

func (*Session) GetTableName

func (s *Session) GetTableName() (string, error)

GetTableName 获取解析后的名字, 提供给orm使用 为什么要在这里重复添加该方法, 而不是直接继承 IBinder 的方法呢? 是因为, 这里涉及到表前缀的问题, 只能通过session来传递, 所以IOrm就可以选择直接继承

func (*Session) GetTransaction

func (s *Session) GetTransaction() bool

GetTransaction 提供给 orm 使用的, 方便reset操作

func (*Session) GetUnion

func (s *Session) GetUnion() interface{}

GetUnion ...

func (*Session) LastInsertId

func (s *Session) LastInsertId() int64

LastInsertId ...

func (*Session) LastSql

func (s *Session) LastSql() string

LastSql ...

func (*Session) Query

func (s *Session) Query(sqlstring string, args ...interface{}) (result []Data, err error)

Query ...

func (*Session) ResetBinderResult

func (s *Session) ResetBinderResult()

GetBinder 获取绑定对象

func (*Session) Rollback

func (s *Session) Rollback() (err error)

Rollback ...

func (*Session) SetIBinder

func (s *Session) SetIBinder(ib IBinder)

GetBinder 获取绑定对象

func (*Session) SetIEngin

func (s *Session) SetIEngin(ie IEngin)

GetDriver 获取驱动

func (*Session) SetTransaction

func (s *Session) SetTransaction(b bool)

SetTransaction ...

func (*Session) SetUnion

func (s *Session) SetUnion(u interface{})

SetUnion ...

func (*Session) Transaction

func (s *Session) Transaction(closers ...func(ses ISession) error) (err error)

Transaction ...

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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