model

package
v0.10.3 Latest Latest
Warning

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

Go to latest
Published: Feb 1, 2023 License: Apache-2.0 Imports: 27 Imported by: 12

Documentation

Index

Constants

View Source
const (
	RelHasOne         = "hasOne"         // 1 v 1
	RelHasMany        = "hasMany"        // 1 v n
	RelBelongsTo      = "belongsTo"      // inverse  1 v 1 / 1 v n / n v n
	RelHasOneThrough  = "hasOneThrough"  // 1 v 1 ( t1 <-> t2 <-> t3)
	RelHasManyThrough = "hasManyThrough" // 1 v n ( t1 <-> t2 <-> t3)
	RelBelongsToMany  = "belongsToMany"  // 1 v1 / 1 v n / n v n
	RelMorphOne       = "morphOne"
	RelMorphMany      = "morphMany"
	RelMorphToMany    = "morphToMany"
	RelMorphByMany    = "morphByMany"
	RelMorphMap       = "morphMap"
)

Relationship types

Variables

View Source
var Encryptors = map[string]*Encryptor{}

Encryptors 已加载加密器

View Source
var IEncryptors = map[string]IEncryptor{
	"AES":      &EncryptorAES{},
	"PASSWORD": &EncryptorPassword{},
}

IEncryptors 加密码器接口映射

View Source
var ModelHandlers = map[string]process.Handler{
	"find":                processFind,
	"get":                 processGet,
	"paginate":            processPaginate,
	"selectoption":        processSelectOption,
	"create":              processCreate,
	"update":              processUpdate,
	"save":                processSave,
	"delete":              processDelete,
	"destroy":             processDestroy,
	"insert":              processInsert,
	"updatewhere":         processUpdateWhere,
	"deletewhere":         processDeleteWhere,
	"destroywhere":        processDestroyWhere,
	"eachsave":            processEachSave,
	"eachsaveafterdelete": processEachSaveAfterDelete,
}

ModelHandlers 模型运行器

View Source
var Models = map[string]*Model{}

Models 已载入模型

View Source
var Validations = map[string]func(value interface{}, row maps.MapStrAny, args ...interface{}) bool{
	"typof":     ValidationTypeof,
	"min":       ValidationMin,
	"max":       ValidationMax,
	"enum":      ValidationEnum,
	"pattern":   ValidationPattern,
	"minLength": ValidationMinLength,
	"maxLength": ValidationMaxLength,
	"email":     ValidationEmail,
	"mobile":    ValidationMobile,
}

Validations 数据校验函数

Functions

func ValidationEmail

func ValidationEmail(value interface{}, _ maps.MapStrAny, _ ...interface{}) bool

ValidationEmail 验证邮箱

func ValidationEnum

func ValidationEnum(value interface{}, _ maps.MapStrAny, args ...interface{}) bool

ValidationEnum 枚举型

func ValidationMax

func ValidationMax(value interface{}, _ maps.MapStrAny, args ...interface{}) bool

ValidationMax 最大值

func ValidationMaxLength

func ValidationMaxLength(value interface{}, _ maps.MapStrAny, args ...interface{}) bool

ValidationMaxLength 最大长度

func ValidationMin

func ValidationMin(value interface{}, _ maps.MapStrAny, args ...interface{}) bool

ValidationMin 最小值

func ValidationMinLength

func ValidationMinLength(value interface{}, _ maps.MapStrAny, args ...interface{}) bool

ValidationMinLength 最小长度

func ValidationMobile

func ValidationMobile(value interface{}, _ maps.MapStrAny, args ...interface{}) bool

ValidationMobile 验证手机号

func ValidationPattern

func ValidationPattern(value interface{}, _ maps.MapStrAny, args ...interface{}) bool

ValidationPattern 正则匹配

func ValidationTypeof

func ValidationTypeof(value interface{}, _ maps.MapStrAny, args ...interface{}) bool

