gorose

package module
v2.1.2 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2019 License: MIT Imports: 15 Imported by: 0

README

GoRose ORM

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

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

translations

English readme | 中文 readme

introduction

gorose is a golang orm framework, which is Inspired by laravel's eloquent.
Gorose 2.0 adopts modular architecture, communicates through the API of interface, and strictly relies on the lower layer. Each module can be disassembled, and even can be customized to its preferred appearance.
The module diagram is as follows:
gorose.2.0.jpg

installation

  • go.mod
require github.com/gohouse/gorose v2.1.0
  • docker
docker run -it --rm ababy/gorose sh -c "go run main.go"

docker image: ababy/gorose, The docker image contains the packages and runtime environment necessary for gorose, view Dockerfile

  • without version control
go get -u github.com/gohouse/gorose

document

2.x doc
1.x doc
0.x doc

api preview

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

simple usage example

package main
import (
	"fmt"
	"github.com/gohouse/gorose"
	_ "github.com/mattn/go-sqlite3"
)
var err error
var engin *gorose.Engin
func init() {
    // Global initialization and reuse of databases
    // The engin here needs to be saved globally, using either global variables or singletons
    // Configuration & gorose. Config {} is a single database configuration
    // If you configure a read-write separation cluster, use & gorose. ConfigCluster {}
	engin, err = gorose.Open(&gorose.Config{Driver: "sqlite3", Dsn: "./db.sqlite"})
    // mysql demo, remeber import mysql driver of github.com/go-sql-driver/mysql
	// engin, err = gorose.Open(&gorose.Config{Driver: "mysql", Dsn: "root:root@tcp(localhost:3306)/test?charset=utf8&parseTime=true"})
}
func DB() gorose.IOrm {
	return engin.NewOrm()
}
func main() {
    // Native SQL, return results directly 
    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 chan operation, fetch one row
    res, err := DB().Table("users").First()
    // res's type is map[string]interface{}
    fmt.Println(res)
    
    // rm chan operation, fetch more rows
    res2, _ := DB().Table("users").Get()
    // res2's type is []map[string]interface{}
    fmt.Println(res2)
}

usage advise

Gorose provides data object binding (map, struct), while supporting string table names and map data return. It provides great flexibility.

It is suggested that data binding should be used as a priority to complete query operation, so that the type of data source can be controlled. Gorose provides default gorose. Map'and gorose. Data' types to facilitate initialization of bindings and data

Simple configuration

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

More configurations, you can configure the cluster, or even configure different databases in a cluster at the same time. The database will randomly select the cluster database to complete the corresponding reading and writing operations, in which master is the writing database, slave is the reading database, you need to do master-slave replication, here only responsible for reading and writing.

var config = &gorose.ConfigCluster{
	Master:       []&gorose.Config{}{configSimple}
    Slave:        []&gorose.Config{}{configSimple}
    Prefix:       "pre_",
    Driver:       "sqlite3",
}

Initial usage

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

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

Native SQL operation (add, delete, check), session usage

Create user tables of 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);

define table struct

type Users struct {
	Uid  int    `gorose:"uid"`
	Name string `gorose:"name"`
	Age  int    `gorose:"age"`
}
// Set the table name. If not, use struct's name by default
func (u *Users) TableName() string {
	return "users"
}

Native query operation

// Here is the structure object to be bound
// If you don't define a structure, you can use map, map example directly
// var u = gorose.Data{}
// var u = gorose.Map{}  Both are possible.
var u Users
session := engin.NewSession()
// Here Bind () is used to store results. If you use NewOrm () initialization, you can use NewOrm (). Table (). Query () directly.
_,err := session.Bind(&u).Query("select * from users where uid=? limit 2", 1)
fmt.Println(err)
fmt.Println(u)
fmt.Println(session.LastSql())

Native inesrt delete update

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)

Object Relational Mapping, the Use of ORM

    1. Basic Chain Usage
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. If you don't want to define struct and want to bind map results of a specified type, you can define map types, such as
type user gorose.Map
// Or the following type definitions can be parsed properly
type user2 map[string]interface{}
type users3 []user
type users4 []map[string]string
type users5 []gorose.Map
type users6 []gorose.Data

