使用araddon/qlbridge 我们可以开发一个通用的sql 引擎,go-memdb 是hashicorp 公司开发的
一个基于内存的支持事务的db,araddon/qlbridge 官方已经支持了go-memdb,以下是一个简单
的试用
环境准备
- go.mod
module demoapp
?
go 1.15
?
require (
github.com/araddon/dateparse v0.0.0-20190622164848-0fb0a474d195
github.com/araddon/gou v0.0.0-20190110011759-c797efecbb61
github.com/araddon/qlbridge v0.0.0-20200708000952-ce9ad213e74c // indirect
)
- main.go
package main
?
import (
"database/sql"
"database/sql/driver"
"flag"
"fmt"
"log"
"strings"
?
"github.com/araddon/qlbridge/datasource/memdb"
_ "github.com/araddon/qlbridge/qlbdriver"
"github.com/araddon/qlbridge/schema"
?
u "github.com/araddon/gou"
"github.com/araddon/qlbridge/expr/builtins"
)
?
var (
logging = "info"
)
?
func init() {
?
flag.StringVar(&logging, "logging", "info", "logging [ debug,info ]")
flag.Parse()
u.SetupLogging(logging)
u.SetColorOutput()
}
?
func main() {
builtins.LoadAllBuiltins()
inrow := []driver.Value{"dalong", 2222, "v2"}
inrow2 := []driver.Value{"dalong1", 2222, "v2"}
memdb, err := memdb.NewMemDbData("demoapp", [][]driver.Value{inrow, inrow2}, []string{"name", "age", "version"})
if err != nil {
log.Fatalln("memdb error", err.Error())
}
schema.RegisterSourceAsSchema("demoapp", memdb)
db, err := sql.Open("qlbridge", "demoapp")
if err != nil {
panic(err.Error())
}
defer db.Close()
// some insert ops
_, err = db.Exec(`insert into demoapp(name,age,version) values(‘dalongdemo‘,333,‘v3‘))`)
if err != nil {
log.Fatalln("insert errpr")
}
// query
rows, err := db.Query("select name,age,version,now() as now from demoapp")
if err != nil {
u.Errorf("could not execute query: %v", err)
return
}
defer rows.Close()
cols, _ := rows.Columns()
readCols := make([]interface{}, len(cols))
writeCols := make([]string, len(cols))
for i := range writeCols {
readCols[i] = &writeCols[i]
}
fmt.Printf("\n\nScanning through memdb: (%v)\n\n", strings.Join(cols, ","))
for rows.Next() {
rows.Scan(readCols
fmt.Println(strings.Join(writeCols, ", "))
}
fmt.Println("")
}
- 代码说明
因为qlbridge已经包装好了一个memdb 的schema source,我们需要的操作是直接初始话,同时定义schema
memdb datasource 的初始化大致有三种方法:包含数据,不包含数据,以及支持索引的,我们初始化memdb
只会就可以使用sql 进行memdb的操作了,可以进行insert select 同时可以使用自定义的表达式,以上代码就包含了
一个简单的insert 以及select 操作
运行&&效果
- 运行
go run cmd/memdb/main.go
- 效果
说明
目前测试araddon/qlbridge 有一点是对于* 模式的支持不太好,所以写编写sql 的时候需要指定明确的列
参考资料
https://github.com/araddon/qlbridge
https://github.com/rongfengliang/qlbridge-learning
https://github.com/hashicorp/go-memdb