| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893 |
- package DB
- import (
- "TsDB2/DB/core/page"
- "TsDB2/DB/core/types"
- "errors"
- "fmt"
- "math/big"
- "reflect"
- "sort"
- "strconv"
- "strings"
- )
- // FieldDef ORM 字段定义
- type FieldDef struct {
- Name string // Go 字段名
- ColName string // 数据库列名 (来自 vrtx tag 或字段名)
- FieldType types.FieldType // 存储类型
- // Flag 列级标志 (随 schema 落盘, 直接透传给 types.FieldInfo.Flag):
- // - 低 5 位: 列级类型参数【按类型解释】——
- // FieldType_Decimal 是小数位数 scale (0..types.MaxDecimalScale),
- // 来自 `vrtx:"decimal:2"` / `vrtx:"scale:2"`;
- // FieldType_String 是行内宽度码, 来自
- // `vrtx:"maxlen:N"` (见 maxlenToColumn; N 的上界是
- // types.MaxStringSize, 超了在建模阶段就报错);
- // - 状态位: types.FlagNullable (来自 `vrtx:"nullable"`);
- // types.FlagUnique (来自 `vrtx:"unique"`, 唯一约束; NULL 不参与);
- // types.FlagDeleted 由核心层 DropField 置位, 声明侧不设。
- //
- // Decimal 的保序前提是"同一列 scale 一致", 字符串列的定宽前提是"同一列宽度码
- // 一致" —— 两者都必须作为列元数据存下来, 而不能只活在 Go 类型里 (见 types.FieldSize)。
- Flag byte
- GoKind reflect.Kind // Go 原始类型
- // GoPath 反射取值路径 (FieldByIndex 用)。ParseModel 时经 Type.FieldByName
- // 一次性解析 (含嵌入提升链); 逐行 structToFieldValues 直接按路径取字段,
- // 省掉每行每列一次 FieldByName 的类型级搜索 (批量灌数实测 ~8% CPU)。
- // 为 nil 时 (字段不在结构体里 / 提升路径特殊) 调用方退回 findField 老路径。
- GoPath []int
- Index int // 该字段在 AllFields 中的位置
- IsPK bool // 用户声明的主键字段 (vrtx:"pk" / 显式列名 _id)
- }
- // Param 列级类型参数 (Flag 低 5 位): Decimal 读作 scale, FieldType_String 读作宽度码。
- func (fd FieldDef) Param() byte { return fd.Flag & types.FlagScaleMask }
- // Width 该列在行内的实际宽度 (字节)。
- //
- // 不能写成 types.GetSize(fd.FieldType): 那只是【类型默认】宽度, 对 `maxlen:1000`
- // 这种用宽度码声明出来的列会算成 256 —— ORM 侧任何按这个宽度补零/截断的地方, 都会
- // 与引擎按 1024 存下来的字节不同源。宽度只认这一处 (转发给 types.FieldSize)。
- func (fd FieldDef) Width() uint16 { return types.FieldSize(fd.FieldType, fd.Param()) }
- // IndexDef 从结构体标签解析的二级索引定义
- type IndexDef struct {
- Name string // 索引名 (空=自动生成 idx_表名_首个字段名)
- FieldID byte // 首个字段在 CoreFields 中的位置 (单列索引)
- FieldIDs []byte // 索引分量在 CoreFields 中的位置, 按键序 (复合索引)
- ColName string // 首个字段列名 (用于自动生成索引名)
- IndexType page.IndexType // 索引类型 (默认 BTree)
- Unique bool // 唯一索引: 同一索引键只允许一行, NULL 分量不参与 (可多行 NULL)
- }
- // coreFieldIDs 返回 core.CreateIndex 需要的分量列表
- func (d IndexDef) coreFieldIDs() []byte {
- if len(d.FieldIDs) > 0 {
- return d.FieldIDs
- }
- return []byte{d.FieldID}
- }
- // 自动索引名的前缀。
- //
- // 索引元数据链本来就是「每表独有」的 —— TableInfo.FirstIndexID 指向本表自己的
- // IndexMeta 链, 所以索引名只需要表内唯一, 表名前缀并不是唯一性所必需的。保留它
- // 纯粹是为了维持既有的 pk_<表名> / idx_<表名>_<列名> 命名, 不破坏已引用这两个名字的代码。
- //
- // 代价: 这两个前缀要占用 core.IndexNameSize 的额度 —— 注意是索引名的, 不是表名的。
- // 因为 IndexNameSize(64) 比 TableNameSize(48) 宽出 16 字节, 前缀这笔账只从索引名里出,
- // 表名依旧可以用满 48 —— 这正是把索引名单独放宽的目的。
- // UseTable 会在建表前把这笔账算清楚 (checkNameBudget), 而不是等到建索引时才报错。
- const (
- pkIndexPrefix = "pk_" // 主键索引: pk_<表名>
- idxIndexPrefix = "idx_" // 自动二级索引: idx_<表名>_<列名>
- )
- // 主键列默认列名: 引擎的行主键号 (pkID) 固定 8 字节, ORM 用这一列把它镜像进结构体。
- // BaseModel / PrimaryModel 默认就是这一列 (TimeSeriesModel 是 _ts), 表可以用 vrtx:"pk"
- // 换成自己的列名; 写 `vrtx:"_id"` 等价于声明这个列名作主键 (见 parseField)。
- const pkColumnName = "_id"
- // 时序表默认的时序键列名。时序键是该表的"主键" —— 它是时序索引的分段键, 决定这一行
- // 落在哪个时间段, 也是 ORM 头部 Load/Reload/Delete 默认的定位键。用户写 `vrtx:"pk"`
- // 时同样可以换成自己的列。
- //
- // 注意它【不是】引擎行号 (pkID): 时序索引的 DataPage 里, 行首 8 字节才是 pkID, 时间键
- // 是紧跟着的第一个字段。两者之所以必须分开, 是因为同一个时间戳下允许存在多行
- // (同一时刻的多个测点 / 多次事件) —— 时间键只能定位到时间段, 行号才能定位到具体那一行。
- //
- // 取值是纳秒级 Unix 时间戳; 插入时若没给 (==0), ORM 会补上当前纳秒时间 (见 table.go)。
- const tsColumnName = "_ts"
- // ErrInvalidPrimaryKey 主键定义非法: 类型不是整数、一个结构体声明了多个主键、
- // 或同时内嵌了多个表基类。具体原因见错误信息。
- var ErrInvalidPrimaryKey = errors.New("主键定义非法")
- // indexName 返回索引的最终名字: 显式命名优先, 否则 idx_表名_首个字段名
- func (d IndexDef) indexName(tableName string) string {
- if d.Name != "" {
- return d.Name
- }
- return idxIndexPrefix + tableName + "_" + d.ColName
- }
- // ModelInfo 模型元信息
- type ModelInfo struct {
- Fields []FieldDef // 用户定义字段 (不含自动主键)
- AllFields []FieldDef // 全部字段 (含自动主键,按存储顺序)
- PKField string // 主键列名 ("_id" 或 "_ts")
- PKIndex int // 主键在 AllFields 中的索引
- IsTimeSeries bool // 是否时序表
- CoreFields []types.FieldInfo // 传给 core 的字段列表 (含自动主键)
- CorePKField byte // 主键在 CoreFields 中的索引 (用于 CreateIndex)
- StructType reflect.Type // 结构体类型 (用于反射)
- PKInStruct bool // 主键字段是否在结构体中 (嵌入基类时有)
- Indexes []IndexDef // 从标签解析的二级索引定义
- }
- // goKindToFieldType Go 类型到数据库字段类型的默认映射
- //
- // 有符号与无符号必须落在不同的类型值上: Uint8..Uint64 是无符号列 (补码大端即其正确序),
- // 有符号整数走 Int8/Int16/Int32/Int64 (保序编码)。旧映射把二者都压在 Uint8..Uint64 上,
- // 于是 int64 列上的负数跨 0 的范围扫描 / ORDER BY 会静默漏行 —— 详见 types.FieldType_Int64。
- var goKindToFieldType = map[reflect.Kind]types.FieldType{
- reflect.Int8: types.FieldType_Int8,
- reflect.Int16: types.FieldType_Int16,
- reflect.Int32: types.FieldType_Int32,
- reflect.Int64: types.FieldType_Int64,
- reflect.Int: types.FieldType_Int64,
- reflect.Uint8: types.FieldType_Uint8,
- reflect.Uint16: types.FieldType_Uint16,
- reflect.Uint32: types.FieldType_Uint32,
- reflect.Uint64: types.FieldType_Uint64,
- // 浮点必须映射到浮点列。旧映射 (Float32→Uint32, Float64→Uint64) 是整数列,
- // 写入时按整数截断: float64 的 123.75 会安静地变成 123 (金额/比例失真)。
- //
- // Float32 单独立类型 (FieldType_Float32): 旧做法折进 Float64 让列宽翻倍,
- // 现在列宽 == Go 类型宽度, 且 32 位精度是用户自己声明的, 不该被悄悄放宽。
- reflect.Float32: types.FieldType_Float32,
- reflect.Float64: types.FieldType_Float64,
- // bool 单独立类型: 借用 Uint8 时"写 2 也算真", 等值/索引/DISTINCT 会给出多套答案。
- reflect.Bool: types.FieldType_Bool,
- }
- // goTypeToFieldType 按【完整 Go 类型】映射到列类型, 优先于 goKindToFieldType。
- //
- // 这些类型都不是"Kind 能区分"的: types.UUID 是 [16]byte (Kind=Array), types.Decimal /
- // big.Int 是结构体。它们自带语义, 所以字段不用写 tag 就能落成正确的列。
- //
- // 只列【非指针】类型: 查表前统一解了一层指针 (见 parseField 的 carrierType),
- // `*T` 命中 T 的条目即可 —— 指针在这里的语义只是"可为 NULL", 不是另一种列型。
- var goTypeToFieldType = map[reflect.Type]types.FieldType{
- reflect.TypeOf(types.Decimal{}): types.FieldType_Decimal,
- reflect.TypeOf(types.UUID{}): types.FieldType_UUID,
- reflect.TypeOf(big.Int{}): types.FieldType_Int128,
- // types.Blob 载体: "对象里直接持有流" —— 写侧 Source/Bytes 流式落链 (内存峰值
- // ~128KB, 与内容大小无关), 读侧引擎只填回 8B ref, 调 row.Body.Open(table) 按需
- // 拿 io.ReadCloser。不声明 tag 即自动推断为 blob 列 (无须 type:blob)。
- reflect.TypeOf(types.Blob{}): types.FieldType_Blob,
- }
- // tagFieldTypes vrtx tag 中 `type:<name>` 可声明的列类型。
- //
- // 为什么不复用 Go Kind 推断: 同一个 Go 类型可能对应多种列语义 —— string 可以是定长串 /
- // UUID 文本 / Decimal 文本, int16 可以是普通整数 / 年份, []byte 可以是普通变长列 /
- // 文件大对象。tag 是用户表达"这一列的语义"的地方; 没写 tag 时才退回 Go 类型推断。
- //
- // 两个约定 (由 TestTagFieldTypesNamesAreCanonical 守):
- //
- // 1. 名字必须与 migrate.TypeName 的输出逐字一致 —— 那是导出 schema 时写进
- // __vrtx_meta 的名字, 对不上的话 "dump 出来照着再声明一遍" 就读不回去了。
- // 2. 一个列型只留一个名字, 不收别名 (曾经有 bool/boolean、float32/f32、decimal/numeric
- // 三对)。别名看着无害, 实则没有文档、没有测试、也永远不会被 TypeName 吐出来,
- // 只是给"同一列型两种写法"开口子。
- var tagFieldTypes = map[string]types.FieldType{
- "bool": types.FieldType_Bool,
- "float32": types.FieldType_Float32,
- "float64": types.FieldType_Float64,
- "decimal": types.FieldType_Decimal,
- "uuid": types.FieldType_UUID,
- "year": types.FieldType_Year,
- "int128": types.FieldType_Int128,
- "blob": types.FieldType_Blob,
- }
- // tagTypeNames 列出 `type:<name>` 可用的全部名称 (排序, 供报错信息使用)。
- //
- // 从 map 生成而不是手写一串: 手写的那份已经漏过一次 —— 新增 blob 时没同步, 于是
- // "可用类型"的提示里始终看不到 blob, 而报错信息正是用户找答案的地方。
- func tagTypeNames() string {
- names := make([]string, 0, len(tagFieldTypes))
- for n := range tagFieldTypes {
- names = append(names, n)
- }
- sort.Strings(names)
- return strings.Join(names, "/")
- }
- var (
- baseModelType = reflect.TypeOf(BaseModel{})
- timeSeriesModelType = reflect.TypeOf(TimeSeriesModel{})
- )
- // ParseModel 解析结构体,提取模型信息
- //
- // obj 必须是指向结构体的指针 (可以是零值), 且该结构体必须内嵌表基类
- // (DB.BaseModel / DB.PrimaryModel / DB.TimeSeriesModel) —— 否则返回 ErrNotModel。
- // "内嵌基类"既是"这是一张本框架的表"的标记, 也是头部增删改查的来源, 详见 requireBase。
- func ParseModel(obj interface{}) (*ModelInfo, error) {
- t := reflect.TypeOf(obj)
- if t.Kind() == reflect.Ptr {
- t = t.Elem()
- }
- if t.Kind() != reflect.Struct {
- return nil, fmt.Errorf("vrtx: obj must be a struct, got %s", t.Kind())
- }
- s := newModelScanner()
- if err := s.scan(t); err != nil {
- return nil, err
- }
- return s.modelInfo(t)
- }
- // baseSpecOf 判断一个嵌入字段是不是表基类, 并取出它自报的物理形态。
- //
- // 只认本包的公开基类, 不做接口通配: 用户自己写的嵌入结构体里也可能嵌着 BaseModel,
- // 那种情况应当继续递归展开它内部的字段, 而不是整块当成表基类 (否则它内部声明的字段
- // 会凭空消失)。再加一种基类时, 只需要让它实现 ModelSpec 并登记到这里。
- func baseSpecOf(t reflect.Type) (ModelSpec, bool) {
- if t != baseModelType && t != timeSeriesModelType {
- return nil, false
- }
- // ModelSpec 的三个方法都是值接收者, 零值即可断言。
- spec, ok := reflect.Zero(t).Interface().(ModelSpec)
- return spec, ok
- }
- // scannedField 一个已解析的用户字段 (不含基类带来的主键列)。
- type scannedField struct {
- def FieldDef
- idxDef *IndexDef
- }
- // modelScanner 逐层展开结构体, 收集用户字段并识别表基类 / 显式主键。
- //
- // 之所以要"先认全、再决定": 主键列既可能来自基类 (_id / _ts), 也可能被 vrtx:"pk"
- // 覆盖, 只有把两类候选都看完, 才知道 AllFields 里该放哪一列。
- type modelScanner struct {
- fields []scannedField
- spec ModelSpec // 内嵌的表基类自报的物理形态
- baseType reflect.Type // 基类的具体类型 (报错用)
- hasPK bool // 用户用 vrtx:"pk" 显式声明了主键
- pkField int // 显式主键在 fields 中的下标
- }
- func newModelScanner() *modelScanner {
- return &modelScanner{pkField: -1}
- }
- func (s *modelScanner) scan(t reflect.Type) error {
- for i := 0; i < t.NumField(); i++ {
- sf := t.Field(i)
- if sf.Anonymous {
- // 表基类: 记下它自报的物理形态, 不当普通字段展开。
- // 它内部的 modelCore / ID 都是运行时状态, 不该变成列。
- if spec, ok := baseSpecOf(sf.Type); ok {
- if s.spec != nil {
- return fmt.Errorf("%w: 一张表只能内嵌一个表基类, 已内嵌 %s, 不能再内嵌 %s "+
- "(主键索引与时序索引都是行存储索引, 一张表只能有一个)",
- ErrInvalidPrimaryKey, s.baseType.Name(), sf.Type.Name())
- }
- s.spec, s.baseType = spec, sf.Type
- continue
- }
- // 其他嵌入结构体: 递归展开
- if sf.Type.Kind() == reflect.Struct {
- if err := s.scan(sf.Type); err != nil {
- return err
- }
- }
- continue
- }
- fd, idxDef, err := parseField(sf, len(s.fields))
- if err != nil {
- return fmt.Errorf("field %s: %w", sf.Name, err)
- }
- s.fields = append(s.fields, scannedField{def: fd, idxDef: idxDef})
- if fd.IsPK {
- if err := s.declarePK(sf); err != nil {
- return err
- }
- }
- }
- return nil
- }
- // declarePK 登记用户用 `vrtx:"pk"` (或显式列名 _id / _ts) 声明的主键。
- //
- // 类型必须是 64 位整数: 引擎的主键号 (pkID) 就是 uint64, 而且这一列会被当作 pkID
- // 的镜像 (插入后回写、Find 反查都靠它)。窄整数装不下时 setPKValue 会静默截断,
- // 字符串 / 浮点 / 切片则根本无法承载 pkID —— 与其留一个查不到的行, 不如直接报错。
- //
- // 它优先于基类带来的默认主键列: 基类给的是"默认样式", 用户显式声明了就听用户的 ——
- // 这正是"每个表自己设计主键"的入口。
- func (s *modelScanner) declarePK(sf reflect.StructField) error {
- if s.hasPK {
- return fmt.Errorf("%w: 字段 %s 与 %s 都声明了主键, 一个表只能有一个主键",
- ErrInvalidPrimaryKey, sf.Name, s.fields[s.pkField].def.Name)
- }
- switch sf.Type.Kind() {
- case reflect.Int, reflect.Uint, reflect.Int64, reflect.Uint64:
- // 这四种在 goKindToFieldType 里都映射到 8 字节列, 与 pkID 同宽
- default:
- return fmt.Errorf("%w: 字段 %s 是 %s, 主键只能是 64 位整数 (int/uint/int64/uint64); 字符串不能当主键",
- ErrInvalidPrimaryKey, sf.Name, sf.Type)
- }
- s.hasPK, s.pkField = true, len(s.fields)-1
- return nil
- }
- // modelInfo 把扫描结果组装成 ModelInfo。主键列的落位有两条规则, 都有实际原因:
- //
- // 1. vrtx:"pk" 覆盖基类的默认列 —— 基类给的是默认样式, 用户声明了就听用户的。
- // 2. 主键列固定排在 AllFields / CoreFields 第一位。行内布局是
- // [pkID(8B)][schemaVer(1B)][字段...], 而时序索引按固定偏移 9 读第一列当时间键
- // (core/index.timeRowInRange、TimeDataPage.FindRowByIndexKey), 所以时序键必须落在
- // 第一列。与其要求用户把字段写在基类前面, 不如统一排到最前。
- // 行镜像是按列名写入的 (core.serializeRow 会 lookupFieldValue 找列),
- // 字段顺序只影响新建表时的列序, 因此这个调整对已有表也安全, 不会把数据写错位。
- //
- // 进到这里之前必须已经确认内嵌了表基类 (见 requireBase): 没有基类就没有默认键列,
- // 一级索引用哪种、行主键号往哪个字段回写都无从谈起。
- func (s *modelScanner) modelInfo(t reflect.Type) (*ModelInfo, error) {
- if err := s.requireBase(t); err != nil {
- return nil, err
- }
- info := &ModelInfo{StructType: t}
- pk := s.primaryKey()
- info.AllFields = append(info.AllFields, pk)
- info.PKField = pk.ColName
- info.PKIndex = 0
- info.PKInStruct = true
- info.IsTimeSeries = s.spec.indexType() == page.IndexTypeTime
- // 每个用户字段落在 AllFields 的位置
- pos := make([]int, len(s.fields))
- for i, f := range s.fields {
- if s.hasPK && i == s.pkField {
- // 显式主键: 字段本身仍然留在 Fields 里 (调用方靠它取名 / 取类型),
- // 但列定义已经作为主键放进 AllFields, 这里不重复追加。
- fd := f.def
- fd.Index = 0
- info.Fields = append(info.Fields, fd)
- continue
- }
- fd := f.def
- fd.Index = len(info.AllFields)
- pos[i] = fd.Index
- info.Fields = append(info.Fields, fd)
- info.AllFields = append(info.AllFields, fd)
- }
- info.Indexes = s.indexes(pos)
- // 反射取值路径一次性解析 (Type.FieldByName 含嵌入提升链)。
- // 逐行 structToFieldValues 走 FieldByIndex 快路径, 省掉每行每列一次
- // FieldByName 的类型级宽度搜索; 解析不到的 (自动 _id 列等) 留 nil,
- // 调用方退回 findField 老路径, 语义不变。
- for i := range info.AllFields {
- if sf, ok := t.FieldByName(info.AllFields[i].Name); ok {
- info.AllFields[i].GoPath = sf.Index
- }
- }
- // 列上的 FlagUnique 只反映【该列 tag 里写了 unique】(由 parseField 置位), 这里
- // 【不】按索引分量补齐。原因是补齐会撒谎, 而且会骗到"从 schema 反推 tag"的工具:
- // - 复合唯一索引 (index:NAME 多列 + 其中一列写 unique) 约束的是整组列, 给每个
- // 分量都打上唯一位, 读起来就成了"这一列单独唯一" —— 恰好是它的反面;
- // - 工具照这个位回写 vrtx tag 时, 会给 B 也加上 unique, 而 unique 在 ORM 里
- // 是"该列单独建一个唯一索引", 于是凭空多出一条约束。
- // 复合键覆盖了哪些列, 由 IndexDef / IndexMeta 的 FieldIDs 表达 (那才是权威)。
- // 构建 CoreFields。Flag 必须一并带过去: Decimal 的列级 scale、可空位与唯一位都存在
- // 这里, 写入/索引编码都要拿它对齐 (缺失会退化成"按值自带 scale", 破坏同列保序前提)。
- info.CoreFields = make([]types.FieldInfo, len(info.AllFields))
- for i, f := range info.AllFields {
- info.CoreFields[i] = types.FieldInfo{
- FieldType: f.FieldType,
- FieldName: []byte(f.ColName),
- Flag: f.Flag,
- }
- }
- info.CorePKField = byte(info.PKIndex)
- return info, nil
- }
- // requireBase 强制"表必须内嵌基类"。
- //
- // 为什么把它做成硬约束, 而不是"没有基类也行、只是没有头部方法":
- //
- // - 基类是"这是一张本框架的表"的唯一凭据。没有它, ORM 只能靠猜 —— 猜哪一列是行
- // 主键号的镜像、一级索引用 Primary 还是 Time; 猜错的代价是一张"插入时不回写主键、
- // 按写入值查不到"的表 (旧的 struct{} 兜底分支就是这个下场)。
- // - 头部增删改查 (Insert/Update/Delete/Load...) 由基类提供。允许没有基类的表存在,
- // 等于允许一半的表用 Table[T] 的 API、另一半的表两种都能用 —— 同一个项目里两套
- // 并列的写法, 新人和代码审查都得先判断"这张表属于哪种"。
- // - 校验放在建表之前, 所以不会留下半成品: 报错时库里什么都没有。
- //
- // 迁移 (migrate 包) 是按 SQL 元数据动态建表的, 那时根本没有 Go 结构体可内嵌 ——
- // 它走 core 层 API (db.CreateTable), 与本约束无关。
- func (s *modelScanner) requireBase(t reflect.Type) error {
- if s.spec != nil {
- return nil
- }
- if s.hasPK {
- // 单写 vrtx:"pk" 是个很自然的误解: 它看起来"已经声明了主键"。
- // 点明它只是"覆盖基类默认键列", 否则用户会以为是别的地方出了错。
- return fmt.Errorf("%w: %s 只声明了 vrtx:\"pk\", 但没内嵌表基类 —— "+
- "pk 标签是用来覆盖基类默认键列的 (BaseModel 的 _id / TimeSeriesModel 的 _ts), "+
- "不能替代基类本身", ErrNotModel, t)
- }
- return fmt.Errorf("%w: %s 必须内嵌 DB.BaseModel / DB.PrimaryModel (主键表) 或 "+
- "DB.TimeSeriesModel (时序表)", ErrNotModel, t)
- }
- // primaryKey 返回主键列定义: 用户用 vrtx:"pk" 显式声明的优先, 否则用基类自报的默认键列
- // (_id / _ts)。两者必有其一 —— 调用前 requireBase 已经保证了基类存在。
- func (s *modelScanner) primaryKey() FieldDef {
- if s.hasPK {
- f := s.fields[s.pkField].def
- f.IsPK = true
- f.Index = 0
- // 主键列必须钉在 FieldType_Uint64 (无符号 64 位) 上, 不能沿用字段自身的有符号类型
- // (FieldType_Int*)。两条原因都不是风格问题:
- // 1. 这一列是引擎行主键号 pkID (uint64) 的镜像, 主键 B+ 树按它的补码字节序排序;
- // 2. 时序表里它就是 _ts —— 时序索引 (index.IndexTimeEntry.Compare) 与时间范围
- // 过滤都按 int64 补码直接读这 8 个字节, 换成保序编码会让时间轴整体错位。
- // 字段被声明成 pk 时值仍经 toUint64 归一化后写入 (getPKValue 已拒绝负数),
- // 盘上字节与默认主键完全一致, 因此按 _id 查询/排序的行为不变。
- f.FieldType = types.FieldType_Uint64
- f.GoKind = reflect.Uint64
- return f
- }
- return FieldDef{
- Name: s.spec.pkGoField(),
- ColName: s.spec.pkColumn(),
- FieldType: types.FieldType_Uint64,
- GoKind: reflect.Uint64,
- Index: 0,
- }
- }
- // indexes 收集所有标记了 index 的字段的索引定义。
- //
- // 同一个具名索引 (index:NAME) 被多个字段声明时, 合并成一个复合索引:
- // 分量顺序 = 字段在表中的物理顺序。这样无需在 tag 里额外表达键顺序,
- // 也正好对上复合索引"最左前缀"的用法 (a=? 或 a=? AND b>?)。
- // 未命名的 index 仍各自成单列索引。同名时以第一个声明为准 (含索引类型)。
- func (s *modelScanner) indexes(pos []int) []IndexDef {
- var out []IndexDef
- named := make(map[string]int, len(s.fields))
- for i, f := range s.fields {
- if f.idxDef == nil {
- continue
- }
- if s.hasPK && i == s.pkField {
- continue // 主键列本身就是一级索引, 不再单独建二级索引
- }
- at := pos[i]
- if f.idxDef.Name != "" {
- if n, ok := named[f.idxDef.Name]; ok {
- // 同名 → 追加为新的索引分量
- out[n].FieldIDs = append(out[n].FieldIDs, byte(at))
- out[n].Unique = out[n].Unique || f.idxDef.Unique
- continue
- }
- }
- d := *f.idxDef
- d.FieldID = byte(at)
- d.FieldIDs = []byte{byte(at)}
- d.ColName = f.def.ColName
- out = append(out, d)
- if d.Name != "" {
- named[d.Name] = len(out) - 1
- }
- }
- return out
- }
- // parseField 解析单个结构体字段
- // 返回: FieldDef, *IndexDef (如果有索引声明), error
- func parseField(sf reflect.StructField, idx int) (FieldDef, *IndexDef, error) {
- // carrierType 列载体类型: 指针载体 `*T` 的列语义由元素类型 T 决定 —— nil ↔ NULL
- // (见 convert.go 的 nil 判定), 非 nil 时按 T 的值写入/读回。解一层指针之后,
- // *int64 与 int64 落在同一个列型上, 只是多了"可以整列为空"这一档。
- carrierType := sf.Type
- if carrierType.Kind() == reflect.Ptr {
- carrierType = carrierType.Elem()
- }
- fd := FieldDef{
- Name: sf.Name,
- GoKind: carrierType.Kind(),
- Index: idx,
- }
- var idxDef *IndexDef
- // 列名: 优先使用 vrtx tag 中的列名
- fd.ColName = sf.Name
- tag, hasTag := sf.Tag.Lookup("vrtx")
- if !hasTag {
- tag, hasTag = sf.Tag.Lookup("tsdb") // 向后兼容: 也检查 tsdb 标签
- }
- if hasTag && tag != "" {
- parts := parseTag(tag)
- // 分类解析每个 part
- maxlen := 0
- hasIndex := false
- idxName := ""
- idxType := page.IndexTypeBTree // 默认 B+树索引
- typeSet := false // tag 里显式写了列类型
- scaleSet := false // tag 里显式写了 decimal scale
- for _, p := range parts {
- p = strings.TrimSpace(p)
- if p == "" {
- continue
- }
- // 1. 检查是否是索引声明: "index" 或 "index:NAME"
- if p == "index" || strings.HasPrefix(p, "index:") {
- hasIndex = true
- if strings.HasPrefix(p, "index:") {
- idxName = p[6:] // 去掉 "index:" 前缀
- }
- continue
- }
- // 2. 检查 key:value 选项 (冒号分隔)
- if strings.Contains(p, ":") && !strings.HasPrefix(p, "index:") {
- kv := strings.SplitN(p, ":", 2)
- key, val := kv[0], kv[1]
- switch key {
- case "type":
- // type:hash / type:btree 是索引类型; 其余值是列类型
- // (type:decimal / type:uuid / ...), 两者共用一个 key 但命名空间不冲突。
- switch val {
- case "hash":
- idxType = page.IndexTypeHash
- case "btree":
- idxType = page.IndexTypeBTree
- default:
- ft, ok := tagFieldTypes[strings.ToLower(strings.TrimSpace(val))]
- if !ok {
- return fd, nil, fmt.Errorf("未知字段类型 %q (可选: %s)", val, tagTypeNames())
- }
- fd.FieldType = ft
- typeSet = true
- }
- case "decimal":
- // decimal:N 是 `type:decimal,scale:N` 的简写。
- n, err := strconv.Atoi(strings.TrimSpace(val))
- if err != nil || n < 0 || n > types.MaxDecimalScale {
- return fd, nil, fmt.Errorf("decimal 精度必须是 0..%d 的整数, 得到 %q",
- types.MaxDecimalScale, val)
- }
- fd.FieldType = types.FieldType_Decimal
- // 只动低 5 位的 scale: 它与 nullable 等状态位共用一个字节, 不能整体覆盖。
- fd.Flag = fd.Flag&^types.FlagScaleMask | byte(n)
- typeSet, scaleSet = true, true
- case "scale":
- n, err := strconv.Atoi(strings.TrimSpace(val))
- if err != nil || n < 0 || n > types.MaxDecimalScale {
- return fd, nil, fmt.Errorf("decimal scale 必须是 0..%d 的整数, 得到 %q",
- types.MaxDecimalScale, val)
- }
- fd.Flag = fd.Flag&^types.FlagScaleMask | byte(n)
- scaleSet = true
- case "maxlen":
- // maxlen 的单位是【字节】(与 types.FieldSize 同口径), 不是字符数:
- // 引擎的行布局按字节算, 拿字符数去声明会让 utf8mb4 中文列 (3 字节/字)
- // 实际容量只有声明的 1/3。需要按字符数声明时请乘上编码宽度。
- if n, err := strconv.Atoi(val); err == nil && n > 0 {
- maxlen = n
- }
- }
- continue
- }
- // 列可空声明: `vrtx:"nullable"` / `vrtx:"null"` —— 允许该列写入 NULL,
- // 行内用 NULL 位图记录 (见 types.NullBitmapLen)。未声明即 NOT NULL。
- if p == "nullable" || p == "null" {
- fd.Flag |= types.FlagNullable
- continue
- }
- // 3. 检查是否是 "unique": 唯一约束。
- // 同时打两个标记 —— 列上的 FlagUnique (声明) 与索引上的 Unique (执行者):
- // 唯一性判定要一次索引查找, 光有列标记无法执行约束; 而只有索引标记则
- // "哪些列被约束"要反查索引元数据才看得见。两者都写, 各司其职。
- if p == "unique" {
- if idxDef == nil {
- idxDef = &IndexDef{}
- }
- idxDef.Unique = true
- fd.Flag |= types.FlagUnique
- hasIndex = true
- continue
- }
- // 3.5 检查是否是主键声明: 该字段就是本表主键。
- // 时序表嵌了 TimeSeriesModel 时它同样成立 —— 声明的那一列会成为时序键
- // (时序索引的分段键), 而基类自带的 _ts 不再建列。
- // 类型校验在 declarePK 里做 —— 字符串等非整数类型直接报错。
- if p == "pk" {
- fd.IsPK = true
- continue
- }
- // 4. 其他: 视为列名
- fd.ColName = p
- }
- // 显式把列名写成 _id / _ts 等价于声明主键: 这两列正是引擎行主键号 (pkID) 的
- // 镜像列, 旧实现会把这种字段当普通列 —— 插入时既不填号也不回写, 静默失效。
- if fd.ColName == pkColumnName || fd.ColName == tsColumnName {
- fd.IsPK = true
- }
- // 主键列本身就是唯一的 (InsertRowWithID 用 ErrDuplicatePK 兜着), 而 indexes()
- // 也不会给主键列建二级索引 —— 留着 FlagUnique 只会让人以为"另有一个唯一索引
- // 在约束它", 实际上什么都没建。声明侧直接抹掉这个位。
- if fd.IsPK {
- fd.Flag &^= types.FlagUnique
- }
- // 处理 maxlen: 只在没有显式列类型时生效 (显式列类型优先)
- if maxlen > 0 && !typeSet {
- if sf.Type.Kind() == reflect.String {
- ft, code, err := maxlenToColumn(maxlen)
- if err != nil {
- // 声明了引擎兑现不了的容量: 在 ParseModel 阶段就拒, 不留"表建好了、
- // 某天写入才失败"的半成品 (与 validateFieldTypeParam 同一原则)。
- return fd, nil, fmt.Errorf("字段 %s: %w", fd.ColName, err)
- }
- fd.FieldType = ft
- // 宽度码写进 Flag 低 5 位: 它就是这一列的定宽依据, 随 schema 落盘,
- // 与 decimal 的 scale 共用同一格 (按类型解释, 见 types.FieldSize)。
- if code > 0 {
- fd.Flag = fd.Flag&^types.FlagScaleMask | code
- }
- }
- // 数值类型忽略 maxlen (用 Go 类型自动推断)
- }
- // 只写了 scale 就默认这是 decimal 列 (scale 是 decimal 独有的参数)。
- if scaleSet && fd.FieldType == 0 && !typeSet {
- fd.FieldType = types.FieldType_Decimal
- }
- // 处理索引声明
- if hasIndex {
- if idxDef == nil {
- idxDef = &IndexDef{}
- }
- idxDef.Name = idxName
- idxDef.IndexType = idxType
- }
- }
- // 字段类型: tag 没显式指定时按 Go 类型推断。
- // 先按完整类型 (Decimal/UUID/big.Int 这类自带语义的类型), 再按 Kind。
- // 两处都看 carrierType: `*int64` 与 `int64` 推出同一个列型 —— 指针只是多了
- // "整列为空"这一档, 不该另立一门列型。
- if fd.FieldType == 0 {
- if ft, ok := goTypeToFieldType[carrierType]; ok {
- fd.FieldType = ft
- } else if ft, ok := goKindToFieldType[carrierType.Kind()]; ok {
- fd.FieldType = ft
- } else if carrierType.Kind() == reflect.String {
- fd.FieldType = types.FieldType_String // string 默认 256 字节
- } else if carrierType.Kind() == reflect.Slice && carrierType.Elem().Kind() == reflect.Uint8 {
- fd.FieldType = types.FieldType_Dynamicbyte
- } else {
- return fd, nil, fmt.Errorf("unsupported type: %s", sf.Type.String())
- }
- }
- // 类型参数校验: 非法组合在建表前就报错, 不留半成品。
- if err := validateFieldTypeParam(fd, sf); err != nil {
- return fd, nil, err
- }
- return fd, idxDef, nil
- }
- // validateFieldTypeParam 校验"列类型 + Go 类型 + Flag"这个组合是否成立。
- //
- // 这些检查都发生在 UseTable 建表之前: 让模型一开始就被拒, 比等到插入时才在
- // 某一行上报错好 —— 后者会留下"表建好了、数据写不进"的半成品状态。
- func validateFieldTypeParam(fd FieldDef, sf reflect.StructField) error {
- // 主键列不能声明 NULL: pkID 是行内固定 8 字节, 没有"缺失"这一档。
- if fd.IsPK && fd.Flag&types.FlagNullable != 0 {
- return fmt.Errorf("主键列 %s 不能声明 nullable", fd.ColName)
- }
- // 载体类型 = 解一层指针 (与 parseField 的推断口径一致): 下面校验的都是"这一列装
- // 什么值", 而 `*T` 装的就是 T, 指针本身只是 NULL 的表示法。
- carrier := sf.Type
- if carrier.Kind() == reflect.Ptr {
- carrier = carrier.Elem()
- }
- switch fd.FieldType {
- case types.FieldType_Decimal:
- if scale := fd.Flag & types.FlagScaleMask; scale > types.MaxDecimalScale {
- return fmt.Errorf("decimal scale=%d 超过上限 %d", scale, types.MaxDecimalScale)
- }
- // decimal 必须有可解析的载体, 否则写入时才发现就晚了。
- if !decimalCarrier(carrier) {
- return fmt.Errorf("decimal 列需要 types.Decimal / string / 数值类型, 不能是 %s", sf.Type)
- }
- case types.FieldType_UUID:
- if !uuidCarrier(carrier) {
- return fmt.Errorf("uuid 列需要 types.UUID / [16]byte / string / []byte, 不能是 %s", sf.Type)
- }
- case types.FieldType_Int128:
- if !int128Carrier(carrier) {
- return fmt.Errorf("int128 列需要 big.Int / *big.Int / types.Decimal / 整数 / string, 不能是 %s", sf.Type)
- }
- case types.FieldType_Year:
- // 解码载体是 int16, 所以只收整型载体 —— time.Time 能写不能读回, 收它等于埋雷。
- switch carrier.Kind() {
- case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint16:
- default:
- return fmt.Errorf("year 列需要整数载体 (int/int16/int32/int64/uint16), 不能是 %s", sf.Type)
- }
- case types.FieldType_Float32:
- // 单精度列只收浮点载体: 装整数没有意义, 且会把"写进去的数被悄悄放宽"这件事
- // 藏起来。float64 载体是允许的 —— 引擎在写入时校验它能否被 float32 无损表示。
- switch carrier.Kind() {
- case reflect.Float32, reflect.Float64:
- default:
- return fmt.Errorf("float32 列需要 float32/float64 载体, 不能是 %s", sf.Type)
- }
- case types.FieldType_Float64:
- // 双精度列同样只收浮点载体。整数载体是必须拒的: 读回走 setFloatField →
- // target.SetInt(int64(val)), 一旦列里出现小数 (例如 Update().Set 写进去的),
- // 就会被静默砍掉 —— 正是 Float32 那条分支要防的同一件事。
- //
- // 这条分支存在的意义主要是"让 tag 可达": float64 字段本来就会自动推断成
- // Float64, 所以 type:float64 是显式/对称写法 (也给 float32 载体提供加宽),
- // 在此之前报错提示里列着 float32 却搜不到 float64, 读着像 bug。
- switch carrier.Kind() {
- case reflect.Float32, reflect.Float64:
- default:
- return fmt.Errorf("float64 列需要 float32/float64 载体, 不能是 %s", sf.Type)
- }
- case types.FieldType_Blob:
- // Blob 认 []byte 与 types.Blob 两种载体 —— 后者是"对象里持有流对象"的
- // 流式载体 (写 Source/Bytes 流式落链, 读回只填 8B ref + Open() 拿流)。
- // 这里【故意不收 string】。
- //
- // 读取路径 setFieldFromValue → setBytesField 对 string 载体是按"截断到第一个
- // NUL 字节"写的 (那是定长串/文本列的 CHAR(n) 语义)。Blob 装的是二进制,
- // 内容里出现 0x00 就会被静默截断 —— 写进去 8 字节读回来 3 字节, 且不报错。
- // 允许 string 等于亲手留一个静默丢数据的后门, 所以直接在建模阶段拒掉。
- // (要存文本用 Dynamicbyte / maxlen, 那些列的 string 载体语义是明确的。)
- if carrier.Kind() == reflect.Slice && carrier.Elem().Kind() == reflect.Uint8 {
- return nil // []byte: 一次性载体, 读回整块拉进内存
- }
- if carrier == reflect.TypeOf(types.Blob{}) {
- return nil // types.Blob: 流式载体
- }
- return fmt.Errorf("blob 列需要 []byte / types.Blob 载体, 不能是 %s (二进制里的 0x00 会被 string 载体静默截断)", sf.Type)
- }
- return nil
- }
- // decimalCarrier Decimal 列的 Go 载体: types.Decimal / string / 任意数值。
- //
- // 三个 carrier 判定收的都是【解过指针的载体类型】(*types.Decimal 传进来的是
- // types.Decimal), 所以这里不用再判指针。
- func decimalCarrier(t reflect.Type) bool {
- if _, ok := goTypeToFieldType[t]; ok {
- return true
- }
- switch t.Kind() {
- case reflect.String,
- reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
- reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
- reflect.Float32, reflect.Float64:
- return true
- }
- return false
- }
- // uuidCarrier UUID 列的 Go 载体: types.UUID / [16]byte / string / []byte。
- func uuidCarrier(t reflect.Type) bool {
- if t == reflect.TypeOf(types.UUID{}) {
- return true
- }
- if t.Kind() == reflect.String {
- return true
- }
- if t.Kind() == reflect.Array && t.Len() == types.UUIDSize && t.Elem().Kind() == reflect.Uint8 {
- return true
- }
- return t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Uint8
- }
- // int128Carrier Int128 列的 Go 载体: big.Int / *big.Int / types.Decimal / 整数 / string。
- func int128Carrier(t reflect.Type) bool {
- if _, ok := goTypeToFieldType[t]; ok {
- return true
- }
- switch t.Kind() {
- case reflect.String,
- reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
- reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- return true
- }
- return false
- }
- // maxlenToColumn 把 `vrtx:"maxlen:N"` (单位: 字节) 映射成 (列类型, 列级宽度码)。
- //
- // 返回的 code 写进 FieldInfo.Flag 低 5 位, 由引擎按它决定行内宽度 (见 types.FieldSize)。
- // code == 0 表示"落动态列"。
- //
- // 【语义: 向上取到最近的档位】宽度码只有 24 档 (16,24,32,...,2048), 声明 200 字节能拿到
- // 224 字节档, 声明 10 只能拿到 16 字节档 —— 宁可贵几字节也不能向下取, 向下取会让合法值
- // 写不进去。真正的闸门是【档位宽度】(写入超过档位宽度会报错并报出该列容量), 不是 N 本身。
- //
- // 超过 types.MaxInlineColumnWidth (2048) 的声明退回动态列 (行内 6 字节堆引用):
- // 定长档位的存在意义是"这一列可索引、可定长比较", 而动态列两者都没有 (CreateIndex 会
- // 明确拒绝), 所以 2048 是"要索引就别超过它"的分界线。
- //
- // 【N 还有第二道上界】落动态列不等于"声明多大都行": 动态列的内容整体落在一个堆页里,
- // 单值上限是 types.MaxStringSize。声明超过它的列永远兑现不了, 所以这里直接报错, 而不是
- // 悄悄建成一条装不下那么多字节的列。这道闸门只能在这里 —— 动态列【不保留声明长度】
- // (Flag 低 5 位必须为 0), 一旦过了这层, N 就不在盘上了, 事后再无据可查。
- func maxlenToColumn(maxlen int) (types.FieldType, byte, error) {
- if err := types.CheckDeclaredStringSize(maxlen); err != nil {
- return 0, 0, err
- }
- code := types.WidthCodeFor(maxlen)
- if code == 0 {
- return types.FieldType_Dynamicbyte, 0, nil
- }
- return types.FieldType_String, code, nil
- }
- // parseTag 解析 vrtx tag: 按逗号分隔
- func parseTag(tag string) []string {
- var parts []string
- current := ""
- for _, c := range tag {
- if c == ',' {
- parts = append(parts, current)
- current = ""
- } else {
- current += string(c)
- }
- }
- if current != "" {
- parts = append(parts, current)
- }
- return parts
- }
- // GetIndexType 返回该模型应创建的一级索引类型
- func (m *ModelInfo) GetIndexType() page.IndexType {
- if m.IsTimeSeries {
- return page.IndexTypeTime
- }
- return page.IndexTypePrimary
- }
|