Start using map binding

db.Table(&user).Select()
db.Table(&users4).Limit(5).Select()

Note: If the slice data structure is not used, only one piece of data can be obtained.


The gorose. Data used here is actually the `map [string] interface {}'type.

And gorose. Map'is actually a t. MapString' type. Here comes a `t'package, a golang basic data type conversion package. See http://github.com/gohouse/t for more details.

    1. laravel's First(),Get(), Used to return the result set
      That is to say, you can even pass in the table name directly without passing in various bound structs and maps, and return two parameters, one is the [] gorose. Map result set, and the second is `error', which is considered simple and rude.

Usage is to replace the Select ()'method above with Get, First, but Select ()' returns only one parameter.

    1. orm Select Update Insert Delete
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()

Final SQL constructor, builder constructs SQL of different databases

Currently supports mysql, sqlite3, postgres, oracle, mssql, Clickhouse and other database drivers that conform to database/sql interface support
In this part, users are basically insensitive, sorted out, mainly for developers can freely add and modify related drivers to achieve personalized needs.

binder, Data Binding Objects

This part is also user-insensitive, mainly for incoming binding object parsing and data binding, and also for personalized customization by developers.

Modularization

Gorose 2.0 is fully modular, each module encapsulates the interface api, calling between modules, through the interface, the upper layer depends on the lower layer

  • Main module
    • engin
      gorose Initialize the configuration module, which can be saved and reused globally
    • session
      Really operate the database underlying module, all operations, will eventually come here to obtain or modify data.
    • orm
      Object relational mapping module, all ORM operations, are done here
    • builder
      Building the ultimate execution SQL module, you can build any database sql, but to comply with the database / SQL package interface
  • sub module
    • driver
      The database driver module, which is dependent on engin and builder, does things according to the driver
    • binder
      Result Set Binding Module, where all returned result sets are located

The above main modules are relatively independent and can be customized and replaced individually, as long as the interface of the corresponding modules is realized.

Best Practices

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);

Actual Code

package main

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

type Users struct {
    Uid int64 `gorose:"uid"`
    Name string `gorose:"name"`
    Age int64 `gorose:"age"`
    Xxx interface{} `gorose:"-"` // This field is ignored in ORM
}

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

var err error
var engin *gorose.Engin

func init() {
    // Global initialization and reuse of databases
    // The engin here needs to be saved globally, using either global variables or singletons
    // Configuration & gorose. Config {} is a single database configuration
    // If you configure a read-write separation cluster, use & gorose. ConfigCluster {}
	engin, err = gorose.Open(&gorose.Config{Driver: "sqlite3", Dsn: "./db.sqlite"})
}
func DB() gorose.IOrm {
	return engin.NewOrm()
}
func main() {
	// A variable DB is defined here to reuse the DB object, and you can use db. LastSql () to get the SQL that was executed last.
	// If you don't reuse db, but use DB () directly, you create a new ORM object, which is brand new every time.
	// So reusing DB must be within the current session cycle
	db := DB()
	
	// fetch a row
	var u Users
	// bind result to 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())
	
	// fetch multi rows
	// bind result to []Users, db and context condition parameters are reused here
	// If you don't want to reuse, you can use DB() to open a new session, or db.Reset()
	// db.Reset() only removes contextual parameter interference, does not change links, DB() will change links.
	var u2 []Users
	err = db.Limit(10).Offset(1).Select()
	fmt.Println(u2)
	
	// count
	var count int64
	// Here reset clears the parameter interference of the upper query and can count all the data. If it is not clear, the condition is the condition of the upper query.
	// At the same time, DB () can be called new, without interference.
	count,err = db.Reset().Count()
	// or
	count, err = DB().Table(&u).Count()
	fmt.Println(count, err)
}

Advanced Usage

  • Chunk Data Fragmentation, Mass Data Batch Processing (Cumulative Processing)

    When a large amount of data needs to be manipulated, the chunk method can be used if it is unreasonable to take it out at one time and then operate it again. The first parameter of chunk is the amount of data specified for a single operation. According to the volume of business, 100 or 1000 can be selected. The second parameter of chunk is a callback method for writing normal data processing logic The goal is to process large amounts of data senselessly The principle of implementation is that each operation automatically records the current operation position, and the next time the data is retrieved again, the data is retrieved from the current position.

    User := db.Table("users")
    User.Fields("id, name").Where("id",">",2).Chunk(2, func(data []map[string]interface{}) {
        // for _,item := range data {
        // 	   fmt.Println(item)
        // }
        fmt.Println(data)
    })
    
    // print result:  
    // 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 Data fragmentation, mass data batch processing (from scratch)

    Similar to chunk method, the implementation principle is that every operation is to fetch data from the beginning. Reason: When we change data, the result of the change may affect the result of our data taking as where condition, so we can use Loop.

    User := db.Table("users")
    User.Fields("id, name").Where("id",">",2).Loop(2, func(data []map[string]interface{}) {
        // for _,item := range data {
        // 	   fmt.Println(item)
        // }
        // here run update / delete  
    })
    
  • where nested

    // 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()
    

realease log

  • v2.1.x:
    • update join with auto table prefix
    • add query return with []map[string]interface{}
  • v2.0.0: new version, new structure

Upgrade Guide

from 2.0.x to 2.1.x
  • change xxx.Join("pre_tablename") into xxx.Join("tablename"),the join table name auto prefix
  • change err:=DB().Bind().Query() into res,err:=DB().Query() with multi return,leave the Bind() method as well
from 1.x to 2.x, install it for new

pay me a coffee

wechat alipay paypal: click
  • pay list
total avator
¥100

Documentation

Index

Constants

View Source
const (
	VERSION_TEXT = "\ngolang orm of gorose's version : "
	VERSION_NO   = "v2.1.0"
	VERSION      = VERSION_TEXT + VERSION_NO + GOROSE_IMG
)
View Source
const (
	DriverOracle = "oci8" // 默认驱动
)
View Source
const GOROSE_IMG = `` /* 772-byte string literal not displayed */

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",
}
View Source
var IGNORE = "-"
View Source
var TAGNAME = "gorose"

Functions

func DefaultLogger

func DefaultLogger() func(e *Engin)

func GetErr

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

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{}

Types

type BindType

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

func (BindType) String

func (b BindType) String() 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
}

func (*Binder) BindParse

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

func (*Binder) GetBindAll

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

func (*Binder) GetBindFields

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

func (*Binder) GetBindName

func (o *Binder) GetBindName() string

func (*Binder) GetBindOrigin

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

func (*Binder) GetBindPrefix

func (o *Binder) GetBindPrefix() string

func (*Binder) GetBindResult

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

func (*Binder) GetBindResultSlice

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

func (*Binder) GetBindType

func (o *Binder) GetBindType() BindType

func (*Binder) ResetBindResultSlice

func (o *Binder) ResetBindResultSlice()

func (*Binder) SetBindAll

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

func (*Binder) SetBindFields

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

func (*Binder) SetBindName

func (o *Binder) SetBindName(arg string)

func (*Binder) SetBindOrigin

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

func (*Binder) SetBindPrefix

func (o *Binder) SetBindPrefix(arg string)

func (*Binder) SetBindResult

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

func (*Binder) SetBindResultSlice

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

func (*Binder) SetBindType

func (o *Binder) SetBindType(arg BindType)

type BuilderClickhouse

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

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

type BuilderDefault

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

func NewBuilderDefault

func NewBuilderDefault(o IOrm) *BuilderDefault

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)

func (*BuilderDefault) BuildDistinct

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

func (*BuilderDefault) BuildExecute

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

BuildExecut : build execute query string

func (*BuilderDefault) BuildFields

func (b *BuilderDefault) BuildFields() string

func (*BuilderDefault) BuildGroup

func (b *BuilderDefault) BuildGroup() string

func (*BuilderDefault) BuildHaving

func (b *BuilderDefault) BuildHaving() string

func (*BuilderDefault) BuildJoin

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

func (*BuilderDefault) BuildLimit

func (b *BuilderDefault) BuildLimit() string

func (*BuilderDefault) BuildOffset

func (b *BuilderDefault) BuildOffset() string

func (*BuilderDefault) BuildOrder

func (b *BuilderDefault) BuildOrder() string

func (*BuilderDefault) BuildQuery

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

func (*BuilderDefault) BuildTable

func (b *BuilderDefault) BuildTable() string

func (*BuilderDefault) BuildWhere

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

func (*BuilderDefault) GetOperator

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

func (*BuilderDefault) GetPlaceholder

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

GetPlaceholder 获取占位符

func (*BuilderDefault) SetDriver

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

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

type BuilderDriver

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

func NewBuilderDriver

func NewBuilderDriver() *BuilderDriver

func (*BuilderDriver) Getter

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

func (*BuilderDriver) Register

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

type BuilderMsSql

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

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

type BuilderMysql

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

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

type BuilderOracle

type BuilderOracle struct {
	BuilderDefault
}

func NewBuilderOracle

func NewBuilderOracle(o IOrm) *BuilderOracle

func (*BuilderOracle) BuildData

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

func (*BuilderOracle) BuildData2

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

func (*BuilderOracle) BuildDistinct

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

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)

func (*BuilderOracle) BuildFields

func (b *BuilderOracle) BuildFields() string

func (*BuilderOracle) BuildGroup

func (b *BuilderOracle) BuildGroup() string

func (*BuilderOracle) BuildHaving

func (b *BuilderOracle) BuildHaving() string

func (*BuilderOracle) BuildJoin

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

func (*BuilderOracle) BuildLimit

func (b *BuilderOracle) BuildLimit() string

func (*BuilderOracle) BuildOffset

func (b *BuilderOracle) BuildOffset() string

func (*BuilderOracle) BuildOrder

func (b *BuilderOracle) BuildOrder() string

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)

func (*BuilderOracle) BuildTable

func (b *BuilderOracle) BuildTable() string

func (*BuilderOracle) BuildWhere

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

func (*BuilderOracle) GetOperator

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

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
}

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

type BuilderSqlite3

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

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

type Config

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

type ConfigCluster

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

type Data

type Data map[string]interface{}

type Engin

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

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)

func (*Engin) GetDriver

func (c *Engin) GetDriver() string

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

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) 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))

type Err

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

func NewErr

func NewErr() *Err

func (*Err) Default

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

func (*Err) Get

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

func (*Err) GetLang

func (e *Err) GetLang() Lang

func (*Err) Register

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

func (*Err) SetLang

func (e *Err) SetLang(l Lang)

type Error

type Error uint
const (
	ERR_PARAMS_COUNTS Error = iota
	ERR_PARAMS_MISSING
	ERR_PARAMS_FORMAT
)

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
}

func NewBinder

func NewBinder(o ...interface{}) IBinder

type IBuilder

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

func NewBuilder

func NewBuilder(driver string) IBuilder

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
	GetLogger() ILogger
	GetDriver() string
}

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
}

type IOrm

type IOrm interface {
	IOrmApi
	IOrmQuery
	IOrmExecute
	IOrmSession
	//ISession
	Hello()
	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
	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
	ResetWhere() IOrm
	GetISession() ISession
	// 悲观锁使用
	// sharedLock(lock in share mode) 不会阻塞其它事务读取被锁定行记录的值
	SharedLock() *Orm
	// 此外你还可以使用 lockForUpdate 方法。“for update”锁避免选择行被其它共享锁修改或删除:
	// 会阻塞其他锁定性读对锁定行的读取(非锁定性读仍然可以读取这些记录,lock in share mode 和 for update 都是锁定性读)
	LockForUpdate() *Orm
	ResetUnion() 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
}

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
}

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() (res Data, err error)
	// 组块结果集
	// 如果你需要处理成千上万或者更多条数据库记录,可以考虑使用 chunk 方法,该方法一次获取结果集的一小块,
	// 然后传递每一小块数据到闭包函数进行处理,该方法在编写处理大量数据库记录的 Artisan 命令的时候非常有用。
	// 例如,我们可以将处理全部 users 表数据分割成一次处理 100 条记录的小组块
	// 你可以通过从闭包函数中返回 err 来终止组块的运行
	Chunk(limit int, callback func([]Data) error) (err error)
	Loop(limit int, callback func([]Data) error) (err error)
}

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{}
}

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
}

func NewSession

func NewSession(e IEngin) ISession

NewSession : 初始化 Session

type Lang

type Lang uint
const (
	CHINESE Lang = iota
	ENGLISH
	CHINESE_TRADITIONAL
)

func (Lang) String

func (l Lang) String() string

type LogLevel

type LogLevel uint
const (
	LOG_SQL LogLevel = iota
	LOG_SLOW
	LOG_ERROR
)

func (LogLevel) String

func (l LogLevel) String() string

type LogOption

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

type Logger

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

func NewLogger

func NewLogger(o *LogOption) *Logger

func (*Logger) EnableErrorLog

func (l *Logger) EnableErrorLog() bool

func (*Logger) EnableSlowLog

func (l *Logger) EnableSlowLog() float64

func (*Logger) EnableSqlLog

func (l *Logger) EnableSqlLog() bool

func (*Logger) Error

func (l *Logger) Error(msg string)

func (*Logger) Slow

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

func (*Logger) Sql

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

type Map

type Map t.MapString

type Orm

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

func NewOrm

func NewOrm(e IEngin) *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) ClearBindValues

func (dba *Orm) ClearBindValues()

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

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{}

func (*Orm) GetData

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

func (*Orm) GetDistinct

func (o *Orm) GetDistinct() bool

func (*Orm) GetDriver

func (dba *Orm) GetDriver() string

func (*Orm) GetExtraCols

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

func (*Orm) GetFields

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

func (*Orm) GetForce

func (dba *Orm) GetForce() bool

func (*Orm) GetGroup

func (o *Orm) GetGroup() string

func (*Orm) GetHaving

func (o *Orm) GetHaving() string

func (*Orm) GetISession

func (dba *Orm) GetISession() ISession

func (*Orm) GetJoin

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

func (*Orm) GetLimit

func (o *Orm) GetLimit() int

func (*Orm) GetOffset

func (o *Orm) GetOffset() int

func (*Orm) GetOrder

func (o *Orm) GetOrder() string

func (*Orm) GetPessimisticLock

func (dba *Orm) GetPessimisticLock() string

func (*Orm) GetTable

func (o *Orm) GetTable() string

func (*Orm) GetWhere

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

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) Hello

func (dba *Orm) Hello()

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

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

func (*Orm) OrWhereIn

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

func (*Orm) OrWhereNotBetween

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

func (*Orm) OrWhereNotIn

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

func (*Orm) OrWhereNotNull

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

func (*Orm) OrWhereNull

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

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() (res Data, err error)

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

{
	"total": 50,
	"per_page": 15,
	"current_page": 1,
	"last_page": 4,
	"first_page_url": "http://laravel.app?page=1",
	"last_page_url": "http://laravel.app?page=4",
	"next_page_url": "http://laravel.app?page=2",
	"prev_page_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) Reset

func (dba *Orm) Reset() IOrm

Reset orm api and bind values reset to init

func (*Orm) ResetExtraCols

func (dba *Orm) ResetExtraCols() IOrm

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

func (*Orm) Select

func (dba *Orm) Select() error

Get : select more rows , relation limit set

func (*Orm) SetBindValues

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

func (*Orm) SetISession

func (dba *Orm) SetISession(is ISession)

func (*Orm) SetWhere

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

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 (s *Orm) Transaction(closers ...func(db IOrm) error) (err error)

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)

Get : select more rows , relation limit set

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

func (*Orm) WhereIn

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

func (*Orm) WhereNotBetween

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

func (*Orm) WhereNotIn

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

func (*Orm) WhereNotNull

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

func (*Orm) WhereNull

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

type OrmApi

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

type Session

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

func (*Session) Begin

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

func (*Session) Bind

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

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

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

func (*Session) Close

func (s *Session) Close()

Close : 关闭 Session

func (*Session) Commit

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

func (*Session) Execute

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

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{}

func (*Session) LastInsertId

func (s *Session) LastInsertId() int64

func (*Session) LastSql

func (s *Session) LastSql() string

func (*Session) Query

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

func (*Session) ResetBinderResult

func (s *Session) ResetBinderResult()

GetBinder 获取绑定对象

func (*Session) Rollback

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

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)

func (*Session) SetUnion

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

func (*Session) Transaction

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

Jump to

Keyboard shortcuts

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