jmoiron / modl

golang database modelling library
MIT License
480 stars 48 forks source link

PostGet does not work for slices #46

Open fd0 opened 8 years ago

fd0 commented 8 years ago

When loading a slice of structs from the database and the struct has a function PostGet(), modl panics:

package main

import (
    "database/sql"
    "fmt"
    "log"

    "github.com/jmoiron/modl"
    _ "github.com/mattn/go-sqlite3"
)

type Person struct {
    ID   int64
    Name string
    Extra string
}

func (p *Person) PostGet(db modl.SqlExecutor) error {
    p.Extra = "x"
    return nil
}

func main() {
    db, err := sql.Open("sqlite3", ":memory:")
    if err != nil {
        log.Fatalf("sql.Open(): %v", err)
    }

    dbmap := modl.NewDbMap(db, modl.SqliteDialect{})
    dbmap.AddTableWithName(Person{}, "people").SetKeys(true, "id")

    if err = dbmap.CreateTablesIfNotExists(); err != nil {
        log.Fatal(err)
    }

    var p Person
    p.Name = "foobar"

    if err = dbmap.Insert(&p); err != nil {
        log.Fatal(err)
    }

    // PostGet works fine with a single Person
    var p2 Person
    err = dbmap.SelectOne(&p2, "select * from people where id = ?", p.ID)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("p2: %v\n", p2)

    // but fails with a panic for []Person
    var people []Person
    err = dbmap.Select(&people, "select * from people", p.ID)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("people: %v\n", people)
}

Result:

$ go run main.go
p2: {1 foobar x}
panic: interface conversion: main.Person is not modl.PostGetter: missing method PostGet

goroutine 1 [running]:
panic(0x5fc0e0, 0xc820012600)
    /usr/lib/go/src/runtime/panic.go:481 +0x3e6
github.com/jmoiron/modl.hookedselect(0xc8200161e0, 0x7f078a3ee4e8, 0xc8200161e0, 0x5b18e0, 0xc8200106c0, 0x64f560, 0x14, 0xc82000a810, 0x1, 0x1, ...)
    /home/fd0/shared/work/web/ghenga/vendor/src/github.com/jmoiron/modl/modl.go:171 +0x2e0
github.com/jmoiron/modl.(*DbMap).Select(0xc8200161e0, 0x5b18e0, 0xc8200106c0, 0x64f560, 0x14, 0xc82000a810, 0x1, 0x1, 0x0, 0x0)
    /home/fd0/shared/work/web/ghenga/vendor/src/github.com/jmoiron/modl/dbmap.go:351 +0xcd
main.main()
    /home/fd0/shared/work/web/ghenga/src/ghenga/modl-debug/main.go:54 +0x9a1
exit status 2
[1]    19228 exit 1     go run main.go
fungl164 commented 8 years ago

Change the slice to var people []*Person. Worked for me....

fd0 commented 8 years ago

Oh, that did the trick. Is this documented somewhere and I was just too stupid to find it?