ValidationTypeof 校验数值类型

Types

type Column

type Column struct {
	Label       string       `json:"label,omitempty"`
	Name        string       `json:"name"`
	Type        string       `json:"type,omitempty"`
	Title       string       `json:"title,omitempty"`
	Description string       `json:"description,omitempty"`
	Comment     string       `json:"comment,omitempty"`
	Length      int          `json:"length,omitempty"`
	Precision   int          `json:"precision,omitempty"`
	Scale       int          `json:"scale,omitempty"`
	Nullable    bool         `json:"nullable,omitempty"`
	Option      []string     `json:"option,omitempty"`
	Default     interface{}  `json:"default,omitempty"`
	DefaultRaw  string       `json:"default_raw,omitempty"`
	Example     interface{}  `json:"example,omitempty"`
	Generate    string       `json:"generate,omitempty"` // Increment, UUID,...
	Crypt       string       `json:"crypt,omitempty"`    // AES, PASSWORD, AES-256, AES-128, PASSWORD-HASH, ...
	Validations []Validation `json:"validations,omitempty"`
	Index       bool         `json:"index,omitempty"`
	Unique      bool         `json:"unique,omitempty"`
	Primary     bool         `json:"primary,omitempty"`
	// contains filtered or unexported fields
}

Column the field description struct

func (*Column) FliterIn

func (column *Column) FliterIn(value interface{}, row maps.MapStrAny)

FliterIn 输入过滤器

func (*Column) FliterOut

func (column *Column) FliterOut(value interface{}, row maps.MapStrAny, export ...string)

FliterOut 输出过滤器

func (*Column) Map

func (column *Column) Map() map[string]interface{}

Map 转换为Map

func (Column) SetOption

func (column Column) SetOption(col *schema.Column)

SetOption 设置字段选项

func (Column) SetType

func (column Column) SetType(table schema.Blueprint) *schema.Column

SetType 设置字段类型

func (*Column) Validate

func (column *Column) Validate(value interface{}, row maps.MapStrAny) (bool, []string)

Validate 数值有效性验证

type ColumnMap

type ColumnMap struct {
	Column *Column
	Model  *Model
	Export string // 取值时的变量名
}

ColumnMap ColumnMap 字段映射

type Encryptor

type Encryptor struct {
	Name   string `json:"-"`                // 名称
	Salt   string `json:"salt,omitempty"`   // 盐
	Key    string `json:"key,omitempty"`    // 钥匙
	Secret string `json:"secret,omitempty"` // 密钥
}

Encryptor 加密器

func WithCrypt

func WithCrypt(data []byte, name string) (*Encryptor, error)

WithCrypt 载入数据加密器

type EncryptorAES

type EncryptorAES struct{ *Encryptor }

EncryptorAES AES

func (EncryptorAES) Decode

func (aes EncryptorAES) Decode(field string) (string, error)

Decode AES Decode

func (EncryptorAES) Encode

func (aes EncryptorAES) Encode(value string) (string, error)

Encode AES Encode

func (*EncryptorAES) Set

func (aes *EncryptorAES) Set(crypt *Encryptor)

Set AES Encode

func (EncryptorAES) Validate

func (aes EncryptorAES) Validate(hash string, field string) bool

Validate AES Decode

type EncryptorAES128

type EncryptorAES128 struct{ Encryptor }

EncryptorAES128 AES 128

type EncryptorAES256

type EncryptorAES256 struct{ Encryptor }

EncryptorAES256 AES 256

type EncryptorPassword

type EncryptorPassword struct{ *Encryptor }

EncryptorPassword 密码加密

func (EncryptorPassword) Decode

func (pwd EncryptorPassword) Decode(value string) (string, error)

Decode PASSWORD Decode

func (EncryptorPassword) Encode

func (pwd EncryptorPassword) Encode(value string) (string, error)

Encode PASSWORD Encode

func (*EncryptorPassword) Set

