GoMybatis

package module
v6.5.6+incompatible Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2020 License: Apache-2.0 Imports: 18 Imported by: 0

README

SQL mapper ORM framework for Golang

Go Report Card Build Status GoDoc Coverage Status codecov

Image text

Please read the documentation website carefully when using the tutorial. DOC

Powerful Features

  • High Performance,The maximum number of transactions per second of a single computer can reach 751020 Tps/s, and the total time consumed is 0.14s (test environment returns simulated SQL data, concurrently 1000, total 100000, 6-core 16GB win10)
  • Painless migration from Java to go,Compatible with most Java(Mybatis3,Mybatis Plus) ,Painless migration of XML SQL files from Java Spring Mybatis to Go language(Modify only the javaType of resultMap to specify go language type for langType)
  • Declarative transaction/AOP transaction/transaction BehaviorOnly one line Tag is needed to define AOP transactions and transaction propagation behavior
  • Extensible Log InterfaceAsynchronous message queue day, SQL log in framework uses cached channel to realize asynchronous message queue logging
  • dynamic sql,contains 15 utilities Features<select>,<update>,<insert>,<delete>,<trim>,<if>,<set>,<where>,<foreach>,<resultMap>,<bind>,<choose><when><otherwise>,<sql><include>
  • Intelligent expressionProcessing dynamic judgment and computation tasks(such as:#{foo.Bar}#{arg+1}#{arg*1}#{arg/1}#{arg-1}),For example, write fuzzy queries select * from table where phone like #{phone+'%'}(Note the post-percentile query run in index)
  • Dynamic Data SourceMultiple data sources can be customized to dynamically switch multiple database instances
  • Template label(new)One line of code to achieve add, delete, modify, delete logic, optimistic lock, but also retain perfect scalability (tag body can continue to expand SQL logic)
  • Optimistic Lock(new)<updateTemplete>Optimistic locks to prevent concurrent competition to modify records as much as possible
  • Logical deletion(new)<insertTemplete><updateTemplete><deleteTemplete><selectTemplete>Logical deletion, prevent accidental deletion of data, data recovery is simple
  • RPC/MVC Component Support(new)To make the service perfect for RPC (reducing parameter restrictions), dynamic proxy, transaction subscription, easy integration and extension of micro services, click on the link https://github.com/zhuxiujia/easyrpc

Database Driver support table

 //Traditional database
 Mysql:                             github.com/go-sql-driver/mysql
 MyMysql:                           github.com/ziutek/mymysql/godrv
 Postgres:                          github.com/lib/pq
 SQLite:                            github.com/mattn/go-sqlite3
 MsSql:                             github.com/denisenkom/go-mssqldb
 Oracle:                            github.com/mattn/go-oci8
 //Distributed NewSql database
 Tidb:                              github.com/go-sql-driver/mysql
 CockroachDB:                       github.com/lib/pq

Use tutorials

Tutorial source code https://github.com/zhuxiujia/GoMybatis/tree/master/example

  • GoPath use, download GoMybatis and the corresponding database driver with the go get command
go get github.com/zhuxiujia/GoMybatis
go get github.com/go-sql-driver/mysql
  • Go mod use
//go.mod加入依赖
require (
	github.com/go-sql-driver/mysql v1.5.0
	github.com/zhuxiujia/GoMybatis v6.5.6+incompatible
)

In practice, we use mapper to define the content of xml. It is suggested that the * Mapper. XML file be stored in the project directory. When editing xml, we can enjoy IDE rendering and intelligent prompts such as GoLand. Production environments can use statikFS to package XML files in the process

  • main.go
var xmlBytes = []byte(`
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://raw.githubusercontent.com/zhuxiujia/GoMybatis/master/mybatis-3-mapper.dtd">
<mapper>
    <select id="SelectAll">
        select * from biz_activity where delete_flag=1 order by create_time desc
    </select>
</mapper>
`)
import (
	"fmt"
	_ "github.com/go-sql-driver/mysql" //Select the required database-driven imports
	"github.com/zhuxiujia/GoMybatis"
)
type ExampleActivityMapperImpl struct {
     SelectAll  func() ([]Activity, error)
}

func main() {
    var engine = GoMybatis.GoMybatisEngine{}.New()
	//Mysql link format user name: password @ (database link address: port)/database name, such as root: 123456 @(***.com: 3306)/test
	err := engine.Open("mysql", "*?charset=utf8&parseTime=True&loc=Local")
	if err != nil {
	   panic(err)
	}
	var exampleActivityMapperImpl ExampleActivityMapperImpl
	
	//Loading XML implementation logic to ExampleActivity Mapper Impl
	engine.WriteMapperPtr(&exampleActivityMapperImpl, xmlBytes)

	//use mapper
	result, err := exampleActivityMapperImpl.SelectAll(&result)
        if err != nil {
	   panic(err)
	}
	fmt.Println(result)
}

Features: Template tag CRUD simplification (must rely on a resultMap tag)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://raw.githubusercontent.com/zhuxiujia/GoMybatis/master/mybatis-3-mapper.dtd">
<mapper>
    <!--logic_enable -->
    <!--logic_deleted -->
    <!--logic_undelete  -->
    <!--version_enable support int,int8,int16,int32,int64-->
    <resultMap id="BaseResultMap" tables="biz_activity">
        <id column="id" langType="string"/>
        <result column="name" langType="string"/>
        <result column="pc_link" langType="string"/>
        <result column="h5_link" langType="string"/>
        <result column="remark" langType="string"/>
        <result column="sort" langType="int"/>
        <result column="status" langType="status"/>
        <result column="version" langType="int"
                version_enable="true"/>
        <result column="create_time" langType="time.Time"/>
        <result column="delete_flag" langType="int"
                logic_enable="true"
                logic_undelete="1"
                logic_deleted="0"/>
    </resultMap>

    <!--模板标签: columns wheres sets 支持逗号,分隔表达式,*?* 为判空表达式-->

    <!--插入模板:默认id="insertTemplete,test="field != null",where自动设置逻辑删除字段,支持批量插入" -->
    <insertTemplete/>
    <!--查询模板:默认id="selectTemplete,where自动设置逻辑删除字段-->
    <selectTemplete wheres="name?name = #{name}"/>
    <!--更新模板:默认id="updateTemplete,set自动设置乐观锁版本号-->
    <updateTemplete sets="name?name = #{name},remark?remark=#{remark}" wheres="id?id = #{id}"/>
    <!--删除模板:默认id="deleteTemplete,where自动设置逻辑删除字段-->
    <deleteTemplete wheres="name?name = #{name}"/>
</mapper>    

XML corresponds to the Mapper structure method defined below

type Activity struct {
	Id         string    `json:"id"`
	Uuid       string    `json:"uuid"`
	Name       string    `json:"name"`
	PcLink     string    `json:"pcLink"`
	H5Link     string    `json:"h5Link"`
	Remark     string    `json:"remark"`
	Version    int       `json:"version"`
	CreateTime time.Time `json:"createTime"`
	DeleteFlag int       `json:"deleteFlag"`
}
type ExampleActivityMapper struct {
	SelectTemplete      func(name string) ([]Activity, error) `args:"name"`
	InsertTemplete      func(arg Activity) (int64, error)
	InsertTempleteBatch func(args []Activity) (int64, error) `args:"args"`
	UpdateTemplete      func(arg Activity) (int64, error)    `args:"name"`
	DeleteTemplete      func(name string) (int64, error)     `args:"name"`
}

Features:Dynamic Data Source

        //To add a second MySQL database, change Mysql Uri to your second data source link
	GoMybatis.Open("mysql", MysqlUri)
	//Dynamic Data Source Routing
	var router = GoMybatis.GoMybatisDataSourceRouter{}.New(func(mapperName string) *string {
		//Point to the data source according to the packet name routing
		if strings.Contains(mapperName, "example.") {
			var url = MysqlUri//The second MySQL database, please change Mysql Uri to your second data source link
			fmt.Println(url)
			return &url
		}
		return nil
	})

Features:Custom log output

	engine.SetLogEnable(true)
	engine.SetLog(&GoMybatis.LogStandard{
		PrintlnFunc: func(messages []byte) {
		  //do someting save messages
		},
	})

Features:Asynchronous log interface (customizable log output)

Image text

Features:Transaction Propagation Processor (Nested Transactions)

Transaction type Explain
PROPAGATION_REQUIREDRepresents that if the current transaction exists, the current transaction is supported. Otherwise, a new transaction will be started. Default transaction type.
PROPAGATION_SUPPORTSRepresents that if the current transaction exists, the current transaction is supported, and if there is no transaction at present, it is executed in a non-transactional manner.
PROPAGATION_MANDATORYRepresents that if the current transaction exists, the current transaction is supported, and if no transaction exists, the transaction nesting error is returned.
PROPAGATION_REQUIRES_NEWRepresents that a new Session opens a new transaction and suspends the current transaction if it currently exists.
PROPAGATION_NOT_SUPPORTEDRepresents that an operation is performed in a non-transactional manner. If a transaction exists, a new Session is created to perform the operation in a non-transactional manner, suspending the current transaction.
PROPAGATION_NEVERRepresents that an operation is executed in a non-transactional manner and returns a transaction nesting error if a transaction currently exists.
PROPAGATION_NESTEDRepresents that if the current transaction exists, it will be executed within the nested transaction. If the nested transaction rolls back, it will only roll back within the nested transaction and will not affect the current transaction. If there is no transaction at the moment, do something similar to PROPAGATION_REQUIRED.
PROPAGATION_NOT_REQUIREDRepresents that if there is currently no transaction, a new transaction will be created, otherwise an error will be returned.
//Nested transaction services
type TestService struct {
   exampleActivityMapper *ExampleActivityMapper //The service contains a mapper operation database similar to Java spring MVC
   UpdateName   func(id string, name string) error   `tx:"" rollback:"error"`
   UpdateRemark func(id string, remark string) error `tx:"" rollback:"error"`
}
func main()  {
   var testService TestService
   testService = TestService{
   	exampleActivityMapper: &exampleActivityMapper,
   	UpdateRemark: func(id string, remark string) error {
   		testService.exampleActivityMapper.SelectByIds([]string{id})
   		panic(errors.New("Business exceptions")) // panic Triggered transaction rollback strategy
   		return nil                   // rollback:"error" A transaction rollback policy is triggered if the error type is returned and is not nil
   	},
   	UpdateName: func(id string, name string) error {
   		testService.exampleActivityMapper.SelectByIds([]string{id})
   		return nil
   	},
   }
   GoMybatis.AopProxyService(&testService, &engine)//Func must use AOP proxy service
   testService.UpdateRemark("1","remark")
}

Features:XML/Mapper Generator - Generate * mapper. XML from struct structure

  //step1 To define your database model, you must include JSON annotations (default database fields), gm:"" annotations specifying whether the value is id, version optimistic locks, and logic logic soft deletion.
  type UserAddress struct {
	Id            string `json:"id" gm:"id"`
	UserId        string `json:"user_id"`
	RealName      string `json:"real_name"`
	Phone         string `json:"phone"`
	AddressDetail string `json:"address_detail"`

	Version    int       `json:"version" gm:"version"`
	CreateTime time.Time `json:"create_time"`
	DeleteFlag int       `json:"delete_flag" gm:"logic"`
}
  • Step 2: Create an Xml CreateTool. go in the main directory of your project as follows
func main() {
	var bean = UserAddress{} //Here's just an example, which should be replaced by your own database model
	GoMybatis.OutPutXml(reflect.TypeOf(bean).Name()+"Mapper.xml", GoMybatis.CreateXml("biz_"+GoMybatis.StructToSnakeString(bean), bean))
}
  • Third, execute the command to get the UserAddressMapper. XML file in the current directory
go run XmlCreateTool.go
  • The following is the content of the automatically generated XML file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://raw.githubusercontent.com/zhuxiujia/GoMybatis/master/mybatis-3-mapper.dtd">
<mapper>
    <!--logic_enable Logical Delete Fields-->
    <!--logic_deleted Logically delete deleted fields-->
    <!--logic_undelete Logically Delete Undeleted Fields-->
    <!--version_enable Optimistic lock version field, support int, int8, int16, int32, Int64-->
    <resultMap id="BaseResultMap" tables="biz_user_address">
    <id column="id" property="id"/>
	<result column="id" property="id" langType="string"   />
	<result column="user_id" property="user_id" langType="string"   />
	<result column="real_name" property="real_name" langType="string"   />
	<result column="phone" property="phone" langType="string"   />
	<result column="address_detail" property="address_detail" langType="string"   />
	<result column="version" property="version" langType="int" version_enable="true"  />
	<result column="create_time" property="create_time" langType="Time"   />
	<result column="delete_flag" property="delete_flag" langType="int"  logic_enable="true" logic_undelete="1" logic_deleted="0" />
    </resultMap>
</mapper>

Components (RPC, JSONRPC, Consul) - With GoMybatis

Please pay attention to the version in time, upgrade the version in time (new features, bug fix). For projects using GoMybatis, please leave your project name + contact information in Issues.

Welcome to Star or Wechat Payment Sponsorship at the top right corner~

Image text

Documentation

Index

Constants

View Source
const Adapter_FormateDate = `2006-01-02 15:04:05`
View Source
const DefaultOneArg = `arg`

默认参数前缀,例如arg0 arg1 arg2 ....

View Source
const Element_Mapper = "mapper"
View Source
const GoMybatis_Session = `GoMybatis.Session`
View Source
const GoMybatis_Session_Ptr = `*GoMybatis.Session`
View Source
const GoMybatis_Time = `time.Time`
View Source
const GoMybatis_Time_Ptr = `*time.Time`
View Source
const ID = `id`
View Source
const NewSessionFunc = "NewSession" //NewSession method,auto write implement body code

Variables

View Source
var (
	IntType   = reflect.TypeOf(c_INT_DEFAULT)
	Int8Type  = reflect.TypeOf(c_INT8_DEFAULT)
	Int16Type = reflect.TypeOf(c_INT16_DEFAULT)
	Int32Type = reflect.TypeOf(c_INT32_DEFAULT)
	Int64Type = reflect.TypeOf(c_INT64_DEFAULT)

	UintType   = reflect.TypeOf(c_UINT_DEFAULT)
	Uint8Type  = reflect.TypeOf(c_UINT8_DEFAULT)
	Uint16Type = reflect.TypeOf(c_UINT16_DEFAULT)
	Uint32Type = reflect.TypeOf(c_UINT32_DEFAULT)
	Uint64Type = reflect.TypeOf(c_UINT64_DEFAULT)

	Float32Type = reflect.TypeOf(c_FLOAT32_DEFAULT)
	Float64Type = reflect.TypeOf(c_FLOAT64_DEFAULT)

	Complex64Type  = reflect.TypeOf(c_COMPLEX64_DEFAULT)
	Complex128Type = reflect.TypeOf(c_COMPLEX128_DEFAULT)

	StringType = reflect.TypeOf(c_EMPTY_STRING)
	BoolType   = reflect.TypeOf(c_BOOL_DEFAULT)
	ByteType   = reflect.TypeOf(c_BYTE_DEFAULT)
	BytesType  = reflect.SliceOf(ByteType)

	TimeType = reflect.TypeOf(c_TIME_DEFAULT)
)
View Source
var (
	PtrIntType   = reflect.PtrTo(IntType)
	PtrInt8Type  = reflect.PtrTo(Int8Type)
	PtrInt16Type = reflect.PtrTo(Int16Type)
	PtrInt32Type = reflect.PtrTo(Int32Type)
	PtrInt64Type = reflect.PtrTo(Int64Type)

	PtrUintType   = reflect.PtrTo(UintType)
	PtrUint8Type  = reflect.PtrTo(Uint8Type)
	PtrUint16Type = reflect.PtrTo(Uint16Type)
	PtrUint32Type = reflect.PtrTo(Uint32Type)
	PtrUint64Type = reflect.PtrTo(Uint64Type)

	PtrFloat32Type = reflect.PtrTo(Float32Type)
	PtrFloat64Type = reflect.PtrTo(Float64Type)

	PtrComplex64Type  = reflect.PtrTo(Complex64Type)
	PtrComplex128Type = reflect.PtrTo(Complex128Type)

	PtrStringType = reflect.PtrTo(StringType)
	PtrBoolType   = reflect.PtrTo(BoolType)
	PtrByteType   = reflect.PtrTo(ByteType)

	PtrTimeType = reflect.PtrTo(TimeType)
)

Functions

func AopProxyService

func AopProxyService(service interface{}, engine SessionEngine)

使用AOP切面 代理目标服务,如果服务painc()它的事务会回滚 默认为单协程模型,如果是多协程调用的情况请开启engine.SetGoroutineIDEnable(true)

func AopProxyServiceValue

func AopProxyServiceValue(service reflect.Value, engine SessionEngine)

使用AOP切面 代理目标服务,如果服务painc()它的事务会回滚

func CreateXml

func CreateXml(tableName string, bean interface{}) []byte

* //例子

//GoMybatis当前是以xml内容为主gm:""注解只是生成xml的时候使用 //定义数据库模型, gm:"id"表示输出id的xml,gm:"version"表示为输出版本号的xml,gm:"logic"表示输出逻辑删除xml

type TestActivity struct {
	Id         string    `json:"id" gm:"id"`
	Uuid       string    `json:"uuid"`
	Name       string    `json:"name"`
	PcLink     string    `json:"pcLink"`
	H5Link     string    `json:"h5Link"`
	Remark     string    `json:"remark"`
	Version    int       `json:"version" gm:"version"`
	CreateTime time.Time `json:"createTime"`
	DeleteFlag int       `json:"deleteFlag" gm:"logic"`
}
func TestUserAddres(t *testing.T)  {
	var s=utils.CreateDefaultXml("biz_user_address",TestActivity{})//创建xml内容
	utils.OutPutXml("D:/GOPATH/src/dao/ActivityMapper.xml",[]byte(s))//写入磁盘
}

根据结构体 创建xml文件.注意 结构体json对应的是数据库的column

func LoadMapperXml

func LoadMapperXml(bytes []byte) (items map[string]etree.Token)

func OutPutXml

func OutPutXml(fileName string, body []byte)

输出文件

func Proxy

func Proxy(proxyPtr interface{}, buildFunc func(funcField reflect.StructField, field reflect.Value) func(arg ProxyArg) []reflect.Value)

AopProxy 可写入每个函数代理方法.proxyPtr:代理对象指针,buildFunc:构建代理函数

func ProxyValue

func ProxyValue(mapperValue reflect.Value, buildFunc func(funcField reflect.StructField, field reflect.Value) func(arg ProxyArg) []reflect.Value)

AopProxy 可写入每个函数代理方法

func SnakeString

func SnakeString(s string) string

转蛇形命名snake string, XxYy to xx_yy , XxYY to xx_yy

func StructToSnakeString

func StructToSnakeString(arg interface{}) string

结构体名称转蛇形名称 例如 pcLink = pc_link

func WriteMapper

func WriteMapper(bean reflect.Value, xml []byte, sessionEngine SessionEngine)

写入方法内容,例如

type ExampleActivityMapperImpl struct {
	SelectAll         func(result *[]Activity) error
	SelectByCondition func(name string, startTime time.Time, endTime time.Time, page int, size int, result *[]Activity) error `args:"name,startTime,endTime,page,size"`
	UpdateById        func(session *GoMybatis.Session, arg Activity, result *int64) error                                     //只要参数中包含有*GoMybatis.Session的类型,框架默认使用传入的session对象,用于自定义事务
	Insert            func(arg Activity, result *int64) error
	CountByCondition  func(name string, startTime time.Time, endTime time.Time, result *int) error `args:"name,startTime,endTime"`
}

func的基本类型的参数(例如string,int,time.Time,int64,float....)个数无限制(并且需要用Tag指定参数名逗号隔开,例如`args:"id,phone"`),返回值必须有error func的结构体参数无需指定args的tag,框架会自动扫描它的属性,封装为map处理掉 使用WriteMapper函数设置代理后即可正常使用。

func WriteMapperByValue

func WriteMapperByValue(value reflect.Value, xml []byte, sessionEngine SessionEngine)

推荐默认使用单例传入 根据sessionEngine写入到mapperPtr,value:指向mapper指针反射对象,xml:xml数据,sessionEngine:session引擎,enableLog:是否允许日志输出,log:日志实现

func WriteMapperPtrByEngine

func WriteMapperPtrByEngine(ptr interface{}, xml []byte, sessionEngine SessionEngine)

推荐默认使用单例传入 根据sessionEngine写入到mapperPtr,ptr:指向mapper指针,xml:xml数据,sessionEngine:session引擎,enableLog:是否允许日志输出,log:日志实现

Types

type DataSourceRouter

type DataSourceRouter interface {
	//路由规则
	//参数:mapperName mapper文件包名+名称例如(example.ExampleActivityMapper)
	//返回(session,error)路由选择后的session,error异常
	Router(mapperName string, engine SessionEngine) (Session, error)
	//设置sql.DB,该方法会被GoMybatis框架内调用
	SetDB(driverName string, url string, db *sql.DB)

	Name() string
}

数据源路由接口

type ElementType

type ElementType = string
const (
	//root elements
	Element_ResultMap ElementType = "resultMap"
	Element_Insert    ElementType = "insert"
	Element_Delete    ElementType = "delete"
	Element_Update    ElementType = `update`
	Element_Select    ElementType = "select"
	Element_Sql       ElementType = "sql"

	//root templete elements
	Element_Insert_Templete ElementType = "insertTemplete"
	Element_Delete_Templete ElementType = "deleteTemplete"
	Element_Update_Templete ElementType = `updateTemplete`
	Element_Select_Templete ElementType = "selectTemplete"

	//child elements
	Element_bind      ElementType = "bind"
	Element_String    ElementType = "string"
	Element_If        ElementType = `if`
	Element_Trim      ElementType = "trim"
	Element_Foreach   ElementType = "foreach"
	Element_Set       ElementType = "set"
	Element_choose    ElementType = "choose"
	Element_when      ElementType = "when"
	Element_otherwise ElementType = "otherwise"
	Element_where     ElementType = "where"
	Element_Include   ElementType = "include"
)

type ExpressionEngineLexerCache

type ExpressionEngineLexerCache interface {
	Set(expression string, lexer interface{}) error
	Get(expression string) (interface{}, error)
	Name() string
}

Lexer 结果缓存

type ExpressionEngineLexerCacheable

type ExpressionEngineLexerCacheable interface {
	SetUseLexerCache(use bool) error
	LexerCacheable() bool
}

type ExpressionEngineLexerMapCache

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

func (*ExpressionEngineLexerMapCache) Get

func (it *ExpressionEngineLexerMapCache) Get(expression string) (interface{}, error)

func (*ExpressionEngineLexerMapCache) Name

func (ExpressionEngineLexerMapCache) New

func (*ExpressionEngineLexerMapCache) Set

func (it *ExpressionEngineLexerMapCache) Set(expression string, lexer interface{}) error

type ExpressionEngineProxy

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

func (*ExpressionEngineProxy) Eval

func (it *ExpressionEngineProxy) Eval(lexerResult interface{}, arg interface{}, operation int) (interface{}, error)

执行一个表达式 参数:lexerResult=编译结果,arg=参数 返回:执行结果,错误

func (*ExpressionEngineProxy) Lexer

func (it *ExpressionEngineProxy) Lexer(expression string) (interface{}, error)

编译一个表达式 参数:lexerArg 表达式内容 返回:interface{} 编译结果,error 错误

func (*ExpressionEngineProxy) LexerAndEval

func (it *ExpressionEngineProxy) LexerAndEval(expression string, arg interface{}) (interface{}, error)

执行

func (*ExpressionEngineProxy) LexerCache

func (*ExpressionEngineProxy) LexerCacheable

func (it *ExpressionEngineProxy) LexerCacheable() bool

func (ExpressionEngineProxy) Name

func (it ExpressionEngineProxy) Name() string

引擎名称

func (ExpressionEngineProxy) New

engine :表达式引擎,useLexerCache:是否缓存Lexer表达式编译结果

func (*ExpressionEngineProxy) SetExpressionEngine

func (it *ExpressionEngineProxy) SetExpressionEngine(engine ast.ExpressionEngine)

引擎名称

func (*ExpressionEngineProxy) SetLexerCache

func (it *ExpressionEngineProxy) SetLexerCache(cache ExpressionEngineLexerCache)

func (*ExpressionEngineProxy) SetUseLexerCache

func (it *ExpressionEngineProxy) SetUseLexerCache(isUseCache bool) error

type GoMybatisDataSourceRouter

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

动态数据源路由

func (*GoMybatisDataSourceRouter) Name

func (it *GoMybatisDataSourceRouter) Name() string

func (GoMybatisDataSourceRouter) New

func (it GoMybatisDataSourceRouter) New(routerFunc func(mapperName string) *string) GoMybatisDataSourceRouter

初始化路由,routerFunc为nil或者routerFunc返回nil,则框架自行选择第一个数据库作为数据源

func (*GoMybatisDataSourceRouter) Router

func (it *GoMybatisDataSourceRouter) Router(mapperName string, engine SessionEngine) (Session, error)

func (*GoMybatisDataSourceRouter) SetDB

func (it *GoMybatisDataSourceRouter) SetDB(driverType string, driverLink string, db *sql.DB)

type GoMybatisEngine

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

func (*GoMybatisEngine) DataSourceRouter

func (it *GoMybatisEngine) DataSourceRouter() DataSourceRouter

func (*GoMybatisEngine) ExpressionEngine

func (it *GoMybatisEngine) ExpressionEngine() ast.ExpressionEngine

表达式执行引擎

func (*GoMybatisEngine) GoroutineIDEnable

func (it *GoMybatisEngine) GoroutineIDEnable() bool

func (*GoMybatisEngine) GoroutineSessionMap

func (it *GoMybatisEngine) GoroutineSessionMap() *GoroutineSessionMap

func (*GoMybatisEngine) IsPrintWarning

func (it *GoMybatisEngine) IsPrintWarning() bool

func (*GoMybatisEngine) Log

func (it *GoMybatisEngine) Log() Log

获取日志实现类

func (*GoMybatisEngine) LogEnable

func (it *GoMybatisEngine) LogEnable() bool

获取日志实现类,是否启用日志

func (*GoMybatisEngine) LogSystem

func (it *GoMybatisEngine) LogSystem() *LogSystem

func (*GoMybatisEngine) Name

func (it *GoMybatisEngine) Name() string

func (GoMybatisEngine) New

func (*GoMybatisEngine) NewSession

func (it *GoMybatisEngine) NewSession(mapperName string) (Session, error)

func (*GoMybatisEngine) Open

func (it *GoMybatisEngine) Open(driverName, dataSourceLink string) (*sql.DB, error)

打开数据库驱动,初始化连接池放入路由。 sql.DB 就是连接池,可以自定义活跃连接数,具体使用参考官方文档 driverName: 驱动名称例如"mysql", dataSourceName: string 数据库url

func (*GoMybatisEngine) SessionFactory

func (it *GoMybatisEngine) SessionFactory() *SessionFactory

session工厂

func (*GoMybatisEngine) SetDataSourceRouter

func (it *GoMybatisEngine) SetDataSourceRouter(router DataSourceRouter)

func (*GoMybatisEngine) SetExpressionEngine

func (it *GoMybatisEngine) SetExpressionEngine(engine ast.ExpressionEngine)

设置表达式执行引擎

func (*GoMybatisEngine) SetGoroutineIDEnable

func (it *GoMybatisEngine) SetGoroutineIDEnable(enable bool)

func (*GoMybatisEngine) SetLog

func (it *GoMybatisEngine) SetLog(log Log)

设置日志实现类

func (*GoMybatisEngine) SetLogEnable

func (it *GoMybatisEngine) SetLogEnable(enable bool)

设置日志实现类,是否启用日志

func (*GoMybatisEngine) SetPrintWarning

func (it *GoMybatisEngine) SetPrintWarning(print bool)

func (*GoMybatisEngine) SetSessionFactory

func (it *GoMybatisEngine) SetSessionFactory(factory *SessionFactory)

设置session工厂

func (*GoMybatisEngine) SetSqlArgTypeConvert

func (it *GoMybatisEngine) SetSqlArgTypeConvert(convert ast.SqlArgTypeConvert)

设置sql类型转换器

func (*GoMybatisEngine) SetSqlBuilder

func (it *GoMybatisEngine) SetSqlBuilder(builder SqlBuilder)

设置sql构建器

func (*GoMybatisEngine) SetSqlResultDecoder

func (it *GoMybatisEngine) SetSqlResultDecoder(decoder SqlResultDecoder)

设置sql查询结果解析器

func (*GoMybatisEngine) SetTempleteDecoder

func (it *GoMybatisEngine) SetTempleteDecoder(decoder TempleteDecoder)

设置模板解析器

func (*GoMybatisEngine) SqlBuilder

func (it *GoMybatisEngine) SqlBuilder() SqlBuilder

sql构建器

func (*GoMybatisEngine) SqlResultDecoder

func (it *GoMybatisEngine) SqlResultDecoder() SqlResultDecoder

sql查询结果解析器

func (*GoMybatisEngine) TempleteDecoder

func (it *GoMybatisEngine) TempleteDecoder() TempleteDecoder

模板解析器

func (*GoMybatisEngine) WriteMapperPtr

func (it *GoMybatisEngine) WriteMapperPtr(ptr interface{}, xml []byte)

type GoMybatisSqlArgTypeConvert

type GoMybatisSqlArgTypeConvert struct {
}

Sql内容类型转换器

func (GoMybatisSqlArgTypeConvert) Convert

func (it GoMybatisSqlArgTypeConvert) Convert(argValue interface{}) string

Sql内容类型转换器

type GoMybatisSqlBuilder

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

func (*GoMybatisSqlBuilder) BuildSql

func (it *GoMybatisSqlBuilder) BuildSql(paramMap map[string]interface{}, nodes []ast.Node, arg_array *[]interface{}, stmtConvert stmt.StmtIndexConvert) (string, error)

func (*GoMybatisSqlBuilder) EnableLog

func (it *GoMybatisSqlBuilder) EnableLog() bool

func (*GoMybatisSqlBuilder) ExpressionEngineProxy

func (it *GoMybatisSqlBuilder) ExpressionEngineProxy() *ExpressionEngineProxy

func (GoMybatisSqlBuilder) New

func (it GoMybatisSqlBuilder) New(expressionEngine ExpressionEngineProxy, log Log, enableLog bool) GoMybatisSqlBuilder

func (*GoMybatisSqlBuilder) NodeParser

func (it *GoMybatisSqlBuilder) NodeParser() ast.NodeParser

func (*GoMybatisSqlBuilder) SetEnableLog

func (it *GoMybatisSqlBuilder) SetEnableLog(enable bool)

type GoMybatisSqlResultDecoder

type GoMybatisSqlResultDecoder struct {
	SqlResultDecoder
}

func (GoMybatisSqlResultDecoder) Decode

func (it GoMybatisSqlResultDecoder) Decode(resultMap map[string]*ResultProperty, sqlResult []map[string][]byte, result interface{}) error

type GoMybatisTempleteDecoder

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

* TODO sqlTemplete解析器,目前直接操作*etree.Element实现,后期应该改成操作xml,换取更好的维护性

func (*GoMybatisTempleteDecoder) Decode

func (it *GoMybatisTempleteDecoder) Decode(method *reflect.StructField, mapper *etree.Element, tree map[string]etree.Token) (bool, error)

func (*GoMybatisTempleteDecoder) DecodeCollectionName

func (it *GoMybatisTempleteDecoder) DecodeCollectionName(method *reflect.StructField) string

反射解码得到 集合名词

func (*GoMybatisTempleteDecoder) DecodeSets

func (it *GoMybatisTempleteDecoder) DecodeSets(arg string, mapper *etree.Element, logic LogicDeleteData, versionData *VersionData)

func (*GoMybatisTempleteDecoder) DecodeTree

func (it *GoMybatisTempleteDecoder) DecodeTree(tree map[string]etree.Token, beanType reflect.Type) error

func (*GoMybatisTempleteDecoder) DecodeWheres

func (it *GoMybatisTempleteDecoder) DecodeWheres(arg string, mapper *etree.Element, logic LogicDeleteData, versionData *VersionData)

解码逗号分隔的where

func (*GoMybatisTempleteDecoder) SetPrintElement

func (it *GoMybatisTempleteDecoder) SetPrintElement(print bool)

type GoroutineSessionMap

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

func (*GoroutineSessionMap) Delete

func (it *GoroutineSessionMap) Delete(k int64)

func (*GoroutineSessionMap) Get

func (it *GoroutineSessionMap) Get(k int64) Session

func (GoroutineSessionMap) New

func (*GoroutineSessionMap) Put

func (it *GoroutineSessionMap) Put(k int64, session Session)

type LocalSession

type LocalSession struct {
	SessionId string
	// contains filtered or unexported fields
}

本地直连session

func (*LocalSession) Begin

func (it *LocalSession) Begin(p *tx.Propagation) error

func (*LocalSession) Close

func (it *LocalSession) Close()

func (*LocalSession) Commit

func (it *LocalSession) Commit() error

func (*LocalSession) Exec

func (it *LocalSession) Exec(sqlorArgs string) (*Result, error)

func (*LocalSession) ExecPrepare

func (it *LocalSession) ExecPrepare(sqlPrepare string, args ...interface{}) (*Result, error)

func (*LocalSession) Id

func (it *LocalSession) Id() string

func (*LocalSession) LastPROPAGATION

func (it *LocalSession) LastPROPAGATION() *tx.Propagation

func (LocalSession) New

func (it LocalSession) New(driverType string, driverLink string, db *sql.DB, logSystem Log) LocalSession

func (*LocalSession) Query

func (it *LocalSession) Query(sqlorArgs string) ([]map[string][]byte, error)

func (*LocalSession) QueryPrepare

func (it *LocalSession) QueryPrepare(sqlPrepare string, args ...interface{}) ([]map[string][]byte, error)

func (*LocalSession) Rollback

func (it *LocalSession) Rollback() error

func (*LocalSession) StmtConvert

func (it *LocalSession) StmtConvert() (stmt.StmtIndexConvert, error)

type Log

type Log interface {
	QueueLen() int           //日志消息队列长度
	Println(messages []byte) //日志输出方法实现
}

type LogStandard

type LogStandard struct {
	PrintlnFunc func(messages []byte) //日志输出方法实现
}

func (*LogStandard) Println

func (it *LogStandard) Println(v []byte)

日志输出方法实现

func (*LogStandard) QueueLen

func (it *LogStandard) QueueLen() int

日志消息队列长度

type LogSystem

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

func (*LogSystem) Close

func (it *LogSystem) Close() error

关闭日志系统和队列

func (LogSystem) New

func (it LogSystem) New(logImpl Log, queueLen int) (LogSystem, error)

logImpl:日志实现类,queueLen:消息队列缓冲长度

func (*LogSystem) SendLog

func (it *LogSystem) SendLog(logs ...string) error

日志发送者

type LogicDeleteData

type LogicDeleteData struct {
	Column   string
	Property string
	LangType string

	Enable         bool
	Deleted_value  string
	Undelete_value string
}

type Mapper

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

type ProxyArg

type ProxyArg struct {
	TagArgs    []TagArg
	TagArgsLen int
	Args       []reflect.Value
	ArgsLen    int
}

代理数据

func (ProxyArg) New

func (it ProxyArg) New(tagArgs []TagArg, args []reflect.Value) ProxyArg

type Result

type Result struct {
	LastInsertId int64
	RowsAffected int64
}

type ResultProperty

type ResultProperty struct {
	XMLName  string //`xml:"result/id"`
	Column   string
	LangType string
}

type ReturnType

type ReturnType struct {
	ErrorType     *reflect.Type
	ReturnOutType *reflect.Type
	ReturnIndex   int //返回数据位置索引
	NumOut        int //返回总数
}

type Session

type Session interface {
	Id() string
	Query(sqlorArgs string) ([]map[string][]byte, error)
	Exec(sqlorArgs string) (*Result, error)
	//Prepare sql, example sqlPrepare: select * from table where id = ?   ,   args:'1'
	QueryPrepare(sqlPrepare string, args ...interface{}) ([]map[string][]byte, error)
	//Prepare sql, example sqlPrepare: select * from table where id = ?   ,   args:'1'
	ExecPrepare(sqlPrepare string, args ...interface{}) (*Result, error)
	Rollback() error
	Commit() error
	Begin(p *tx.Propagation) error
	Close()
	LastPROPAGATION() *tx.Propagation
	StmtConvert() (stmt.StmtIndexConvert, error)
}

type SessionEngine

type SessionEngine interface {
	//打开数据库
	Open(driverName, dataSourceLink string) (*sql.DB, error)
	//写方法到mapper
	WriteMapperPtr(ptr interface{}, xml []byte)
	//引擎名称
	Name() string
	//创建session
	NewSession(mapperName string) (Session, error)
	//获取数据源路由
	DataSourceRouter() DataSourceRouter
	//设置数据源路由
	SetDataSourceRouter(router DataSourceRouter)

	//是否启用日志
	LogEnable() bool

	//是否启用日志
	SetLogEnable(enable bool)

	//获取日志实现类
	Log() Log

	//设置日志实现类
	SetLog(log Log)

	//session工厂
	SessionFactory() *SessionFactory

	//设置session工厂
	SetSessionFactory(factory *SessionFactory)

	//设置sql类型转换器
	SetSqlArgTypeConvert(convert ast.SqlArgTypeConvert)

	//表达式执行引擎
	ExpressionEngine() ast.ExpressionEngine

	//设置表达式执行引擎
	SetExpressionEngine(engine ast.ExpressionEngine)

	//sql构建器
	SqlBuilder() SqlBuilder

	//设置sql构建器
	SetSqlBuilder(builder SqlBuilder)

	//sql查询结果解析器
	SqlResultDecoder() SqlResultDecoder

	//设置sql查询结果解析器
	SetSqlResultDecoder(decoder SqlResultDecoder)

	//模板解析器
	TempleteDecoder() TempleteDecoder

	//设置模板解析器
	SetTempleteDecoder(decoder TempleteDecoder)

	//(注意(该方法需要在多协程环境下调用)启用会从栈获取协程id,有一定性能消耗,换取最大的事务定义便捷)
	GoroutineSessionMap() *GoroutineSessionMap

	//是否启用goroutineIDEnable(注意(该方法需要在多协程环境下调用)启用会从栈获取协程id,有一定性能消耗,换取最大的事务定义便捷)
	SetGoroutineIDEnable(enable bool)

	//是否启用goroutineIDEnable(注意(该方法需要在多协程环境下调用)启用会从栈获取协程id,有一定性能消耗,换取最大的事务定义便捷)
	GoroutineIDEnable() bool

	LogSystem() *LogSystem

	IsPrintWarning() bool
}

产生session的引擎

type SessionFactory

type SessionFactory struct {
	Engine     SessionEngine
	SessionMap sync.Map //map[string]Session
}

func (*SessionFactory) Close

func (it *SessionFactory) Close(id string)

func (*SessionFactory) CloseAll

func (it *SessionFactory) CloseAll(id string)

func (*SessionFactory) GetSession

func (it *SessionFactory) GetSession(id string) Session

func (SessionFactory) New

func (*SessionFactory) NewSession

func (it *SessionFactory) NewSession(mapperName string, sessionType SessionType) Session

func (*SessionFactory) SetSession

func (it *SessionFactory) SetSession(id string, session Session)

type SessionFactorySession

type SessionFactorySession struct {
	Session Session
	Factory *SessionFactory
}

func (*SessionFactorySession) Begin

func (it *SessionFactorySession) Begin(p *tx.Propagation) error

func (*SessionFactorySession) Close

func (it *SessionFactorySession) Close()

func (*SessionFactorySession) Commit

func (it *SessionFactorySession) Commit() error

func (*SessionFactorySession) Exec

func (it *SessionFactorySession) Exec(sqlorArgs string) (*Result, error)

func (*SessionFactorySession) ExecPrepare

func (it *SessionFactorySession) ExecPrepare(sqlorArgs string, args ...interface{}) (*Result, error)

func (*SessionFactorySession) Id

func (it *SessionFactorySession) Id() string

func (*SessionFactorySession) LastPROPAGATION

func (it *SessionFactorySession) LastPROPAGATION() *tx.Propagation

func (*SessionFactorySession) Query

func (it *SessionFactorySession) Query(sqlorArgs string) ([]map[string][]byte, error)

func (*SessionFactorySession) QueryPrepare

func (it *SessionFactorySession) QueryPrepare(sqlorArgs string, args ...interface{}) ([]map[string][]byte, error)

func (*SessionFactorySession) Rollback

func (it *SessionFactorySession) Rollback() error

func (*SessionFactorySession) StmtConvert

func (it *SessionFactorySession) StmtConvert() (stmt.StmtIndexConvert, error)

type SessionSupport

type SessionSupport struct {
	NewSession func() (Session, error) //session为事务操作
}

type SessionType

type SessionType = int
const (
	SessionType_Default SessionType = iota //默认session类型
	SessionType_Local                      //本地session
)

type SqlBuilder

type SqlBuilder interface {
	BuildSql(paramMap map[string]interface{}, nodes []ast.Node, arg_array *[]interface{}, stmtConvert stmt.StmtIndexConvert) (string, error)
	ExpressionEngineProxy() *ExpressionEngineProxy
	SetEnableLog(enable bool)
	EnableLog() bool
	NodeParser() ast.NodeParser
}

sql文本构建

type SqlResultDecoder

type SqlResultDecoder interface {
	//resultMap = in xml resultMap element
	//dbData = select the SqlResult
	//decodeResultPtr = need decode result type
	Decode(resultMap map[string]*ResultProperty, SqlResult []map[string][]byte, decodeResultPtr interface{}) error
}

sql查询结果解码

type TagArg

type TagArg struct {
	Name  string
	Index int
}

type TempleteDecoder

type TempleteDecoder interface {
	SetPrintElement(print bool)
	DecodeTree(tree map[string]etree.Token, beanType reflect.Type) error
}

type VersionData

type VersionData struct {
	Column   string
	Property string
	LangType string
}

Directories

Path Synopsis
Package snowflake provides a very simple Twitter snowflake generator and parser.
Package snowflake provides a very simple Twitter snowflake generator and parser.
lib
github.com/antonmedv/expr
Package expr is an engine that can evaluate expressions.
Package expr is an engine that can evaluate expressions.
github.com/beevik/etree
Package etree provides XML services through an Element Tree abstraction.
Package etree provides XML services through an Element Tree abstraction.
github.com/google/uuid
Package uuid generates and inspects UUIDs.
Package uuid generates and inspects UUIDs.

Jump to

Keyboard shortcuts

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