redis_orm

package module
v0.0.0-...-d4fcfd7 Latest Latest
Warning

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

Go to latest
Published: Feb 5, 2020 License: BSD-2-Clause Imports: 13 Imported by: 4

README

redis_orm

Object Relational Mapping use redis as a relational database。

产出背景
项目的快速迭代,不仅需要敏捷的开发,还需具备较高性能的和稳定性,单纯用关系型数据库有瓶颈,然后在关系型数据库基础上加分布式缓存或者进程内缓存有增加了开发和维护成本,
刚好项目中在用Redis,就考虑基于Redis的Hash和SortedSet两个数据结构来设计类似关系型数据库的ORM。经过多个版本的迭代,现在已经实现了ORM的基本功能,在应用中发现维护和查看数据
不太方便,又开发了[工作台](https://github.com/weikaishio/redis_orm_workbench).

工作台

功能列表
  • 基于对象的增、删、改、查、统计
  • 基于Map的增、删、改、查、统计(方便用在redis_orm_workbench)
  • 支持动态创建表、删除表、创建索引、重建索引
  • 支持可配置的自动同步到MySql数据库(一般为了更方便的查询统计所用)
使用说明
  • 模型定义的标签说明
    TagIdentifier = "redis_orm"
    	//定义是否索引,索引名自动生成 e.g.fmt.Sprintf("%s%s_%s", KeyIndexPrefix, strings.ToLower(table.Name), strings.ToLower(columnName)),
    TagIndex = "index"
    	//唯一索引 hash和走zscore一样都是O(1) 针对IndexType_IdMember有效,IndexType_IdScore的索引本来就是唯一的~
    TagUniqueIndex = "unique"
    	/*
    			要支持一种查询条件就得增加一个索引,定义用&连接联合索引中的字段,e.g.Status&Uid
    			组合索引 字符串则唯一!集合数据结构决定;
    		    除非用int64,44或224或2222来存放Score,即44:前4个字节uint32和后4个字节uint32
    			1、id作为score, 可以组合但是member唯一,唯一查询可用
    			此情况下的组合索引,直接按顺序拼接即可
    
    			2、id作为member,同一个member只能有一个score,该字段类型必须是长整型,数值索引可用,可以查询范围
    			此情况下的组合索引,仅仅支持两整型字段,左边32位 右边32位,支持范围查询的放左边
    	*/
    TagCombinedindex = "combinedindex"
	//默认值
	TagDefaultValue = "dft"
	//是否主键
	TagPrimaryKey = "pk"
	//自增~ 应用于主键
	TagAutoIncrement = "autoincr"
	//配置在主键的tag上,配置了该tag才能生效,同步到数据库
	TagSync2DB = "sync2db"
	//备注名
	TagComment = "comment"
	//是否支持自动写创建时间
	TagCreatedAt = "created_at"
	//是否支持自动写更新时间
	TagUpdatedAt = "updated_at"
  • 模型例子
type Faq struct {
	Id         int64  `redis_orm:"pk autoincr sync2db comment 'ID'"` //主键 自增 备注是ID
	Unique     int64  `redis_orm:"unique comment '唯一'"` //唯一索引
	Type       uint32 `redis_orm:"dft 1 comment '类型'"` //默认值:1
	Title      string `redis_orm:"dft 'faqtitle' index comment '标题'"` //默认值 faqtitle, 索引,备注 标题
	Content    string `redis_orm:"dft 'cnt' comment '内容'"`
	Hearts     uint32 `redis_orm:"dft 10 comment '点赞数'"`
	CreatedAt  int64  `redis_orm:"created_at comment '创建时间'"` //入库时自动写创建时间
	UpdatedAt  int64  `redis_orm:"updated_at comment '修改时间'"`
	TypeTitle  string `redis_orm:"combinedindex Type&Title comment '组合索引(类型&标题)'"` //组合索引 用到Type和Title两字段,字符串类型的索引,所以是唯一索引 
	TypeHearts int64  `redis_orm:"combinedindex Type&Hearts comment '组合索引(类型&赞数)'"` //组合索引 非唯一索引
}
  • 需要引用的库、初始化方式等
import (   
	"github.com/mkideal/log"
	"github.com/go-redis/redis" 
	"github.com/weikaishio/redis_orm"
	"github.com/weikaishio/redis_orm/test/models"
) 

func main() {
	options := redis.Options{
		Addr:     "127.0.0.1:6379",
		Password: "",
		DB:       1,
	}

	redisClient := redis.NewClient(&options)
	//注:已省略redisClient可用性检测
	
	engine := redis_orm.NewEngine(redisClient)
	engine.IsShowLog(true)
	
	driver := "mysql"
	host := "127.0.0.1:3306"
	database := "bg_db"
	username := "root"
	password := ""
	dataSourceName := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&&allowOldPasswords=1&parseTime=true", username, password, host, database)
	
	dbEngine, err := xorm.NewEngine(driver, dataSourceName)
	if err != nil {
		log.Error("NewEngine:%s,err:%v", dataSourceName, err)
		return
    }
	//给redisORM对象设置同步到dbEngine数据库对象,每90秒同步一次
    engine.SetSync2DB(dbEngine, 90)
	//退出之前会执行同步到DB
	defer engine.Quit()
	
	faq := &models.Faq{
		Type: 1,
		Title:  "Title",
		Unique: 111,
		Content: "Content",
	}
	//插入数据
	engine.Insert(faq)
	
	//查询指定Id的数据
	model := &models.Faq{
		Id: 1,
   	}
	has, err := engine.Get(model)
   	if err != nil {
   		log.Error("Get(%d) err:%v", model.Id, err)
   		return
    }
    	
	//查询指定条件的数据
	searchCon := NewSearchConditionV2(faq.Unique, faq.Unique, 111)
	var ary []models.Faq
	count, err := engine.Find(0, 100, searchCon, &ary)
	if err != nil {
   		log.Error("Find(%v) err:%v", searchCon, err)
		return 
    }
	//其他请见engine_curd.go、engine_curd_by_map.go里面的方法....更新、删除等功能, 也可以看目录下面的测试代码
}
  • 查看数据
建议使用配套的redis_orm_workbench来管理,可以维护表结构、数据和索引,方便直接在上面新增、修改和删除行数据。
也可以直接用redis-cli来查看数据,前缀tb:和ix:分别查看表数据和索引。

Documentation

Index

Constants

View Source
const (
	TagIdentifier = "redis_orm"
	//定义是否索引,索引名自动生成 e.g.fmt.Sprintf("%s%s_%s", KeyIndexPrefix, strings.ToLower(table.Name), strings.ToLower(columnName)),
	TagIndex = "index"
	//唯一索引 hash和走zscore一样都是O(1) 针对IndexType_IdMember有效,IndexType_IdScore的索引本来就是唯一的~
	TagUniqueIndex = "unique"
	/*
			要支持一种查询条件就得增加一个索引,定义用&连接联合索引中的字段,e.g.Status&Uid
			组合索引 字符串则唯一!集合数据结构决定;
		    除非用int64,44或224或2222来存放Score,即44:前4个字节uint32和后4个字节uint32
			1、id作为score, 可以组合但是member唯一,唯一查询可用
			此情况下的组合索引,直接按顺序拼接即可

			2、id作为member,同一个member只能有一个score,该字段类型必须是长整型,数值索引可用,可以查询范围
			此情况下的组合索引,仅仅支持两整型字段,左边32位 右边32位,支持范围查询的放左边
	*/
	TagCombinedindex = "combinedindex"
	//默认值
	TagDefaultValue = "dft"
	//是否主键
	TagPrimaryKey = "pk"
	//自增~ 应用于主键
	TagAutoIncrement = "autoincr"
	//配置在主键的tag上,配置了该tag才能生效,同步到数据库
	TagSync2DB = "sync2db"
	//备注名
	TagComment = "comment"
	//是否支持自动写创建时间
	TagCreatedAt = "created_at"
	//是否支持自动写更新时间
	TagUpdatedAt = "updated_at"
	//枚举类型
	TagEnum = "enum"

	//表key前缀+表名
	KeyTbPrefix = "tb:"
	//索引key前缀+表名+字段名
	KeyIndexPrefix = "ix:"
	//自增前缀+自增字段名
	KeyAutoIncrPrefix = "autoincr_last_"

	ScoreMax = "+inf"
	ScoreMin = "-inf"

	NeedMapTable                  = "schematablestb,schemacolumnstb,schemaindexstb"
	ChannelSchemaChangedSubscribe = "channel_schema_change"
)

Done: 多个独立的tag辩识和书写更方便些~ 需要加统一前缀,免得跟其他功能定义的tag冲突,然后又太长了,先不改

View Source
const (
	ErrorCodeSuccess    = 0
	ErrorCodeUnexpected = iota + 100

	ErrorCodeUnKnowField
	ErrorCodeUnKnowTable
	ErrorCodeUnKnowError
	ErrorCodeNotSupportIndexField
	ErrorCodeUnSupportedType
	ErrorCodeUnSupportedTableModel
	ErrorCodeFieldValueInvalid
	ErrorCodePrimaryKeyNotFound
	ErrorCodePrimaryKeyTypeInvalid
	ErrorCodeMoreThanOneIncrementColumn
	ErrorCodeDataNotAvailable
	ErrorCodeDataHadAvailable
	ErrorCodeCombinedIndexColCountOver
	ErrorCodeCombinedIndexTypeError
	ErrorCodeNeedPointer
	ErrorCodeNeedSlice
	ErrorCodeNotSupportPointer2Pointer
	ErrorCodeNilArgument
	ErrorCodeFieldValueInvalidForEnum
)

Variables

View Source
var (
	Err_Unexpected                 = Error(ErrorCodeUnexpected, "redis-orm-error:unexpected error")
	ERR_UnKnowField                = Error(ErrorCodeUnKnowField, "redis-orm-error:unknown column")
	ERR_UnKnowTable                = Error(ErrorCodeUnKnowTable, "redis-orm-error:unknown table")
	ERR_UnKnowError                = Error(ErrorCodeUnKnowError, "redis-orm-error:unknown error")
	ERR_NotSupportIndexField       = Error(ErrorCodeNotSupportIndexField, "redis-orm-error:not support this field's index")
	Err_UnSupportedType            = Error(ErrorCodeUnSupportedType, "redis-orm-error:unsupported type")
	Err_UnSupportedTableModel      = Error(ErrorCodeUnSupportedTableModel, "redis-orm-error:unsupported table model")
	Err_FieldValueInvalid          = Error(ErrorCodeFieldValueInvalid, "redis-orm-error:column value invalid")
	Err_PrimaryKeyNotFound         = Error(ErrorCodePrimaryKeyNotFound, "redis-orm-error:primarykey not found")
	Err_PrimaryKeyTypeInvalid      = Error(ErrorCodePrimaryKeyTypeInvalid, "redis-orm-error:primarykey type invalid")
	Err_MoreThanOneIncrementColumn = Error(ErrorCodeMoreThanOneIncrementColumn, "redis-orm-error:more than one increment column")
	Err_DataNotAvailable           = Error(ErrorCodeDataNotAvailable, "redis-orm-error:data not exist")
	Err_DataHadAvailable           = Error(ErrorCodeDataHadAvailable, "redis-orm-error:data had exist")
	Err_CombinedIndexColCountOver  = Error(ErrorCodeCombinedIndexColCountOver, "redis-orm-error:combined index not support more than 2 column")
	Err_CombinedIndexTypeError     = Error(ErrorCodeCombinedIndexTypeError, "redis-orm-error:combined index not support this type of column")
	Err_NeedPointer                = Error(ErrorCodeNeedPointer, "redis-orm-error:needs a pointer to a value")
	Err_NeedSlice                  = Error(ErrorCodeNeedSlice, "redis-orm-error:value needs to be a slice")
	Err_NotSupportPointer2Pointer  = Error(ErrorCodeNotSupportPointer2Pointer, "redis-orm-error:pointer to pointer is not supported")
	Err_NilArgument                = Error(ErrorCodeNilArgument, "redis-orm-error:argument is nil")
	Err_FieldValueInvalidForEnum   = Error(ErrorCodeFieldValueInvalidForEnum, "redis-orm-error:column value invalid for enum")
)

Functions

func Camel2Underline

func Camel2Underline(s string) string

func Code

func Code(err error) int

func ColsIsExistIndex

func ColsIsExistIndex(index *Index, cols ...string) bool

func GetFieldName

func GetFieldName(pkId interface{}, colName string) string

func MapTableColumnFromTag

func MapTableColumnFromTag(table *Table, seq int, columnName string, columnType string, rdsTagStr string) error

func SetBoolFromStr

func SetBoolFromStr(ptr *bool, s string) error

func SetDefaultValue

func SetDefaultValue(col *Column, value *reflect.Value)

func SetFloat32FromStr

func SetFloat32FromStr(ptr *float32, s string) error

func SetFloat64FromStr

func SetFloat64FromStr(ptr *float64, s string) error

func SetInt32FromStr

func SetInt32FromStr(ptr *int32, s string) error

func SetInt64FromStr

func SetInt64FromStr(ptr *int64, s string) error

func SetIntFromStr

func SetIntFromStr(ptr *int, s string) error

func SetUint16FromStr

func SetUint16FromStr(ptr *uint16, s string) error

func SetUint32FromStr

func SetUint32FromStr(ptr *uint32, s string) error

func SetUint64FromStr

func SetUint64FromStr(ptr *uint64, s string) error

func SetUint8FromStr

func SetUint8FromStr(ptr *uint8, s string) error

func SetUintFromStr

func SetUintFromStr(ptr *uint, s string) error

func SetValue

func SetValue(val interface{}, value *reflect.Value)

func ToString

func ToString(v interface{}) string

func Underline2Camel

func Underline2Camel(s string) string

Types

type Column

type Column struct {
	Seq             byte
	Name            string
	DefaultValue    string
	IsPrimaryKey    bool
	IsAutoIncrement bool
	IsCreated       bool
	IsUpdated       bool
	IsCombinedIndex bool //it 's only used for judge wherther need insert or delete and so on
	//IsCascade       bool
	EnumOptions map[string]int
	//SetOptions      map[string]int
	Comment  string
	DataType string
}

func ColumnFromSchemaColumns

func ColumnFromSchemaColumns(v *SchemaColumnsTb, schemaTable *SchemaTablesTb) *Column

func NewEmptyColumn

func NewEmptyColumn(colName string) *Column

type ColumnsModel

type ColumnsModel []*Column

func (ColumnsModel) Len

func (c ColumnsModel) Len() int

func (ColumnsModel) Less

func (c ColumnsModel) Less(i, j int) bool

func (ColumnsModel) Swap

func (c ColumnsModel) Swap(i, j int)

type Engine

type Engine struct {
	Tables map[string]*Table

	TZLocation *time.Location // The timezone of the application

	Schema *SchemaEngine
	Index  *IndexEngine
	// contains filtered or unexported fields
}
type ORM interface {
	Insert()
	Update()
	Delete()
	Find()
	Get()
}

从tag获取 索引, 只支持数值 字符 唯一索引的 自增 默认值

todo:链式查询

todo:权限控制~

todo:concurrency safe 并发的处理 1、唯一值的写入 解决方案: 2、自增(HIncrBy,HIncrByFloat)的原子可靠性 3、CAS

todo:pipeline

func NewEngine

func NewEngine(redisCli redis.Cmdable) *Engine

func (*Engine) Count

func (e *Engine) Count(searchCon *SearchCondition, beanAry interface{}) (int64, error)

func (*Engine) Delete

func (e *Engine) Delete(bean interface{}) error

func (*Engine) DeleteByCondition

func (e *Engine) DeleteByCondition(bean interface{}, searchCon *SearchCondition) (int, error)

func (*Engine) DeleteByPK

func (e *Engine) DeleteByPK(table *Table, pkInt int64) error

func (*Engine) FileterCols

func (e *Engine) FileterCols(table *Table, cols ...string) []string

func (*Engine) Find

func (e *Engine) Find(offset, limit int64, searchCon *SearchCondition, beanAry interface{}) (int64, error)

func (*Engine) Get

func (e *Engine) Get(bean interface{}) (bool, error)

func (*Engine) GetByCondition

func (e *Engine) GetByCondition(bean interface{}, searchCon *SearchCondition) (bool, error)

only support one searchCondition to get or find todo: SearchCondition not a elegant way..

func (*Engine) GetDefaultValue

func (e *Engine) GetDefaultValue(bean interface{}) error

func (*Engine) GetTableByName

func (e *Engine) GetTableByName(tableName string) (*Table, bool)

func (*Engine) GetTableByReflect

func (e *Engine) GetTableByReflect(beanValue, beanIndirectValue reflect.Value) (*Table, error)

func (*Engine) Incr

func (e *Engine) Incr(bean interface{}, col string, val int64) (int64, error)

func (*Engine) Insert

func (e *Engine) Insert(bean interface{}) error

Done:unique index is exist? -> IsExistData

func (*Engine) InsertByMap

func (e *Engine) InsertByMap(table *Table, columnValMap map[string]string) error

func (*Engine) InsertMulti

func (e *Engine) InsertMulti(beans ...interface{}) (int, error)

func (*Engine) IsShowLog

func (e *Engine) IsShowLog(isShow bool)

func (*Engine) Printf

func (e *Engine) Printf(format string, a ...interface{})

todo: command->redis client

func (*Engine) Printfln

func (e *Engine) Printfln(format string, a ...interface{})

func (*Engine) Query

func (e *Engine) Query(offset, limit int64, condition *SearchCondition, table *Table, cols ...string) ([]map[string]interface{}, int64, error)

func (*Engine) Quit

func (e *Engine) Quit()

func (*Engine) SetSync2DB

func (e *Engine) SetSync2DB(mysqlOrm *xorm.Engine, lazyTimeSecond int)

func (*Engine) Sum

func (e *Engine) Sum(bean interface{}, searchCon *SearchCondition, col string) (int64, error)

func (*Engine) TableFromBeanAryReflect

func (e *Engine) TableFromBeanAryReflect(beanAry interface{}) (*Table, error)

func (*Engine) TableName

func (e *Engine) TableName(v reflect.Value) string

func (*Engine) TableTruncate

func (e *Engine) TableTruncate(bean interface{}) error

del the hashkey, it will del all elements for this hash

func (*Engine) TableTruncateByTable

func (e *Engine) TableTruncateByTable(table *Table) error

func (*Engine) Update

func (e *Engine) Update(bean interface{}, cols ...string) error

func (*Engine) UpdateByMap

func (e *Engine) UpdateByMap(table *Table, columnValMap map[string]string) error

func (*Engine) UpdateMulti

func (e *Engine) UpdateMulti(bean interface{}, searchCon *SearchCondition, cols ...string) (int, error)

type ErrorWithCode

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

func (ErrorWithCode) Append

func (e ErrorWithCode) Append(format string, a ...interface{}) ErrorWithCoder

func (ErrorWithCode) Code

func (e ErrorWithCode) Code() int

func (*ErrorWithCode) Equal

func (e *ErrorWithCode) Equal(err error) bool

func (ErrorWithCode) Error

func (e ErrorWithCode) Error() string

type ErrorWithCoder

type ErrorWithCoder interface {
	error
	Code() int
	Append(format string, a ...interface{}) ErrorWithCoder
	Equal(err error) bool
}

func Error

func Error(code int, format string, a ...interface{}) ErrorWithCoder

type Index

type Index struct {
	Seq         byte
	NameKey     string
	IndexColumn []string
	Comment     string
	Type        IndexType
	IsUnique    bool
}

func IndexFromSchemaIndexs

func IndexFromSchemaIndexs(v *SchemaIndexsTb) *Index

type IndexEngine

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

func NewIndexEngine

func NewIndexEngine(e *Engine) *IndexEngine

func (*IndexEngine) Count

func (ixe *IndexEngine) Count(table *Table, searchCon *SearchCondition) (count int64, err error)

func (*IndexEngine) Delete

func (ixe *IndexEngine) Delete(table *Table, idInt int64) error

func (*IndexEngine) Drop

func (ixe *IndexEngine) Drop(table *Table, except ...string) error

func (*IndexEngine) DropSingleIndex

func (ixe *IndexEngine) DropSingleIndex(dropIndex *Index) error

func (*IndexEngine) GetId

func (ixe *IndexEngine) GetId(table *Table, searchCon *SearchCondition) (int64, error)

Done:combined index

func (*IndexEngine) IdIsExist

func (ixe *IndexEngine) IdIsExist(table *Table, pkId int64) (bool, error)

func (*IndexEngine) IsExistData

func (ixe *IndexEngine) IsExistData(table *Table, beanValue, reflectVal reflect.Value, cols ...string) (int64, error)

当前数据是否已经存在,存在则返回主键ID,唯一索引的才需要判断是否存在!

func (*IndexEngine) IsExistDataByMap

func (ixe *IndexEngine) IsExistDataByMap(table *Table, valMap map[string]string) (int64, error)

func (*IndexEngine) Range

func (ixe *IndexEngine) Range(table *Table, searchCon *SearchCondition, offset, count int64) (idAry []string, err error)

func (*IndexEngine) ReBuild

func (ixe *IndexEngine) ReBuild(bean interface{}) error

todo:ReBuild single index

func (*IndexEngine) ReBuildByTable

func (ixe *IndexEngine) ReBuildByTable(table *Table) error

func (*IndexEngine) Update

func (ixe *IndexEngine) Update(table *Table, beanValue, reflectVal reflect.Value, cols ...string) error

todo: no thread safety! watch?

func (*IndexEngine) UpdateByMap

func (ixe *IndexEngine) UpdateByMap(table *Table, pkInt int64, valMap map[string]string) error

type IndexType

type IndexType int
const (
	IndexType_UnSupport IndexType = 0
	IndexType_IdMember  IndexType = 1
	IndexType_IdScore   IndexType = 2 //todo:sortedset -> hash
)

type RedisClientProxy

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

func NewRedisCliProxy

func NewRedisCliProxy(redisCli redis.Cmdable) *RedisClientProxy

func (*RedisClientProxy) Del

func (c *RedisClientProxy) Del(keys ...string) *redis.IntCmd

func (*RedisClientProxy) HDel

func (c *RedisClientProxy) HDel(key string, fields ...string) *redis.IntCmd

func (*RedisClientProxy) HGet

func (c *RedisClientProxy) HGet(key string, field string) *redis.StringCmd

func (*RedisClientProxy) HIncrBy

func (c *RedisClientProxy) HIncrBy(key, field string, incr int64) *redis.IntCmd

func (*RedisClientProxy) HIncrByFloat

func (c *RedisClientProxy) HIncrByFloat(key, field string, incr float64) *redis.FloatCmd

func (*RedisClientProxy) HIncrby

func (c *RedisClientProxy) HIncrby(key string, field string, intVal int64) *redis.IntCmd

func (*RedisClientProxy) HIncrbyFloat

func (c *RedisClientProxy) HIncrbyFloat(key string, field string, intVal float64) *redis.FloatCmd

func (*RedisClientProxy) HMGet

func (c *RedisClientProxy) HMGet(key string, fields ...string) *redis.SliceCmd

func (*RedisClientProxy) HMSet

func (c *RedisClientProxy) HMSet(key string, fields map[string]interface{}) *redis.StatusCmd

func (*RedisClientProxy) ZAdd

func (c *RedisClientProxy) ZAdd(key string, members ...redis.Z) *redis.IntCmd

func (*RedisClientProxy) ZAddNX

func (c *RedisClientProxy) ZAddNX(key string, members ...redis.Z) *redis.IntCmd

func (*RedisClientProxy) ZCount

func (c *RedisClientProxy) ZCount(key, min, max string) *redis.IntCmd

func (*RedisClientProxy) ZRangeByScore

func (c *RedisClientProxy) ZRangeByScore(key string, opt redis.ZRangeBy) *redis.StringSliceCmd

func (*RedisClientProxy) ZRem

func (c *RedisClientProxy) ZRem(key string, members ...interface{}) *redis.IntCmd

func (*RedisClientProxy) ZRemRangeByScores

func (c *RedisClientProxy) ZRemRangeByScores(key string, min, max string) *redis.IntCmd

func (*RedisClientProxy) ZRevRangeByScore

func (c *RedisClientProxy) ZRevRangeByScore(key string, opt redis.ZRangeBy) *redis.StringSliceCmd

func (*RedisClientProxy) ZScore

func (c *RedisClientProxy) ZScore(key, member string) *redis.FloatCmd

type SchemaColumnsTb

type SchemaColumnsTb struct {
	Id                int64  `redis_orm:"pk autoincr comment 'ID'"`
	TableId           int64  `redis_orm:"index comment '表ID'"`
	Seq               byte   `redis_orm:"comment '列顺序'"`
	ColumnName        string `redis_orm:"comment '列名'"`
	ColumnComment     string `redis_orm:"dft '' comment '列注释'"`
	DataType          string `redis_orm:"comment '数据类型'"`
	DefaultValue      string `redis_orm:"comment '默认值'"`
	TableIdColumnName string `redis_orm:"combinedindex TableId&ColumnName comment '组合索引(表ID&列名)'"`
	CreatedAt         int64  `redis_orm:"created_at comment '创建时间'"`
	UpdatedAt         int64  `redis_orm:"updated_at comment '修改时间'"`
}

func SchemaColumnsFromColumn

func SchemaColumnsFromColumn(tableId int64, v *Column) *SchemaColumnsTb

type SchemaEngine

type SchemaEngine struct {
	*Engine
}

todo:DB隔离, DB如何兼容已有的Table,暂不用吧,redis有自己的DB

Done:存表、字段、索引结构

Done:逆向生成表Table模型

Done:改表结构? pub/sub, 修改了表结构需要reload table, schemaTable -> mapTable 增加,修改,删除字段,有索引的会自动删除索引 增加,修改,删除索引,重建索引

func NewSchemaEngine

func NewSchemaEngine(e *Engine) *SchemaEngine

func (*SchemaEngine) AddColumn

func (s *SchemaEngine) AddColumn(bean interface{}, cols ...string) error

the bean is new, the column which it is the new need to be added

func (*SchemaEngine) AddIndex

func (s *SchemaEngine) AddIndex(bean interface{}, cols ...string) error

func (*SchemaEngine) AlterTable

func (s *SchemaEngine) AlterTable(sql string) error

createTable by AST ALTER TABLE table_name ADD COLUMN column_name string DEFAULT abc COMMENT 测试列 AFTER updated_at;

ALTER TABLE table_name ADD INDEX index_name uid;

ALTER TABLE table_name ADD INDEX index_name (uid, name);

CREATE TABLE table_name (

column_name1 INT(11) COMMENT 列1,
column_name2 string DEFAULT abc COMMENT 列2,
column_name3 BIGINT(20) created_at COMMENT 添加时间,

) pk(column_name1) autoincr=1 sync2db COMMENT='xx表';

func (*SchemaEngine) CreateTable

func (s *SchemaEngine) CreateTable(bean interface{}) error

func (*SchemaEngine) CreateTableByTable

func (s *SchemaEngine) CreateTableByTable(table *Table) error

func (*SchemaEngine) ReloadTable

func (s *SchemaEngine) ReloadTable(tableName string) (*Table, error)

func (*SchemaEngine) ReloadTables

func (s *SchemaEngine) ReloadTables() ([]*Table, error)

func (*SchemaEngine) RemoveColumn

func (s *SchemaEngine) RemoveColumn(bean interface{}, cols ...string) error

func (*SchemaEngine) RemoveIndex

func (s *SchemaEngine) RemoveIndex(bean interface{}, cols ...string) error

func (*SchemaEngine) ShowTables

func (s *SchemaEngine) ShowTables() []string

func (*SchemaEngine) TableDrop

func (s *SchemaEngine) TableDrop(table *Table) error

type SchemaIndexsTb

type SchemaIndexsTb struct {
	Id               int64  `redis_orm:"pk autoincr comment 'ID'"`
	TableId          int64  `redis_orm:"index comment '表ID'"`
	Seq              byte   `redis_orm:"comment '索引顺序'"`
	IndexName        string `redis_orm:"comment '索引名'"`
	IndexComment     string `redis_orm:"dft '' comment '索引注释'"`
	IndexColumn      string `redis_orm:"comment '索引字段,&分割'"`
	IndexType        int    `redis_orm:"comment '数据类型'"`
	IsUnique         bool   `redis_orm:"comment '是否唯一索引'"`
	TableIdIndexName string `redis_orm:"combinedindex TableId&IndexName comment '组合索引(表ID&索引名)'"`
	CreatedAt        int64  `redis_orm:"created_at comment '创建时间'"`
	UpdatedAt        int64  `redis_orm:"updated_at comment '修改时间'"`
}

func SchemaIndexsFromColumn

func SchemaIndexsFromColumn(tableId int64, v *Index) *SchemaIndexsTb

type SchemaTablesTb

type SchemaTablesTb struct {
	Id            int64  `redis_orm:"pk autoincr comment 'ID'"`
	TableName     string `redis_orm:"unique comment '唯一'"`
	TableComment  string `redis_orm:"dft '' comment '表注释'"` //暂时没用上
	PrimaryKey    string `redis_orm:"comment '主键字段'"`
	AutoIncrement string `redis_orm:"comment '自增字段'"`
	IsSync2DB     bool   `redis_orm:"comment '是否同步到数据库'"`
	Created       string `redis_orm:"comment '创建时间字段'"`
	Updated       string `redis_orm:"comment '更新时间字段'"`
	//Version       int32  `redis_orm:"comment '版本'"`
	CreatedAt int64 `redis_orm:"created_at comment '创建时间'"`
	UpdatedAt int64 `redis_orm:"updated_at comment '修改时间'"`
}

SET @table_schema='employees'; SELECT

table_name,
table_type,
engine,
table_rows,
avg_row_length,
data_length,
index_length,
table_collation,
create_time

FROM

information_schema.tables

WHERE

table_schema = @table_schema

ORDER BY table_name;

func SchemaTablesFromTable

func SchemaTablesFromTable(table *Table) *SchemaTablesTb

type SearchCondition

type SearchCondition struct {
	SearchColumn []string
	//IndexType     IndexType
	FieldMaxValue interface{}
	FieldMinValue interface{}
	IsAsc         bool
}

func NewSearchCondition

func NewSearchCondition(indexType IndexType, minVal, maxVal interface{}, column ...string) *SearchCondition

NewSearchCondition will be deprecated, please use NewSearchConditionV2 instead

func NewSearchConditionV2

func NewSearchConditionV2(minVal, maxVal interface{}, column ...string) *SearchCondition

func (*SearchCondition) IsEqualIndexName

func (s *SearchCondition) IsEqualIndexName(index *Index) bool

func (*SearchCondition) Name

func (s *SearchCondition) Name() string

type Session

type Session struct {
}

todo: Chain methods => where a=a and b=b and c>c order by d desc todo: transaction

type Table

type Table struct {
	TableId int64
	Name    string
	Comment string
	//Version int32
	//Type          reflect.Type
	ColumnsSeq    []string
	ColumnsMap    map[string]*Column
	IndexesMap    map[string]*Index
	PrimaryKey    string
	AutoIncrement string
	IsSync2DB     bool
	Created       string
	Updated       string
	// contains filtered or unexported fields
}

func NewEmptyTable

func NewEmptyTable() *Table

func TableFromSchemaTables

func TableFromSchemaTables(table *SchemaTablesTb) *Table

func (*Table) AddColumn

func (table *Table) AddColumn(col *Column)

func (*Table) AddIndex

func (table *Table) AddIndex(typ string, indexColumn, columnName, comment string, isUnique bool, seq byte)

func (*Table) GetAutoIncrKey

func (table *Table) GetAutoIncrKey() string

func (*Table) GetIndexKey

func (table *Table) GetIndexKey(col string) string

func (*Table) GetTableKey

func (table *Table) GetTableKey() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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