func (pwd *EncryptorPassword) Set(crypt *Encryptor)

Set AES Encode

func (EncryptorPassword) Validate

func (pwd EncryptorPassword) Validate(hash string, value string) bool

Validate PASSWORD Decode

type ExportData

type ExportData struct {
	Model   string          `json:"model"`
	Columns []string        `json:"columns"`
	Values  [][]interface{} `json:"values"`
}

ExportData the export data struct

type IEncryptor

type IEncryptor interface {
	Set(crypt *Encryptor)
	Encode(value string) (string, error)
	Decode(value string) (string, error)
	Validate(hash string, value string) bool
}

IEncryptor 加密器接口

func SelectCrypt

func SelectCrypt(name string) (IEncryptor, error)

SelectCrypt 选择加密器

type Index

type Index struct {
	Comment string   `json:"comment,omitempty"`
	Name    string   `json:"name,omitempty"`
	Columns []string `json:"columns,omitempty"`
	Type    string   `json:"type,omitempty"` // primary,unique,index,match
}

Index the search index struct

func (Index) SetIndex

func (index Index) SetIndex(table schema.Blueprint)

SetIndex 设置索引

type MetaData

type MetaData struct {
	Name      string              `json:"name,omitempty"`      // 元数据名称
	Connector string              `json:"connector,omitempty"` // Bind a connector, MySQL, SQLite, Postgres, Clickhouse, Tidb, Oracle support. default is SQLite
	Table     Table               `json:"table,omitempty"`     // 数据表选项
	Columns   []Column            `json:"columns,omitempty"`   // 字段定义
	Indexes   []Index             `json:"indexes,omitempty"`   // 索引定义
	Relations map[string]Relation `json:"relations,omitempty"` // 映射关系定义
	Values    []maps.MapStrAny    `json:"values,omitempty"`    // 初始数值
	Option    Option              `json:"option,omitempty"`    // 元数据配置
}

MetaData 元数据

type Model

type Model struct {
	ID            string
	Name          string
	File          string
	Driver        string // Driver
	MetaData      MetaData
	Columns       map[string]*Column // 字段映射表
	ColumnNames   []interface{}      // 字段名称清单
	PrimaryKey    string             // 主键(单一主键)
	PrimaryKeys   []string           // 主键(联合主键)
	UniqueColumns []*Column          // 唯一字段清单
}

Model 数据模型

func Load

func Load(file string, id string) (*Model, error)

Load 载入数据模型

func Select

func Select(id string) *Model

Select 读取已加载模型

func (*Model) Blueprint

func (mod *Model) Blueprint() (types.Blueprint, error)

Blueprint cast to the blueprint struct

func (*Model) Create

func (mod *Model) Create(row maps.MapStrAny) (int, error)

Create 创建单条数据, 返回新创建数据ID

func (*Model) CreateTable

func (mod *Model) CreateTable() error

CreateTable create the table of the model

func (*Model) Delete

func (mod *Model) Delete(id interface{}) error

Delete 删除单条记录

func (*Model) DeleteWhere

func (mod *Model) DeleteWhere(param QueryParam) (int, error)

DeleteWhere 批量删除数据, 返回更新行数

func (*Model) Destroy

func (mod *Model) Destroy(id interface{}) error

Destroy 真删除单条记录

func (*Model) DestroyWhere

func (mod *Model) DestroyWhere(param QueryParam) (int, error)

DestroyWhere 批量真删除数据, 返回更新行数

func (*Model) DropTable

func (mod *Model) DropTable() error

DropTable drop the table of the model

func (*Model) EachSave

func (mod *Model) EachSave(rows []map[string]interface{}, eachrow ...maps.MapStrAny) ([]interface{}, error)

EachSave 批量保存数据, 返回数据ID集合

func (*Model) Export

func (mod *Model) Export(chunkSize int, process func(curr, total int)) ([]string, error)

Export the model

func (*Model) Filterselect

