GoMybatis

package module
v3.0.0-...-aff40cf Latest Latest
Warning

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

Go to latest
Published: Feb 14, 2019 License: Apache-2.0 Imports: 20 Imported by: 0

README

SQL mapper ORM framework for Golang

Image text

website https://zhuxiujia.github.io/gomybatis.io/info.html

advantage

-High concurrencyAssuming that the response time of the database is 0, the number of transactions per second in the framework on a 6-core 16GB PC can reach 246982 Tps/s, which takes only 0.4s.
-Transaction supportSession flexible plug-in, compatible with transitional micro-services
-dynamic sqlIn xml, you can flexibly use<if><foreach><resultMap>,<bind>and so on. The 15 practical functions of Mybatis are included in the Java framework.
<select>,<update>,<insert>,<delete>,<trim>,<if>,<set>,<where>,<foreach>,<resultMap>,<bind>,<choose><when><otherwise>,<sql><include>
-Multi-database support Mysql,Postgres,Tidb,SQLite,Oracle....and more
-Quick StartBased on Reflective Dynamic Agent, no intermediate code such as *.go generated by go generator is needed. After reading xml, the function can be called directly.
-Expression and XML object-oriented designIf foo. Bar is a pointer, then calling foo. Bar in XML will take the actual value and completely avoid using & and * symbolic pointer operations.
-Dynamic multiple data sourcesYou can customize multiple data source rules using routing engine. SetDataSourceRouter

Asynchronous Message Queue Logging System

Image text

Over-remote substitution for micro-service members to handle transactions supports micro-services during the transition from single database (Mysql, postgresql) to distributed database (TiDB, cockroachdb...)

Image text

Database Driven List

 Mysql: github.com/go-sql-driver/mysql
 MyMysql: github.com/ziutek/mymysql/godrv
 Postgres: github.com/lib/pq
 Tidb: github.com/pingcap/tidb
 SQLite: github.com/mattn/go-sqlite3
 MsSql: github.com/denisenkom/go-mssqldb
 MsSql: github.com/lunny/godbc
 Oracle: github.com/mattn/go-oci8
 CockroachDB(Postgres): github.com/lib/pq

Using tutorials

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

Set up GoPath and 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

Actual use of mapper

import (
	_ "github.com/go-sql-driver/mysql" //Import MySQL driver
	"github.com/zhuxiujia/GoMybatis"
	"fmt"
	"time"
)

//Define the content of xml. It is recommended that the * Mapper. XML file be stored in the project directory. When editing xml, you can enjoy IDE rendering and intelligent prompts such as GoLand. Production environments can use statikFS to package XML files into processes

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 namespace="ActivityMapperImpl">
    <!--SelectAll(result *[]Activity)error-->
    <select id="selectAll">
        select * from biz_activity where delete_flag=1 order by create_time desc
    </select>
</mapper>
`)

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)

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

Welcome to the top right-hand corner of star.

Documentation

Index

Constants

View Source
const Adapter_FormateDate = `2006-01-02 15:04:05`
View Source
const CallMethod = "TransationRMServer.Msg"
View Source
const ConnectError = "connection is shut down"
View Source
const DefaultOneArg = `[default]`
View Source
const DefaultOverrides = ","
View Source
const DefaultWhereElement_Prefix = "where"
View Source
const DefaultWhereElement_PrefixOverrides = "and |or |And |Or |AND |OR "
View Source
const Element_Mapper = "mapper"
View Source
const EtreeCharData = `*etree.CharData`
View Source
const EtreeElement = `*etree.Element`
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 LoadMapperXml

func LoadMapperXml(bytes []byte) (items map[string]*MapperXml)

load xml from string data,return a map[elementId]*MapperXml

func ServerTransationTcp

func ServerTransationTcp(addr string, driverName, dataSourceName string)

开启一个事务节点

func UseMapper

func UseMapper(mapper interface{}, proxyFunc func(method string, args []reflect.Value, tagArgs []TagArg) []reflect.Value)

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

func UseMapperValue

func UseMapperValue(mapperValue reflect.Value, proxyFunc func(method string, args []reflect.Value, tagArgs []TagArg) []reflect.Value)

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

func WriteMapper

func WriteMapper(bean reflect.Value, xml []byte, sessionFactory *SessionFactory, decoder SqlResultDecoder, sqlBuilder SqlBuilder, enableLog bool)

写入方法内容,例如

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 `mapperParams:"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 `mapperParams:"name,startTime,endTime"`
}

