Hello, Run the test code below, it will panic as error:
panic: invalid sql type Tests (slice) for sqlite3
But the Test has scan and value method.
package main
import (
"database/sql/driver"
"fmt"
"os"
"strconv"
"strings"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
var db *gorm.DB
func init() {
var err error
os.Remove("test.db")
db, err = gorm.Open("sqlite3", "test.db")
if err != nil {
panic(err)
}
db.LogMode(true)
}
type User struct {
ID int
No int
Name string
Tests Tests
}
func main() {
db = db.Debug()
db.Exec("PRAGMA foreign_keys = ON;")
db.DropTable(&User{})
db.CreateTable(&User{})
if err := db.Create(&User{
Name: "user",
No: 10,
Tests: Tests{1.2, 3.4},
}).Error; err != nil {
fmt.Print(err)
}
}
type Tests []float64
func (c *Tests) Scan(value interface{}) error {
b, ok := value.(string)
if !ok {
return fmt.Errorf("Invalid Value")
}
if strings.TrimSpace(b) == "" {
return nil
}
strs := strings.Split(strings.TrimSpace(b), " ")
for _, s := range strs {
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return fmt.Errorf("Invalid Value")
}
*c = append(*c, f)
}
return nil
}
func (c Tests) Value() (driver.Value, error) {
strs := []string{}
for _, f := range c {
strs = append(strs, strconv.FormatFloat(f, 'f', -1, 64))
}
return strings.Join(strs, " "), nil
}
Maybe it a bug? Thanks.
Is this a currrent BUG ?
Yes, I use the newest commit.
I've been dealing with similar problem recently, and it seems that sql.Scanner and driver.Valuer interfaces don't help detecting underlying type at all. They're only used during query execution (when you pass the value to or from the database). Auto-migration (and creating tables) is a different problem.
Is there any resolution or a workaround on this? I've encountered the same problem after upgrading to go 1.8.3. It can't create the table even with the Scan and Value functions
OK, I've found a solution to the table creation problem. For []byte table elements, you need to use the gorm 'type' pragma:
MyValues []byte `gorm:"type:byte[]"`
I'm still seeing another problem, but to avoid confusion, I will post that in another comment.
Most helpful comment
OK, I've found a solution to the table creation problem. For []byte table elements, you need to use the gorm 'type' pragma:
I'm still seeing another problem, but to avoid confusion, I will post that in another comment.