func (mod *Model) Filterselect(alias string, columns []interface{}, cmap map[string]ColumnMap, exportPrefix string) []interface{}

Filterselect 选择字段

func (*Model) Find

func (mod *Model) Find(id interface{}, param QueryParam) (maps.MapStr, error)

Find 查询单条记录

func (*Model) FliterIn

func (mod *Model) FliterIn(row maps.MapStrAny)

FliterIn 输入前过滤解码

func (*Model) FliterOut

func (mod *Model) FliterOut(row maps.MapStrAny)

FliterOut 输出前过滤解码

func (*Model) FliterWhere

func (mod *Model) FliterWhere(alias string, col interface{}) interface{}

FliterWhere 选项

func (*Model) Get

func (mod *Model) Get(param QueryParam) ([]maps.MapStr, error)

Get 按条件查询, 不分页

func (*Model) HasTable

func (mod *Model) HasTable() (bool, error)

HasTable check if the table of the model is exists

func (*Model) Import

func (mod *Model) Import(file string) error

Import the data

func (*Model) Insert

func (mod *Model) Insert(columns []string, rows [][]interface{}) error

Insert 插入多条数据

func (*Model) InsertValues

func (mod *Model) InsertValues() ([]int, []error)

InsertValues insert the default values of the model

func (*Model) Migrate

func (mod *Model) Migrate(force bool) error

Migrate 数据迁移

func (*Model) MustCreate

func (mod *Model) MustCreate(row maps.MapStrAny) int

MustCreate 创建单条数据, 返回新创建数据ID, 失败抛出异常

func (*Model) MustDelete

func (mod *Model) MustDelete(id interface{})

MustDelete 删除单条记录, 失败抛出异常

func (*Model) MustDeleteWhere

func (mod *Model) MustDeleteWhere(param QueryParam) int

MustDeleteWhere 批量删除数据, 返回更新行数, 失败抛出异常

func (*Model) MustDestroy

func (mod *Model) MustDestroy(id interface{})

MustDestroy 真删除单条记录, 失败抛出异常

func (*Model) MustDestroyWhere

func (mod *Model) MustDestroyWhere(param QueryParam) int

MustDestroyWhere 批量真删除数据, 返回更新行数, 失败抛出异常

func (*Model) MustEachSave

func (mod *Model) MustEachSave(rows []map[string]interface{}, eachrow ...maps.MapStrAny) []interface{}

MustEachSave 批量保存数据, 返回数据ID集合, 失败抛出异常

func (*Model) MustFind

func (mod *Model) MustFind(id interface{}, param QueryParam) maps.MapStr

MustFind 查询单条记录

func (*Model) MustGet

func (mod *Model) MustGet(param QueryParam) []maps.MapStr

MustGet 按条件查询, 不分页, 失败抛出异常

func (*Model) MustInsert

func (mod *Model) MustInsert(columns []string, rows [][]interface{})

MustInsert 插入多条数据, 失败抛出异常

func (*Model) MustPaginate

func (mod *Model) MustPaginate(param QueryParam, page int, pagesize int) maps.MapStr

MustPaginate 按条件查询, 分页, 失败抛出异常

func (*Model) MustSave

func (mod *Model) MustSave(row maps.MapStrAny) interface{}

MustSave 保存单条数据, 返回数据ID, 失败抛出异常

func (*Model) MustUpdate

func (mod *Model) MustUpdate(id interface{}, row maps.MapStrAny)

MustUpdate 更新单条数据, 失败抛出异常

func (*Model) MustUpdateWhere

func (mod *Model) MustUpdateWhere(param QueryParam, row maps.MapStrAny) int

MustUpdateWhere 按条件更新记录, 返回更新行数, 失败抛出异常

func (*Model) Paginate

func (mod *Model) Paginate(param QueryParam, page int, pagesize int) (maps.MapStr, error)

Paginate 按条件查询, 分页

func (*Model) Reload

