tableorm

package module
v0.0.0-...-3c26c41 Latest Latest
Warning

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

Go to latest
Published: Apr 14, 2021 License: MIT Imports: 10 Imported by: 0

README

TableORM

简介

通过ORM的方式简化阿里云TableStore使用。

项目起源

一直想找一个合适的serverless数据库,看上了阿里云的TableStore,但是API设计的太繁琐,于是参考gorm的接口后就写了这个项目打算封装一下,不过后来发现用了套路云多元索引后强制预留CU资源,每个小时都会产生费用,因此serverless就没什么意义了,不过代码还是放上来,供不差钱的朋友们使用吧。

约定

  • 为了简化逻辑,约定每个结构体都有一个ID(_id)字段,作为TableStore的主键,有且仅有一个,其余字段作为column存在。
  • 每个字段默认自动创建对应类型的多元索引,可以通过tag禁止创建对应字段的索引。

使用


import (
	"github.com/diemus/tableorm"
	"github.com/diemus/tableorm/query"
)

type User struct {
	ID       string `json:"_id"` //默认必须有的字段,作为主键
	Username string `json:"username" index:"text"` //索引会根据类型进行推断,但是也可以主动指定
	Age      int64  `json:"age"`
	Extra    string `json:"extra" index:"-"` //表示不建立索引
}

type Book struct {
	ID      string  `json:"_id"`
	Caption string  `json:"caption" index:"-"` //不开启索引
	Test    string  `json:"-"`                 //不储存到tablestore
	Count   int64   `json:"count"`
	IsReady bool    `json:"isReady"`
	Price   float64 `json:"price"`
}

func main() {
	db := tableorm.NewDB(
		"https://xxxxx.ots.aliyuncs.com",
		"xxxx",
		"xxxx",
		"xxxxx",
	)

	//自动建表+索引
	db.AutoMigrate(User{}, Book{})

	//创建+修改
	user1 := User{Username: "sam", Age: 16}
	user2 := User{Username: "tom", Age: 32}
	db.Save(user1, user2) //可以传入多个,批量创建

	//查询
	user := User{}
	db.Query(query.TermQuery("username", "sam")).Find(&user)

	//复杂查询
	q1 := query.Not(query.TermQuery("username", "tom"))
	q2 := query.And(query.TermsQuery("age", 10, 12, 13), query.RangeQuery("age", ">", 15))
	q3 := query.Or(q1, q2)
	db.Query(q1,q2,q3).Find(&user)

	//删除
	db.Delete(user1,user2) //可以传入多个,批量删除
}


Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	NotResultFound  = fmt.Errorf("no result found")
	NotAllSuccess   = fmt.Errorf("no all success")
	IDFieldNotExist = fmt.Errorf(`primary key "_id" must be define`)
)

Functions

func CheckModel

func CheckModel(obj interface{}) error

检查模型定义是否符合要求,防止出错

func CreateIndexSchema

func CreateIndexSchema(obj interface{}) ([]*tablestore.FieldSchema, error)

func EnsureID

func EnsureID(obj interface{}) (string, error)

检查ID是否为空,为空自动生成一个uuid

func GetBatchWriteResult

func GetBatchWriteResult(resp *tablestore.BatchWriteRowResponse) error

判断是否部分失败,一般概率较小,因为所有请求都是统一格式的且为Ignore,不容易有这种错误 但是一旦发生不好排查,因为pk是空的,无法确认是那个对象失败了

func GetDeleteRowChange

func GetDeleteRowChange(obj interface{}) (*tablestore.DeleteRowChange, error)

func GetFieldNameMap

func GetFieldNameMap(obj interface{}) (map[string]string, map[string]string, error)

func GetSaveRowChange

func GetSaveRowChange(obj interface{}) (*tablestore.PutRowChange, error)

func GetTableName

func GetTableName(obj interface{}) string

func LoadData

func LoadData(obj interface{}, row *tablestore.Row) error

Types

type DB

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

func NewDB

func NewDB(endPoint, instanceName, accessKeyId, accessKeySecret string, options ...tablestore.ClientOption) *DB

func (*DB) AutoMigrate

func (db *DB) AutoMigrate(models ...interface{})

自动根据结构体创建或者更新表和索引

func (*DB) Count

func (db *DB) Count(num *int) error

func (*DB) CreateIndex

func (db *DB) CreateIndex(obj interface{}) error

根据tag创建索引,默认所有字段都创建对应类型的索引,可以通过index tag覆盖默认

func (*DB) CreateTable

func (db *DB) CreateTable(obj interface{}) error

创建表,表名为结构体小写,主键约定为 _id string

func (*DB) Delete

func (db *DB) Delete(objList ...interface{}) error

func (*DB) DeleteIndex

func (db *DB) DeleteIndex(obj interface{}) error

func (*DB) DeleteTable

func (db *DB) DeleteTable(obj interface{}) error

删除表

func (*DB) Find

func (db *DB) Find(obj interface{}) error

func (*DB) FindByToken

func (db *DB) FindByToken(obj interface{}, token []byte) (nextToken []byte, err error)

func (*DB) First

func (db *DB) First(obj interface{}) error

只有First,如果需要Last,则自行将排序反过来,即可获取最后一个

func (*DB) Limit

func (db *DB) Limit(n int) *DB

当需要获取的总条数小于2000行时,可以通过limit和offset进行翻页,limit+offset <= 2000。

func (*DB) Offset

func (db *DB) Offset(n int) *DB

当需要获取的总条数小于2000行时,可以通过limit和offset进行翻页,limit+offset <= 2000。

func (*DB) Query

func (db *DB) Query(queries ...search.Query) *DB

func (*DB) Save

func (db *DB) Save(objList ...interface{}) ([]interface{}, error)

批量保存,并返回保存后的对象,方便获取ID

func (*DB) SortByField

func (db *DB) SortByField(field string, asc bool) *DB

func (*DB) SortByGeoDistance

func (db *DB) SortByGeoDistance(field string, points []string) *DB

func (*DB) SortByPrimaryKey

func (db *DB) SortByPrimaryKey(asc bool) *DB

func (*DB) SortByScore

func (db *DB) SortByScore(asc bool) *DB

func (*DB) Token

func (db *DB) Token(token []byte) *DB

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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