GoMybatis

package module
v2.0.0-...-390ca0f Latest Latest
Warning

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

Go to latest
Published: Jan 1, 2019 License: Apache-2.0 Imports: 17 Imported by: 0

README

SQL mapper framework for Golang

Go Report Card Build Status GoDoc Coverage Status codecov

Image text

官方网站/文档

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

优势

-高并发,假设数据库响应时间为0,在6核16GB PC上框架每秒事务数可达246982Tps/s,耗时仅仅0.4s
-事务,session灵活插拔,兼容过渡期微服务
-动态SQL,在xml中可灵活运用if判断,foreach遍历数组,resultMap,bind等等java框架Mybatis包含的实用功能<select>,<update>,<insert>,<delete>,<trim>,<if>,<set>,<where>,<foreach>,<resultMap>,<bind>,<choose><when><otherwise>,<sql><include>
-多数据库支持Mysql,Postgres,Tidb,SQLite,Oracle....等等更多
-基于反射动态代理,无需go generate生成*.go等中间代码,xml读取后可直接写入到自定义的Struct,Func属性中调用函数

已支持本地和远程事务,方便处于 单数据库(Mysql,postgresql)-分布式数据库(TiDB,cockroachdb...)过渡期间的微服务

Image text

数据库驱动列表

 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

使用教程

示例源码https://github.com/zhuxiujia/GoMybatis/tree/master/example

设置好GoPath,用go get 命令下载GoMybatis和对应的数据库驱动

go get github.com/zhuxiujia/GoMybatis
go get github.com/go-sql-driver/mysql

实际使用mapper

import (
	_ "github.com/go-sql-driver/mysql" //导入mysql驱动
	"github.com/zhuxiujia/GoMybatis"
	"fmt"
	"time"
)

//定义xml内容,建议以*Mapper.xml文件存于项目目录中,在编辑xml时就可享受GoLand等IDE渲染和智能提示。生产环境可以使用statikFS把xml文件打包进程序里

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 err error
	//Mysql链接格式 用户名:密码@(数据库链接地址:端口)/数据库名称,如root:123456@(***.com:3306)/test
	engine, err := GoMybatis.Open("mysql", "*?charset=utf8&parseTime=True&loc=Local")
	if err != nil {
	   panic(err)
	}
	var exampleActivityMapperImpl ExampleActivityMapperImpl
	
	//加载xml实现逻辑到ExampleActivityMapperImpl
	GoMybatis.WriteMapperPtrByEngine(&exampleActivityMapperImpl, xmlBytes, engine,true)

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

请及时关注版本,及时升级版本(新的功能,bug修复)

TODO 期待功能路线(预览功能,可能会更改)

-在线WebUI后台界面,可在线编辑SQL和xml文件,可以在系统上线后动态修改xml中的SQL逻辑并生效(进行中,敬请期待哦~)

喜欢的老铁欢迎在右上角点下 star 关注和支持我们哈

Documentation

Index

Constants