func (mod *Model) Reload() (*Model, error)

Reload 更新模型

func (*Model) Save

func (mod *Model) Save(row maps.MapStrAny) (interface{}, error)

Save 保存单条数据, 不存在创建记录, 存在更新记录, 返回数据ID

func (*Model) SaveTable

func (mod *Model) SaveTable() error

SaveTable update or create the table of the model

func (*Model) Update

func (mod *Model) Update(id interface{}, row maps.MapStrAny) error

Update 更新单条数据

func (*Model) UpdateWhere

func (mod *Model) UpdateWhere(param QueryParam, row maps.MapStrAny) (int, error)

UpdateWhere 按条件更新记录, 返回更新行数

func (*Model) Validate

func (mod *Model) Validate(row maps.MapStrAny) []ValidateResponse

Validate 数值校验

type Option

type Option struct {
	Timestamps  bool `json:"timestamps,omitempty"`   // + created_at, updated_at 字段
	SoftDeletes bool `json:"soft_deletes,omitempty"` // + deleted_at 字段
	Trackings   bool `json:"trackings,omitempty"`    // + created_by, updated_by, deleted_by 字段
	Constraints bool `json:"constraints,omitempty"`  // + 约束定义
	Permission  bool `json:"permission,omitempty"`   // + __permission 字段
	Logging     bool `json:"logging,omitempty"`      // + __logging_id 字段
	Readonly    bool `json:"read_only,omitempty"`    // Ignore the migrate operation
}

Option 模型配置选项

type QueryOrder

type QueryOrder struct {
	Rel    string `json:"rel,omitempty"` // Relation Name
	Column string `json:"column"`
	Option string `json:"option,omitempty"` // desc, asc
}

QueryOrder Order 查询排序

type QueryParam

type QueryParam struct {
	Model    string          `json:"model,omitempty"`
	Table    string          `json:"table,omitempty"`
	Alias    string          `json:"alias,omitempty"`
	Export   string          `json:"export,omitempty"` // 导出前缀
	Select   []interface{}   `json:"select,omitempty"` // string | dbal.Raw
	Wheres   []QueryWhere    `json:"wheres,omitempty"`
	Orders   []QueryOrder    `json:"orders,omitempty"`
	Limit    int             `json:"limit,omitempty"`
	Page     int             `json:"page,omitempty"`
	PageSize int             `json:"pagesize,omitempty"`
	Withs    map[string]With `json:"withs,omitempty"`
}

QueryParam 数据查询器参数

func AnyToQueryParam

func AnyToQueryParam(v interface{}) (QueryParam, bool)

AnyToQueryParam interface 转换为 QueryParams

func URLToQueryParam

func URLToQueryParam(values url.Values) QueryParam

URLToQueryParam url.Values 转换为 QueryParams

func (QueryParam) NewQuery

func (param QueryParam) NewQuery() *QueryStack

NewQuery 新建查询栈

func (QueryParam) Order

func (param QueryParam) Order(order QueryOrder, qb query.Query, mod *Model)

Order 排序条件

func (QueryParam) Query

func (param QueryParam) Query(stack *QueryStack, stackParams ...QueryStackParam) *QueryStack

Query 构建查询栈(本版先实现,下一版本根据实际应用场景迭代)

func (QueryParam) Where

func (param QueryParam) Where(where QueryWhere, qb query.Query, mod *Model)

Where 查询条件

func (QueryParam) With

func (param QueryParam) With(name string, stack *QueryStack, with With, mod *Model)

With 关联查询

type QueryStack

type QueryStack struct {
	Builders []QueryStackBuilder
	Params   []QueryStackParam
	Current  int
}

QueryStack 查询栈

func MakeQueryStack

func MakeQueryStack() *QueryStack

MakeQueryStack 创建查询栈

func NewQueryStack

func NewQueryStack(param QueryParam) *QueryStack

NewQueryStack 新建查询栈