func的基本类型的参数(例如string,int,time.Time,int64,float....)个数无限制(并且需要用Tag指定参数名逗号隔开,例如`mapperParams:"id,phone"`),返回值必须有error func的结构体参数无需指定mapperParams的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 ActionType

type ActionType int
const (
	ActionType_Exec  ActionType = iota //执行
	ActionType_Query                   //查询
)

type DataSourceRouter

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

数据源路由接口

type DefaultTransationManager

type DefaultTransationManager struct {
	TransactionManager
	SessionFactory     *SessionFactory
	TransactionFactory *TransactionFactory
}

func (DefaultTransationManager) Commit

func (it DefaultTransationManager) Commit(mapperName string, transactionId string) error

func (DefaultTransationManager) DoAction

执行数据库操作

func (DefaultTransationManager) DoTransaction

执行事务

func (DefaultTransationManager) GetTransaction

func (it DefaultTransationManager) GetTransaction(mapperName string, def *TransactionDefinition, transactionId string, OwnerId string) (*TransactionStatus, error)

func (DefaultTransationManager) New

func (it DefaultTransationManager) New(SessionFactory *SessionFactory, TransactionFactory *TransactionFactory) DefaultTransationManager

func (DefaultTransationManager) Rollback

func (it DefaultTransationManager) Rollback(mapperName string, transactionId string) error

type ElementItem

type ElementItem struct {
	ElementType  string
	Propertys    map[string]string
	DataString   string
	ElementItems []ElementItem
}

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"

	//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 ExpressionEngine

type ExpressionEngine interface {
	//引擎名称
	Name() string
	//编译一个表达式
	//参数:lexerArg 表达式内容
	//返回:interface{} 编译结果,error 错误
	Lexer(lexerArg string) (interface{}, error)

	//执行一个表达式
	//参数:lexerResult=编译结果,arg=参数
	//返回:执行结果,错误
	Eval(lexerResult interface{}, arg interface{}, operation int) (interface{}, error)

	//取Lexer缓存,可不提供。需要提供单例
	LexerCache() ExpressionEngineLexerCache
}

q:为什么要拆分表达式编译和执行步骤?优化性能,如果需要可以缓存表达式编译结果,执行表达式时不需要重复编译 表达式引擎接口

type ExpressionEngineExpr

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

func (*ExpressionEngineExpr) Eval

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

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

func (*ExpressionEngineExpr) Lexer

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

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

func (*ExpressionEngineExpr) LexerCache

Lexer缓存,可不提供。

func (*ExpressionEngineExpr) Name

func (it *ExpressionEngineExpr) Name() string

引擎名称

type ExpressionEngineGovaluate

type ExpressionEngineGovaluate struct {
}

func (*ExpressionEngineGovaluate) Eval

func (it *ExpressionEngineGovaluate) Eval(compileResult interface{}, arg interface{}, operation int) (interface{}, error)

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

func (*ExpressionEngineGovaluate) Lexer

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

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

func (*ExpressionEngineGovaluate) LexerCache

Lexer缓存,可不提供。

func (*ExpressionEngineGovaluate) Name

func (it *ExpressionEngineGovaluate) Name() string

type ExpressionEngineJee

type ExpressionEngineJee struct {
}

ExpressionEngineJee 是一个基于json表达式操作的第三方库实现

func (*ExpressionEngineJee) Eval