View Source
const Adapter_DateType = `time.Time`
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`

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 WriteMapperByEngine

func WriteMapperByEngine(value reflect.Value, xml []byte, sessionEngine *SessionEngine, enableLog bool)

根据sessionEngine写入到mapperPtr

func WriteMapperPtrByEngine

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

根据sessionEngine写入到mapperPtr

Types

type ActionType

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

type DefaultTransationManager

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

func (DefaultTransationManager) Commit

func (this DefaultTransationManager) Commit(transactionId string) error

func (DefaultTransationManager) DoAction

func (this DefaultTransationManager) DoAction(dto TransactionReqDTO, transcationStatus *TransactionStatus) TransactionRspDTO

执行数据库操作

func (DefaultTransationManager) DoTransaction

执行事务

func (DefaultTransationManager) GetTransaction

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

func (DefaultTransationManager) New

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

func (DefaultTransationManager) Rollback

func (this DefaultTransationManager) Rollback(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 ExpressionTypeConvert

type ExpressionTypeConvert interface {
	Convert(arg SqlArg) interface{}
}

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

type GoMybatisEngine

type GoMybatisEngine struct {
	SessionEngine
	DB *sql.DB
}

func (GoMybatisEngine) NewSession

func (this GoMybatisEngine) NewSession() Session

type GoMybatisExpressionTypeConvert

type GoMybatisExpressionTypeConvert struct {
	ExpressionTypeConvert
}

表达式类型转换器

func (GoMybatisExpressionTypeConvert) Convert

func (this GoMybatisExpressionTypeConvert) Convert(arg SqlArg) interface{}

表达式类型转换器

type GoMybatisSqlArgTypeConvert

type GoMybatisSqlArgTypeConvert struct {
	SqlArgTypeConvert
}

Sql内容类型转换器

func (GoMybatisSqlArgTypeConvert) Convert

func (this GoMybatisSqlArgTypeConvert) Convert(arg SqlArg) string

Sql内容类型转换器

type GoMybatisSqlBuilder

type GoMybatisSqlBuilder struct {
	SqlBuilder
	ExpressionTypeConvert ExpressionTypeConvert
	SqlArgTypeConvert     SqlArgTypeConvert
}

func (GoMybatisSqlBuilder) BuildSql

func (this GoMybatisSqlBuilder) BuildSql(paramMap map[string]SqlArg, mapperXml *MapperXml, enableLog bool) (string, error)

func (GoMybatisSqlBuilder) New

func (this GoMybatisSqlBuilder) New(ExpressionTypeConvert ExpressionTypeConvert, SqlArgTypeConvert SqlArgTypeConvert) GoMybatisSqlBuilder

type GoMybatisSqlResultDecoder

type GoMybatisSqlResultDecoder struct {
	SqlResultDecoder
}

func (GoMybatisSqlResultDecoder) Decode

func (this 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 (this *LocalSession) Begin() error

func (*LocalSession) Close

func (this *LocalSession) Close()

func (*LocalSession) Commit

func (this *LocalSession) Commit() error

func (*LocalSession) Exec

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

func (*LocalSession) Id

func (this *LocalSession) Id() string

func (*LocalSession) Query

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

func (*LocalSession) Rollback

func (this *LocalSession) Rollback() 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 (this *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 {
	NewSession() Session
}

产生session的引擎

func Open

func Open(driverName, dataSourceName string) (*SessionEngine, error)

打开一个本地引擎

type SessionFactory

type SessionFactory struct {
	Engine     *SessionEngine
	SessionMap map[string]*Session
}
var DefaultSessionFactory *SessionFactory

如果使用WriteMapperByEngine(),则内建默认的SessionFactory

func (*SessionFactory) Close

func (this *SessionFactory) Close(id string)

func (*SessionFactory) CloseAll

func (this *SessionFactory) CloseAll(id string)

func (*SessionFactory) GetSession

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

func (SessionFactory) New

func (this SessionFactory) New(Engine *SessionEngine) SessionFactory

func (*SessionFactory) NewSession

func (this *SessionFactory) NewSession(sessionType SessionType, config *TransationRMClientConfig) Session

func (*SessionFactory) SetSession

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

type SessionFactorySession

type SessionFactorySession struct {
	Session Session
	Factory *SessionFactory
}

func (*SessionFactorySession) Begin

func (this *SessionFactorySession) Begin() error

func (*SessionFactorySession) Close

func (this *SessionFactorySession) Close()

func (*SessionFactorySession) Commit

func (this *SessionFactorySession) Commit() error

func (*SessionFactorySession) Exec

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

func (*SessionFactorySession) Id

func (this *SessionFactorySession) Id() string

func (*SessionFactorySession) Query

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

func (*SessionFactorySession) Rollback

func (this *SessionFactorySession) Rollback() error

type SessionType

type SessionType = int
const (
	SessionType_Default SessionType = iota
	SessionType_Local
	SessionType_TransationRM
	SessionType_UnKnow
)

type SqlArg

type SqlArg struct {
	Value interface{}
	Type  reflect.Type
}

type SqlArgTypeConvert

type SqlArgTypeConvert interface {
	Convert(arg SqlArg) string
}

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

type SqlBuilder

type SqlBuilder interface {
	BuildSql(paramMap map[string]SqlArg, mapperXml *MapperXml, enableLog bool) (string, error)
}

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
}

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 (this *TransactionFactory) Append(transactionId string, transaction TransactionStatus)

func (*TransactionFactory) GetTransactionStatus

func (this *TransactionFactory) GetTransactionStatus(transactionId string) (*TransactionStatus, error)

func (TransactionFactory) New

func (this TransactionFactory) New(SessionFactory *SessionFactory) TransactionFactory

func (*TransactionFactory) SetTransactionStatus

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

type TransactionManager

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

type TransactionReqDTO

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

type TransactionRspDTO

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

type TransactionStatus

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

func (*TransactionStatus) Begin

func (this *TransactionStatus) Begin() error

func (*TransactionStatus) Commit

func (this *TransactionStatus) Commit() error

func (*TransactionStatus) DelayFlush

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

延迟关闭

func (*TransactionStatus) Flush

func (this *TransactionStatus) Flush()

func (*TransactionStatus) Rollback

func (this *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 (this *TransationRMClient) Close() error
func (this *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 (this TransationRMServer) Msg(arg TransactionReqDTO, result *TransactionRspDTO) (err error)

type TransationRMSession

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

func (*TransationRMSession) Begin

func (this *TransationRMSession) Begin() error

func (*TransationRMSession) Close

func (this *TransationRMSession) Close()

func (*TransationRMSession) Commit

func (this *TransationRMSession) Commit() error

func (*TransationRMSession) Exec

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

func (*TransationRMSession) Id

func (this *TransationRMSession) Id() string

func (TransationRMSession) New

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

func (*TransationRMSession) Query

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

func (*TransationRMSession) Rollback

func (this *TransationRMSession) Rollback() error

Directories

Path Synopsis
lib
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/satori/go.uuid
Package uuid provides implementation of Universally Unique Identifier (UUID).
Package uuid provides implementation of Universally Unique Identifier (UUID).
ui

Jump to

Keyboard shortcuts

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