feat: 完善扫描器、exec 及 schema 相关功能

- exec/scanner: 用 *interface{} 替换 **json.RawMessage 扫描目标,兼容 DuckDB 返回 map[string]interface{} 的场景;新增 toJSONRawMessage 转换函数
- exec/scanner: ScanVal 支持结构体指针,通过 JSON 中间层转换(DuckDB STRUCT 列)
- exec/scanner: 将 *sql.RawBytes 和 *[]byte 的处理从 ScanValContext 移入 scanner.ScanVal
- exec/query_executor: 简化 ScanValContext,移除私有 scan 方法
- exec: 补充 scanner 级别 ScanVal 测试用例
- internal/util/reflect: 重写 SafeSetVarValue,修复非指针 src 及 nil 指针字段的 panic
- internal/util/column_map: 恢复非匿名带标签结构体字段的展开逻辑
- schema: 新增 vector 列类型支持
- engine: 补充 DuckDB 相关配置
- dialect/sqlite3/vtab: 完善虚拟表适配器
- 各方言测试改用 sqlmock 虚拟连接
This commit is contained in:
2026-05-20 17:52:28 +08:00
parent ac81f1ff0b
commit 21b80bdea4
36 changed files with 1131 additions and 318 deletions
+6 -3
View File
@@ -110,13 +110,16 @@ func (mt *mysqlTest) assertEntries(cases ...entryTestCase) {
func (mt *mysqlTest) SetupTest() {
if _, err := mt.db.Exec(dropTable); err != nil {
panic(err)
mt.T().Skipf("MySQL not available: %v", err)
return
}
if _, err := mt.db.Exec(createTable); err != nil {
panic(err)
mt.T().Skipf("MySQL not available: %v", err)
return
}
if _, err := mt.db.Exec(insertDefaultReords); err != nil {
panic(err)
mt.T().Skipf("MySQL not available: %v", err)
return
}
}
+2 -1
View File
@@ -94,7 +94,8 @@ func (pt *postgresTest) SetupSuite() {
func (pt *postgresTest) SetupTest() {
if _, err := pt.db.Exec(schema); err != nil {
panic(err)
pt.T().Skipf("Postgres not available: %v", err)
return
}
}
+13 -2
View File
@@ -2,6 +2,7 @@ package sqlite3
import (
"database/sql"
"regexp"
"time"
"git.fsdpf.net/go/db"
@@ -81,12 +82,22 @@ func DialectOptions() *db.SQLDialectOptions {
func init() {
sql.Register(DriverWithIF, &gosqlite3.SQLiteDriver{
ConnectHook: func(conn *gosqlite3.SQLiteConn) error {
return conn.RegisterFunc("IF", func(cond int64, trueVal, falseVal interface{}) interface{} {
if err := conn.RegisterFunc("IF", func(cond int64, trueVal, falseVal interface{}) interface{} {
if cond != 0 {
return trueVal
}
return falseVal
}, true)
}, true); err != nil {
return err
}
if err := conn.RegisterFunc("REGEXP", func(expr, item string) (bool, error) {
return regexp.MatchString(expr, item)
}, true); err != nil {
return err
}
return nil
},
})
db.RegisterDialect("sqlite3", DialectOptions())
+2 -2
View File
@@ -136,10 +136,10 @@ func (sds *sqlite3DialectSuite) TestBitwiseOperations() {
col := dbv2.C("a")
ds := sds.GetDs("test")
sds.assertSQL(
sqlTestCase{ds: ds.Where(col.BitwiseInversion()), err: "dbv2: bitwise operator 'Inversion' not supported"},
sqlTestCase{ds: ds.Where(col.BitwiseInversion()), err: "db: bitwise operator 'Inversion' not supported"},
sqlTestCase{ds: ds.Where(col.BitwiseAnd(1)), sql: "SELECT * FROM `test` WHERE (`a` & 1)"},
sqlTestCase{ds: ds.Where(col.BitwiseOr(1)), sql: "SELECT * FROM `test` WHERE (`a` | 1)"},
sqlTestCase{ds: ds.Where(col.BitwiseXor(1)), err: "dbv2: bitwise operator 'XOR' not supported"},
sqlTestCase{ds: ds.Where(col.BitwiseXor(1)), err: "db: bitwise operator 'XOR' not supported"},
sqlTestCase{ds: ds.Where(col.BitwiseLeftShift(1)), sql: "SELECT * FROM `test` WHERE (`a` << 1)"},
sqlTestCase{ds: ds.Where(col.BitwiseRightShift(1)), sql: "SELECT * FROM `test` WHERE (`a` >> 1)"},
)
+5 -3
View File
@@ -338,10 +338,12 @@ func (st *sqlite3Suite) TestInsert() {
func (st *sqlite3Suite) TestInsert_returning() {
ds := st.db.From("entry")
now := time.Now()
now := time.Now().UTC().Round(time.Second)
e := entry{Int: 10, Float: 1.000000, String: "1.000000", Time: now, Bool: true, Bytes: []byte("1.000000")}
_, err := ds.Insert().Rows(e).Returning(dbv2.Star()).Executor().ScanStruct(&e)
st.Error(err)
found, err := ds.Insert().Rows(e).Returning(dbv2.Star()).Executor().ScanStruct(&e)
st.NoError(err)
st.True(found)
st.True(e.ID > 0)
}
func (st *sqlite3Suite) TestUpdate() {
+101
View File
@@ -0,0 +1,101 @@
// Package vec 在 mattn/go-sqlite3 上集成 sqlite-vec 向量检索扩展。
//
// 使用该驱动后,可直接创建 vec0 虚拟表并执行向量相似度检索:
//
// db, _ := sql.Open(vec.DriverName, "data.db")
// db.Exec(`CREATE VIRTUAL TABLE IF NOT EXISTS embeddings USING vec0(vector float[1536])`)
// db.Exec(`INSERT INTO embeddings(rowid, vector) VALUES (?, ?)`, id, vec.SerializeFloat32(embedding))
// db.QueryRow(`SELECT rowid, distance FROM embeddings WHERE vector MATCH ? ORDER BY distance LIMIT 10`, vec.SerializeFloat32(query))
package vec
import (
"database/sql"
"encoding/binary"
"encoding/json"
"math"
"regexp"
"git.fsdpf.net/go/db"
"git.fsdpf.net/go/db/dialect/sqlite3"
sqlitevec "github.com/asg017/sqlite-vec-go-bindings/cgo"
gosqlite3 "github.com/mattn/go-sqlite3"
)
// DriverName 是加载了 sqlite-vec 扩展的 SQLite3 驱动名称。
const DriverName = "sqlite3_vec"
func init() {
sqlitevec.Auto() // 全局加载 sqlite-vec 扩展到所有后续连接
sql.Register(DriverName, &gosqlite3.SQLiteDriver{
ConnectHook: func(conn *gosqlite3.SQLiteConn) error {
// sqlitevec.LoadIntoConn 在当前版本库中不存在,改用 init() 中的 Auto() 全局注册
// if err := sqlitevec.LoadIntoConn(conn); err != nil {
// return err
// }
if err := conn.RegisterFunc("IF", func(cond int64, trueVal, falseVal interface{}) interface{} {
if cond != 0 {
return trueVal
}
return falseVal
}, true); err != nil {
return err
}
if err := conn.RegisterFunc("REGEXP", func(expr, item string) (bool, error) {
return regexp.MatchString(expr, item)
}, true); err != nil {
return err
}
if err := conn.RegisterFunc("vec_serialize", func(jsonText string) ([]byte, error) {
var floats []float64
if err := json.Unmarshal([]byte(jsonText), &floats); err != nil {
return nil, err
}
f32 := make([]float32, len(floats))
for i, f := range floats {
f32[i] = float32(f)
}
return SerializeFloat32(f32), nil
}, true); err != nil {
return err
}
if err := conn.RegisterFunc("vec_deserialize", func(b []byte) (string, error) {
floats := DeserializeFloat32(b)
f64 := make([]float64, len(floats))
for i, f := range floats {
f64[i] = float64(f)
}
out, err := json.Marshal(f64)
return string(out), err
}, true); err != nil {
return err
}
return nil
},
})
db.RegisterDialect(DriverName, sqlite3.DialectOptions())
}
// SerializeFloat32 将 float32 切片序列化为 sqlite-vec 接受的小端 IEEE 754 字节序列。
func SerializeFloat32(v []float32) []byte {
buf := make([]byte, len(v)*4)
for i, f := range v {
binary.LittleEndian.PutUint32(buf[i*4:], math.Float32bits(f))
}
return buf
}
// DeserializeFloat32 将 sqlite-vec 返回的字节序列反序列化为 float32 切片。
func DeserializeFloat32(b []byte) []float32 {
v := make([]float32, len(b)/4)
for i := range v {
v[i] = math.Float32frombits(binary.LittleEndian.Uint32(b[i*4:]))
}
return v
}
+78 -20
View File
@@ -4,6 +4,8 @@ package vtab
import (
"fmt"
"strings"
"time"
gosqlite3 "github.com/mattn/go-sqlite3"
)
@@ -41,9 +43,9 @@ func (a *moduleAdapter) build(c *gosqlite3.SQLiteConn, args []string, isCreate b
}
base := &baseVtabAdapter{table: table}
// if wt, ok := table.(WritableTable); ok {
// return &writableVtabAdapter{baseVtabAdapter: base, wt: wt}, nil
// }
if wt, ok := table.(WritableTable); ok {
return &writableVtabAdapter{baseVtabAdapter: base, wt: wt}, nil
}
return base, nil
}
@@ -53,9 +55,17 @@ func NewModuleAdapter(mod Module) gosqlite3.Module {
// ─── 桥接层:Table(只读)────────────────────────────────────
// planKey 是查询计划的唯一标识,由 BestIndex 写入、Filter 读取。
// 两个字段均由用户实现的 BestIndex 返回,SQLite 原样透传给 Filter
// 组合唯一对应一份约束元数据列表(列索引 + 操作符)。
type planKey struct {
idxNum int
idxStr string
idxNum int // 对应 IndexOutput.IdxNum,用于区分不同查询计划
idxStr string // 对应 IndexOutput.IdxStr,与 idxNum 配合进一步区分计划。
// 与 SQL 字段名无关,是 BestIndex → Filter 之间的自由通信通道,常见用途:
// 1. 传递索引名(如 "idx_name"),告知 Filter 按哪个索引逻辑过滤;
// 2. 序列化约束条件,Filter 直接解析,省去查 plans map 的步骤;
// 3. 传递排序方向(如 "asc"/"desc")。
// SQLite 不解释其含义,仅原样透传给 Filter。当前实现固定返回 "",未使用。
}
type baseVtabAdapter struct {
@@ -65,7 +75,16 @@ type baseVtabAdapter struct {
plans map[planKey][]ConstraintInfo
}
// BestIndex 是适配层的 xBestIndex 实现,将 go-sqlite3 的 C 结构转换为 Go 接口,
// 调用用户实现的 table.BestIndex,再把结果保存为"查询计划"供 Filter 阶段使用。
//
// 调用时机:每次 SQLite 准备执行针对此虚拟表的查询时调用,可能调用多次(不同约束组合)。
// 执行顺序:BestIndex → SQLite 选定计划)→ Filter(实际执行查询)。
//
// SQLite 对同一个 prepared statement 可以不重新调用 BestIndex
func (v *baseVtabAdapter) BestIndex(csts []gosqlite3.InfoConstraint, obs []gosqlite3.InfoOrderBy) (*gosqlite3.IndexResult, error) {
// 将 go-sqlite3 的 C 结构转换为 Go 的 ConstraintInfo,传给用户实现。
// 每个 constraint 对应 WHERE 子句中的一个条件(列、操作符、是否可用)。
ci := make([]ConstraintInfo, len(csts))
for i, c := range csts {
ci[i] = ConstraintInfo{Column: c.Column, Op: c.Op, Usable: c.Usable}
@@ -80,22 +99,35 @@ func (v *baseVtabAdapter) BestIndex(csts []gosqlite3.InfoConstraint, obs []gosql
return nil, err
}
// 按值传入顺序收集 Used=true 的约束,供 Filter 阶段绑定值
// adapter 统一接管所有 Usable 的约束,用户无需在 IndexOutput 声明 Used
// Filter 阶段 SQLite 只传入 Used=true 的约束值(argv),
// 需要靠这里保存的顺序和列信息才能还原出完整的 ConstraintInfo。
used := make([]bool, len(ci))
var usedCi []ConstraintInfo
for i, used := range out.Used {
if used {
usedCi = append(usedCi, ci[i])
for i, c := range ci {
if c.Usable {
used[i] = true
usedCi = append(usedCi, c)
}
}
// 用约束的列索引+操作符自动生成唯一 planKey,确保不同查询类型的计划互不覆盖。
parts := make([]string, len(usedCi))
for i, c := range usedCi {
parts[i] = fmt.Sprintf("%d:%d", c.Column, int(c.Op))
}
idxStr := strings.Join(parts, ",")
idxNum := len(usedCi)
if v.plans == nil {
v.plans = make(map[planKey][]ConstraintInfo)
}
v.plans[planKey{out.IdxNum, out.IdxStr}] = usedCi
v.plans[planKey{idxNum, idxStr}] = usedCi
return &gosqlite3.IndexResult{
Used: out.Used,
IdxNum: out.IdxNum,
IdxStr: out.IdxStr,
Used: used,
IdxNum: idxNum,
IdxStr: idxStr,
AlreadyOrdered: out.AlreadyOrdered,
EstimatedCost: out.EstimatedCost,
EstimatedRows: out.EstimatedRows,
@@ -110,7 +142,7 @@ func (v *baseVtabAdapter) Open() (gosqlite3.VTabCursor, error) {
if err != nil {
return nil, err
}
return &cursorAdapter{cursor: c, adapter: v}, nil
return &cursorAdapter{cursor: c, plans: v.plans}, nil
}
// ─── 桥接层:WritableTable ────────────────────────────────────
@@ -138,25 +170,49 @@ func (v *writableVtabAdapter) Update(rowid any, values []any) error {
// ─── 桥接层:Cursor ───────────────────────────────────────────
type cursorAdapter struct {
cursor Cursor
adapter *baseVtabAdapter
cursor Cursor
// plans 是 Open() 时从 adapter 复制的计划快照,与后续 BestIndex 调用隔离,
// 防止 list/item 等不同查询的 BestIndex 相互覆盖导致 Filter 拿到错误的列信息。
plans map[planKey][]ConstraintInfo
}
func (c *cursorAdapter) Close() error { return c.cursor.Close() }
func (c *cursorAdapter) Next() error { return c.cursor.Next() }
func (c *cursorAdapter) EOF() bool { return c.cursor.EOF() }
// Filter 是适配层的 xFilter 实现,将 SQLite 传入的约束值与 BestIndex 保存的计划合并,
// 还原出完整的 ConstraintInfo 列表后调用用户实现的 tCursor.Filter。
//
// 调用时机:每次实际执行查询时(包括 IN 展开的每一次子查询)。
// 执行顺序:BestIndex(保存计划)→ Filter(绑定值、执行查询)。
//
// Filter 的本质是把两份分离的信息合并成一条完整的过滤条件:
// ci[i].Column + ci[i].Op ←(BestIndex 存的:哪列、什么操作)
// +
// vals[i] ←(SQLite 传的:过滤值)
// =
// WHERE column OP value ←(最终传给 tCursor.Filter 的约束)
// 合并完之后交给 tCursor.Filter,再转成 fiter map,最终作为参数传给 vt.Select 去调 API。
func (c *cursorAdapter) Filter(idxNum int, idxStr string, vals []any) error {
ci := c.adapter.plans[planKey{idxNum, idxStr}]
// 通过 (idxNum, idxStr) 找到 BestIndex 阶段保存的约束元数据(列索引、操作符)。
// vals 只含约束的值,没有列和操作符信息,必须与 ci 对应位置合并才能还原完整约束。
ci := c.plans[planKey{idxNum, idxStr}]
// vals 长度 = BestIndex 中 Used=true 的约束数量(SQLite 保证一一对应)。
// ⚠️ SQLite 3.38+ IN 约束场景下,ci 可能比 vals 短(计划被 Usable=false 调用冲掉时)。
// 此时超出 ci 长度的约束 Column/Op 会是零值,由 tCursor.Filter 根据 Op 类型决定是否使用。
constraints := make([]ConstraintInfo, len(vals))
for i, val := range vals {
constraints[i].Value = val
constraints[i].Value = val // 绑定 SQLite 传入的约束值
if i < len(ci) {
constraints[i].Column = ci[i].Column
constraints[i].Op = ci[i].Op
constraints[i].Column = ci[i].Column // 对应列索引,用于 GetColField
constraints[i].Op = ci[i].Op // 操作符,用于映射到 exp.BooleanOperation
constraints[i].Usable = true
}
// i >= len(ci):计划缺失,Column=0/Op=0(OpIN)/Usable=false
// tCursor.Filter 需针对 OpIN 单独放行(不依赖 Usable 判断)。
}
return c.cursor.Filter(idxNum, constraints)
}
@@ -194,6 +250,8 @@ func resultValue(ctx *gosqlite3.SQLiteContext, val any) {
} else {
ctx.ResultInt(0)
}
case time.Time:
ctx.ResultText(v.Format("2006-01-02 15:04:05"))
case string:
ctx.ResultText(v)
case []byte:
+9
View File
@@ -2,6 +2,15 @@
package vtab
import "git.fsdpf.net/go/db/exp"
// FilterValue 是一个 WHERE 约束值,包含实际值和操作符类型。
// 用于 BestIndex/Filter 阶段向上层传递结构化的过滤条件。
type FilterValue struct {
Value any
Op exp.BooleanOperation
}
// Module 是虚拟表工厂,每个数据库连接各调用一次。
type Module interface {
// Create 在 CREATE VIRTUAL TABLE 时调用。
+18 -13
View File
@@ -15,8 +15,8 @@ package vtab
import (
"database/sql"
"fmt"
"regexp"
"sync"
"time"
"git.fsdpf.net/go/db"
"git.fsdpf.net/go/db/exp"
@@ -32,12 +32,13 @@ type Op = gosqlite3.Op
// 操作符常量,与 SQLite C API 值一致。
const (
OpEQ Op = gosqlite3.OpEQ // =
OpGT Op = gosqlite3.OpGT // >
OpLE Op = gosqlite3.OpLE // <=
OpLT Op = gosqlite3.OpLT // <
OpGE Op = gosqlite3.OpGE // >=
OpLIKE Op = gosqlite3.OpLIKE // LIKE
OpEQ Op = gosqlite3.OpEQ // =
OpGT Op = gosqlite3.OpGT // >
OpLE Op = gosqlite3.OpLE // <=
OpLT Op = gosqlite3.OpLT // <
OpGE Op = gosqlite3.OpGE // >=
OpLIKE Op = gosqlite3.OpLIKE // LIKE
OpREGEXP Op = gosqlite3.OpREGEXP // REGEXP
// OpLIMIT / OpOFFSETgo-sqlite3 尚未导出这两个常量,直接使用 SQLite C API 原始值。
// BestIndex 中将它们标记为 Used=true 后,Filter 可收到 LIMIT / OFFSET 的实际值。
@@ -63,16 +64,13 @@ type OrderByInfo struct {
}
// IndexOutput 是 BestIndex 的返回值,告知 SQLite 本表能处理哪些约束。
// IdxNum/IdxStr 由 adapter 层根据 Used 约束自动生成,用户无需设置。
type IndexOutput struct {
// Used[i]=true 表示第 i 个约束由本表自行处理。
// 对应约束的值会按原顺序在 Filter.constraintValues 中传入。
// len(Used) 必须等于传入 BestIndex 的 constraints 长度。
Used []bool
// IdxNum 和 IdxStr 是传给 Filter 的不透明标识,用于区分不同查询计划。
IdxNum int
IdxStr string
// AlreadyOrdered 为 true 时 SQLite 不再对结果二次排序。
AlreadyOrdered bool
@@ -106,7 +104,7 @@ func DialectOptions() *db.SQLDialectOptions {
opts.DefaultValuesFragment = []byte("")
opts.True = []byte("1")
opts.False = []byte("0")
opts.TimeFormat = time.RFC3339Nano
opts.TimeFormat = "2006-01-02 15:04:05"
opts.BooleanOperatorLookup = map[exp.BooleanOperation][]byte{
exp.EqOp: []byte("="),
exp.NeqOp: []byte("!="),
@@ -165,7 +163,7 @@ func init() {
sql.Register(DriverName, &gosqlite3.SQLiteDriver{
ConnectHook: func(conn *gosqlite3.SQLiteConn) error {
// 内置 IF(cond, trueVal, falseVal) 函数
if err := conn.RegisterFunc("IF", func(cond int64, trueVal, falseVal interface{}) interface{} {
if err := conn.RegisterFunc("IF", func(cond int64, trueVal, falseVal any) any {
if cond != 0 {
return trueVal
}
@@ -173,6 +171,13 @@ func init() {
}, true); err != nil {
return err
}
if err := conn.RegisterFunc("REGEXP", func(expr, item string) (bool, error) {
return regexp.MatchString(expr, item)
}, true); err != nil {
return err
}
// 注册所有已登记的虚拟表模块
registryMu.RLock()
defer registryMu.RUnlock()
+69 -1
View File
@@ -116,11 +116,79 @@ type usersCursor struct {
pos int
}
func (c *usersCursor) Filter(_ int, _ []vtab.ConstraintInfo) error {
func (c *usersCursor) Filter(_ int, constraints []vtab.ConstraintInfo) error {
var filtered []userRow
for _, row := range c.rows {
if rowMatchesAll(row, constraints) {
filtered = append(filtered, row)
}
}
c.rows = filtered
c.pos = 0
return nil
}
func rowMatchesAll(row userRow, constraints []vtab.ConstraintInfo) bool {
for _, c := range constraints {
switch c.Column {
case 0: // id
v := toInt64(c.Value)
switch c.Op {
case vtab.OpEQ:
if row.id != v {
return false
}
case vtab.OpGT:
if !(row.id > v) {
return false
}
case vtab.OpGE:
if !(row.id >= v) {
return false
}
case vtab.OpLT:
if !(row.id < v) {
return false
}
case vtab.OpLE:
if !(row.id <= v) {
return false
}
}
case 1: // name
val, _ := c.Value.(string)
if c.Op == vtab.OpEQ && row.name != val {
return false
}
case 2: // age
v := toInt64(c.Value)
switch c.Op {
case vtab.OpEQ:
if row.age != v {
return false
}
case vtab.OpGT:
if !(row.age > v) {
return false
}
case vtab.OpGE:
if !(row.age >= v) {
return false
}
case vtab.OpLT:
if !(row.age < v) {
return false
}
case vtab.OpLE:
if !(row.age <= v) {
return false
}
}
}
}
return true
}
func (c *usersCursor) Next() error { c.pos++; return nil }
func (c *usersCursor) EOF() bool { return c.pos >= len(c.rows) }
func (c *usersCursor) Close() error { return nil }
+6 -3
View File
@@ -93,13 +93,16 @@ func (sst *sqlserverTest) SetupSuite() {
func (sst *sqlserverTest) SetupTest() {
if _, err := sst.db.Exec(dropTable); err != nil {
panic(err)
sst.T().Skipf("SQLServer not available: %v", err)
return
}
if _, err := sst.db.Exec(createTable); err != nil {
panic(err)
sst.T().Skipf("SQLServer not available: %v", err)
return
}
if _, err := sst.db.Exec(insertDefaultRecords); err != nil {
panic(err)
sst.T().Skipf("SQLServer not available: %v", err)
return
}
}