func (it *ExpressionEngineJee) Eval(compileResult interface{}, arg interface{}, operation int) (interface{}, error)

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

func (*ExpressionEngineJee) Lexer

func (it *ExpressionEngineJee) Lexer(lexerArg string) (interface{}, error)

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

func (*ExpressionEngineJee) LexerAndOrSupport

func (it *ExpressionEngineJee) LexerAndOrSupport(lexerArg string) string

添加and 和 or 语法支持

func (*ExpressionEngineJee) LexerCache

Lexer缓存,可不提供。

func (*ExpressionEngineJee) LexerEval

func (it *ExpressionEngineJee) LexerEval(lexerArg string, arg interface{}, operation int) (interface{}, error)

编译后立即执行

func (*ExpressionEngineJee) Name

func (it *ExpressionEngineJee) Name() string

type ExpressionEngineLexerCache

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

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

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

type ExpressionOperation

type ExpressionOperation = int
const (
	JeeOperation_Marshal_Map ExpressionOperation = iota //序列化和反序列化为json
	JeeOperation_Unmarshal_Byte
)

type GoMybatisDataSourceRouter

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

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) (Session, error)

func (*GoMybatisDataSourceRouter) SetDB

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

type GoMybatisEngine

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

func (*GoMybatisEngine) DBMap

func (it *GoMybatisEngine) DBMap() map[string]*sql.DB

func (*GoMybatisEngine) DataSourceRouter

func (it *GoMybatisEngine) DataSourceRouter() DataSourceRouter

func (*GoMybatisEngine) ExpressionEngine

func (it *GoMybatisEngine) ExpressionEngine() ExpressionEngine

表达式执行引擎

func (*GoMybatisEngine) Log

func (it *GoMybatisEngine) Log() Log

获取日志实现类

func (*GoMybatisEngine) LogEnable

func (it *GoMybatisEngine) LogEnable() bool

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

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, dataSourceName string) error

打开数据库 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 ExpressionEngine)

设置表达式执行引擎

func (*GoMybatisEngine) SetLog

func (it *GoMybatisEngine) SetLog(log Log)

设置日志实现类

func (*GoMybatisEngine) SetLogEnable

func (it *GoMybatisEngine) SetLogEnable(enable bool)

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

func (*GoMybatisEngine) SetSessionFactory

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

设置session工厂

func (*GoMybatisEngine) SetSqlArgTypeConvert

func (it *GoMybatisEngine) SetSqlArgTypeConvert(convert SqlArgTypeConvert)

设置sql类型转换器

func (*GoMybatisEngine) SetSqlBuilder

func (it *GoMybatisEngine) SetSqlBuilder(builder SqlBuilder)

设置sql构建器

func (*GoMybatisEngine) SetSqlResultDecoder

func (it *GoMybatisEngine) SetSqlResultDecoder(decoder SqlResultDecoder)

设置sql查询结果解析器

func (*GoMybatisEngine) SqlArgTypeConvert

func (it *GoMybatisEngine) SqlArgTypeConvert() SqlArgTypeConvert

sql类型转换器

func (*GoMybatisEngine) SqlBuilder

func (it *GoMybatisEngine) SqlBuilder() SqlBuilder

sql构建器

func (*GoMybatisEngine) SqlResultDecoder

func (it *GoMybatisEngine) SqlResultDecoder() SqlResultDecoder

sql查询结果解析器

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{}, argType reflect.Type) string

Sql内容类型转换器

type GoMybatisSqlBuilder

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

func (GoMybatisSqlBuilder) BuildSql

func (it GoMybatisSqlBuilder) BuildSql(paramMap map[string]interface{}, mapperXml *MapperXml) (string, error)

func (GoMybatisSqlBuilder) ExpressionEngineProxy

func (it GoMybatisSqlBuilder) ExpressionEngineProxy() ExpressionEngineProxy

func (GoMybatisSqlBuilder) LogSystem

func (it GoMybatisSqlBuilder) LogSystem() *LogSystem