func (*QueryStack) Builder

func (stack *QueryStack) Builder() *QueryStackBuilder

Builder 返回当前查询构建器

func (*QueryStack) FirstQuery

func (stack *QueryStack) FirstQuery() query.Query

FirstQuery 返回第一个查询器

func (*QueryStack) Len

func (stack *QueryStack) Len() int

Len 查询器数量

func (*QueryStack) Merge

func (stack *QueryStack) Merge(new *QueryStack)

Merge 合并 Stack

func (*QueryStack) Next

func (stack *QueryStack) Next() int

Next 返回下一个查询器

func (*QueryStack) Paginate

func (stack *QueryStack) Paginate(page int, pagesize int) maps.MapStrAny

Paginate 执行查询栈(分页查询)

func (*QueryStack) Push

func (stack *QueryStack) Push(builder QueryStackBuilder, param QueryStackParam)

Push 添加查询器

func (*QueryStack) Query

func (stack *QueryStack) Query() query.Query

Query 返回当前查询器

func (*QueryStack) QueryParam

func (stack *QueryStack) QueryParam() QueryParam

QueryParam 返回当前查询参数

func (*QueryStack) Relation

func (stack *QueryStack) Relation() Relation

Relation 返回当前查询参数

func (*QueryStack) Run

func (stack *QueryStack) Run() []maps.MapStrAny

Run 执行查询栈

type QueryStackBuilder

type QueryStackBuilder struct {
	Model     *Model
	Query     query.Query
	ColumnMap map[string]ColumnMap
}

QueryStackBuilder 查询构建器

type QueryStackParam

type QueryStackParam struct {
	QueryParam   QueryParam
	Relation     Relation
	ExportPrefix string // 字段导出前缀
}

QueryStackParam QueryStack 查询参数

type QueryWhere

type QueryWhere struct {
	Rel    string       `json:"rel,omitempty"` // Relation Name
	Column interface{}  `json:"column,omitempty"`
	Value  interface{}  `json:"value,omitempty"`
	Method string       `json:"method,omitempty"` // where,orwhere, wherein, orwherein...
	OP     string       `json:"op,omitempty"`     // 操作 eq/gt/lt/ge/le/like...
	Wheres []QueryWhere `json:"wheres,omitempty"` // 分组查询
}

QueryWhere Where 查询条件

type Relation

type Relation struct {
	Name    string     `json:"-"`
	Type    string     `json:"type"`
	Key     string     `json:"key,omitempty"`
	Model   string     `json:"model,omitempty"`
	Foreign string     `json:"foreign,omitempty"`
	Links   []Relation `json:"links,omitempty"`
	Query   QueryParam `json:"query,omitempty"`
}

Relation the new xun model relation

type Table

type Table struct {
	Name        string   `json:"name,omitempty"`   // optional, if not set, the default is generate from model name. eg name.space.user, table name is name_space_user
	Prefix      string   `json:"prefix,omitempty"` // optional, the table prefix
	Comment     string   `json:"comment,omitempty"`
	Engine      string   `json:"engine,omitempty"` // InnoDB,MyISAM ( MySQL Only )
	Collation   string   `json:"collation"`
	Charset     string   `json:"charset"`
	PrimaryKeys []string `json:"primarykeys"`
}

Table the model mapping table in DB

type ValidateResponse

type ValidateResponse struct {
	Line     int      `json:"line,omitempty"`
	Column   string   `json:"column,omitempty"`
	Messages []string `json:"messages,omitempty"`
}

ValidateResponse 数据校验返回结果

type Validation

type Validation struct {
	Method  string        `json:"method"`
	Args    []interface{} `json:"args,omitempty"`
	Message string        `json:"message,omitempty"`
}

Validation the field validation struct

type With

type With struct {
	Name  string     `json:"name"`
	Query QueryParam `json:"query,omitempty"`
}

With relations 关联查询

Jump to

Keyboard shortcuts

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