【问题标题】:JSON1 support go-sqlite3 using gormJSON1 支持 go-sqlite3 使用 gorm
【发布时间】:2019-10-11 07:47:06
【问题描述】:

在以下示例中,我使用 json_extract(...) 在 Golang 中使用 go-sqlite3 驱动程序。

package main

import (
    _ "github.com/mattn/go-sqlite3"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/sqlite"
    "fmt"
    "encoding/json"
    "net/http"
)

func main() {

    var db *gorm.DB

    type Session struct {
        gorm.Model
        SessionID string `json:"session_id"`
        Options string `json:"options"`
    }

    db, err := gorm.Open("sqlite3", "./app.db")
    if err != nil {
        fmt.Println(err)
    }

    defer db.Close() 
    db.AutoMigrate(&Session{})

    var m map[string]int
    m = make(map[string]int)
    m["a"] = 1
    m["b"] = 2
    m["c"] = 3

    js, err := json.Marshal(m)

    sess := Session{
        SessionID: "test",
        Options: string(js),
    }

    db.Create(&sess)
    db.Save(&sess)

    var b = &Session{}

    type Result struct {
        Options string
    }

    // JSON test
    var res Result
    db.Raw("SELECT json_extract(options, '$.a') as Options from sessions").Scan(&res)

    fmt.Println(sess.ID)
    fmt.Println(res)

}

问题是我在重建go-sqlite3 驱动程序时无法激活JSON1 模块。它将在db.Raw(...) 行上出错undefined function: json_extract

无论如何,我知道对于 JSON 支持,github.com/mattn/go-sqlite3 必须与 -flags "sqlite_json1" 一起编译。我尝试了几种变体:

go build -a -flags "sqlite_json1"  github.com/mattn/go-sqlite3
go install -a -flags "sqlite_json1"  github.com/mattn/go-sqlite3
go build -a --flags "sqlite_json1"  github.com/mattn/go-sqlite3
go install -a --flags "sqlite_json1"  github.com/mattn/go-sqlite3

以及flags 的更多变体,例如sqlite_jsonjsonjson1 等。没有什么可以摆脱未定义函数错误。任何想法如何正确重建go-sqlite3

显然,在那之后我也重新构建了自己的代码。


一些信息:

go 版本:go version go1.13.1 linux/amd64(平台:Kubuntu 18.04)

go-sqlite3 版本:github.com/mattn/go-sqlite3 当前主控

gorm 版本:github.com/jinzhu/gorm 当前大师

【问题讨论】:

    标签: go go-gorm go-sqlite3


    【解决方案1】:

    根据go-sqlite3 的文档,以下任何标志都可以使用:

    • sqlite_json
    • sqlite_json1
    • json1

    这里是sqlite3_opt.json1.go 的内容,它定义了包含这个文件的标签。

    // Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>.
    //
    // Use of this source code is governed by an MIT-style
    // license that can be found in the LICENSE file.
    
    // +build sqlite_json sqlite_json1 json1
    
    package sqlite3
    
    /*
    #cgo CFLAGS: -DSQLITE_ENABLE_JSON1
    */
    import "C"
    

    参考:https://github.com/mattn/go-sqlite3/blob/master/sqlite3_opt_json1.go

    还要指出,您在 go build 命令中使用了 --flags,但请尝试使用 --tags

    【讨论】:

    • --tags--flags 与任何值 sqlite_jsonsqlite_json1json1 仍然会产生具有相同错误的构建。奇怪的是,直接在 C 合并中执行它确实有效,即:sqlite3-binding.c 中的 #define SQLITE_ENABLE_JSON1 1 并在 src 目录中运行 go build -a
    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 2012-06-23
    • 2021-06-23
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    相关资源
    最近更新 更多