func (GoMybatisSqlBuilder) New

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

func (GoMybatisSqlBuilder) SqlArgTypeConvert

func (it GoMybatisSqlBuilder) SqlArgTypeConvert() SqlArgTypeConvert

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 ISOLATION

type ISOLATION int
const (
	ISOLATION_DEFAULT ISOLATION = iota - 1
	ISOLATION_READ_UNCOMMITTED
	ISOLATION_READ_COMMITTED
	ISOLATION_REPEATABLE_READ
	ISOLATION_SERIALIZABLE
)

隔离级别

type LocalSession

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

本地直连session

func (*LocalSession) Begin

func (it *LocalSession) Begin() 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) Id

func (it *LocalSession) Id() string

func (*LocalSession) Query

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

func (*LocalSession) Rollback

func (it *LocalSession) Rollback() 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 MapperXml

type MapperXml struct {
	Tag          string
	Id           string
	Propertys    map[string]string
	ElementItems []ElementItem
}

type PROPAGATION

type PROPAGATION int
const (
	PROPAGATION_REQUIRED PROPAGATION = iota
	PROPAGATION_SUPPORTS
	PROPAGATION_MANDATORY
	PROPAGATION_REQUIRES_NEW
	PROPAGATION_NOT_SUPPORTED
	PROPAGATION_NEVER
	PROPAGATION_NESTED
)

传播行为

type RemoteSessionEngine

type RemoteSessionEngine struct {
	SessionEngine
	Client *TransationRMClient
}

func (RemoteSessionEngine) New

func (*RemoteSessionEngine) NewSession

func (it *RemoteSessionEngine) NewSession() Session

type Result

type Result struct {
	LastInsertId int64
	RowsAffected int64
}

type ResultProperty

type ResultProperty struct {
	XMLName  string //`xml:"result/id"`
	Column   string
	Property string
	GoType   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)
	Rollback() error
	Commit() error
	Begin() error
	Close()
}

type SessionEngine

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

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

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

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

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

	//session工厂
	SessionFactory() *SessionFactory

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

	//sql类型转换器
	SqlArgTypeConvert() SqlArgTypeConvert

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

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

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

	//sql构建器
	SqlBuilder() SqlBuilder

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

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

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

产生session的引擎

type SessionFactory

type SessionFactory struct {
	Engine     SessionEngine
	SessionMap 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, config *TransationRMClientConfig) 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() 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) Id

func (it *SessionFactorySession) Id() string

func (*SessionFactorySession) Query

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

func (*SessionFactorySession) Rollback

func (it *SessionFactorySession) Rollback() error

type SessionType

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

type SqlArgTypeConvert

type SqlArgTypeConvert interface {
	Convert(arg interface{}, argType reflect.Type) string
}

表达式类型(基本类型)转换函数

type SqlBuilder

type SqlBuilder interface {
	BuildSql(paramMap map[string]interface{}, mapperXml *MapperXml) (string, error)
	ExpressionEngineProxy() ExpressionEngineProxy
	SqlArgTypeConvert() SqlArgTypeConvert
	LogSystem() *LogSystem
}

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 Transaction

type Transaction struct {
	Id      string
	Session Session
}

type TransactionDefinition

type TransactionDefinition struct {
	PropagationBehavior PROPAGATION
	IsolationLevel      ISOLATION
	Timeout             time.Duration
	IsReadOnly          bool
}

func (TransactionDefinition) Default

type TransactionFactory

type TransactionFactory struct {
	TransactionStatuss map[string]*TransactionStatus
	SessionFactory     *SessionFactory
}

func (*TransactionFactory) Append

func (it *TransactionFactory) Append(mapperName string, transactionId string, transaction TransactionStatus)

func (*TransactionFactory) GetTransactionStatus

func (it *TransactionFactory) GetTransactionStatus(mapperName string, transactionId string) (*TransactionStatus, error)

func (TransactionFactory) New

func (it TransactionFactory) New(SessionFactory *SessionFactory) TransactionFactory

func (*TransactionFactory) SetTransactionStatus

func (it *TransactionFactory) SetTransactionStatus(transactionId string, transaction *TransactionStatus)

type TransactionManager

type TransactionManager interface {
	GetTransaction(mapperName string, def *TransactionDefinition, transactionId string, OwnerId string) (*TransactionStatus, error)
	Commit(mapperName string, transactionId string) error
	Rollback(mapperName string, transactionId string) error
}

type TransactionReqDTO

type TransactionReqDTO struct {
	Status        Transaction_Status
	TransactionId string //事务id(不可空)
	OwnerId       string //所有者
	Sql           string //sql内容(可空)
	ActionType    ActionType
	MapperName    string //mapper名称
}

type TransactionRspDTO

type TransactionRspDTO struct {
	TransactionId string //事务id(不可空)
	Error         string
	Success       int
	Query         []map[string][]byte
	Exec          Result
}

type TransactionStatus

type TransactionStatus struct {
	MapperName       string
	OwnerId          string       //所有者id
	IsNewTransaction bool         //是否新启动的事务
	HasSavepoint     bool         //是否保存点
	IsRollbackOnly   bool         //是否只允许rollback
	IsCompleted      bool         //是否完成
	HasSetDelayClose bool         //是否设置了延迟关闭/回滚
	Transaction      *Transaction //事务对象
}

func (*TransactionStatus) Begin

func (it *TransactionStatus) Begin() error

func (*TransactionStatus) Commit

func (it *TransactionStatus) Commit() error

func (*TransactionStatus) DelayFlush

func (it *TransactionStatus) DelayFlush(t time.Duration)

延迟关闭

func (*TransactionStatus) Flush

func (it *TransactionStatus) Flush()

func (*TransactionStatus) Rollback

func (it *TransactionStatus) Rollback() error

type Transaction_Status

type Transaction_Status int
const (
	Transaction_Status_NO       Transaction_Status = iota //非事务
	Transaction_Status_Prepare                            //准备事务
	Transaction_Status_Commit                             //提交事务
	Transaction_Status_Rollback                           //回滚事务
)

func (Transaction_Status) ToString

func (status Transaction_Status) ToString() string

type TransationRMClient

type TransationRMClient struct {
	Client    *rpc.Client
	Addr      string
	RetryTime int
}

func (*TransationRMClient) Call

func (*TransationRMClient) Close

func (it *TransationRMClient) Close() error
func (it *TransationRMClient) Link(addr string) (*rpc.Client, error)

type TransationRMClientConfig

type TransationRMClientConfig struct {
	Addr          string
	RetryTime     int
	TransactionId string
	Status        Transaction_Status
}

type TransationRMServer

type TransationRMServer struct {
	DefaultTransationManager *DefaultTransationManager
}

func (TransationRMServer) Msg

func (it TransationRMServer) Msg(arg TransactionReqDTO, result *TransactionRspDTO) (err error)

type TransationRMSession

type TransationRMSession struct {
	MapperName    string
	TransactionId string
	OwnerId       string
	Client        *TransationRMClient
	Status        Transaction_Status //默认0,非事务
}

func (*TransationRMSession) Begin

func (it *TransationRMSession) Begin() error

func (*TransationRMSession) Close

func (it *TransationRMSession) Close()

func (*TransationRMSession) Commit

func (it *TransationRMSession) Commit() error

func (*TransationRMSession) Exec

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

func (*TransationRMSession) Id

func (it *TransationRMSession) Id() string

func (TransationRMSession) New

func (it TransationRMSession) New(mapperName string, TransactionId string, Client *TransationRMClient, Status Transaction_Status) *Session

func (*TransationRMSession) Query

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

func (*TransationRMSession) Rollback

func (it *TransationRMSession) Rollback() error

Directories

Path Synopsis
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.

Jump to

Keyboard shortcuts

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