v1 schema struct mapping

This commit is contained in:
Jay 2018-04-20 14:09:27 +08:00
parent a4488be12b
commit 04b2cb38b1
2 changed files with 71 additions and 10 deletions

View File

@ -24,8 +24,12 @@ func ScanToStruct(rows *sql.Rows, ss interface{}) (err error) {
func ScanToStructAll(rows *sql.Rows, ss interface{}) error {
sliceVal := reflect.Indirect(reflect.ValueOf(ss))
if sliceVal.Kind() != reflect.Slice && sliceVal.Kind() != reflect.Map {
return errors.New("need a pointer to a slice or a map")
if sliceVal.Kind() != reflect.Slice {
return errors.New("need a pointer to a slice ")
}
vt := sliceVal.Type().Elem()
if vt.Kind() != reflect.Struct {
return errors.New("need struct slice")
}
data, err := ResultToMap(rows)
@ -34,7 +38,13 @@ func ScanToStructAll(rows *sql.Rows, ss interface{}) error {
}
for i := range data {
tmp := reflect.New(vt)
iface := tmp.Interface()
err = MapToStruct(data[i], iface)
if err != nil {
return err
}
sliceVal.Set(reflect.Append(sliceVal, reflect.ValueOf(iface).Elem()))
}
return nil

65
main.go
View File

@ -4,29 +4,80 @@ import (
"database/sql"
"fmt"
"log"
"reflect"
"git.trj.tw/golang/utils/dbtool"
_ "github.com/lib/pq"
)
// FileT - file db schema
type FileT struct {
ID string `db:"id"`
Name string `db:"name"`
ID string `sql:"id"`
Name string `sql:"name"`
}
func main() {
connStr := "postgres://postgres@localhost:5432/mystorage?sslmode=disable"
db, err := sql.Open("postgres", connStr)
handleError(err)
defer db.Close()
rows, err := db.Query(`select id, name from "storage"."files" where "tmp" = $1 and "trash" = $2 limit 2`, false, false)
handleError(err)
defer rows.Close()
var id, name string
for rows.Next() {
rows.Scan(&id, &name)
fmt.Printf("id: %s, name: %s \n", id, name)
}
// mm, err := dbtool.ResultToMap(rows)
// handleError(err)
var files []FileT
err = dbtool.ScanToStructAll(rows, &files)
fmt.Println(files)
// var id, name string
// for rows.Next() {
// rows.Scan(&id, &name)
// fmt.Printf("id: %s, name: %s \n", id, name)
// }
// var fts []FileT
// err := ttt(&fts)
// handleError(err)
// fmt.Println(fts[0].Name)
}
func ttt(dest interface{}) error {
vv := reflect.Indirect(reflect.ValueOf(dest))
fmt.Println(vv)
vt := vv.Type().Elem()
fmt.Println(vt)
fmt.Println("test :::::::::")
pv := reflect.New(vt)
fmt.Println(pv.Kind(), pv.Elem().Kind(), pv.Type())
// fmt.Println(pv.Elem().Type().Field(0).Name)
pve := pv.Interface()
// fmt.Println(reflect.ValueOf(pv.Interface()).Elem().NumField())
d := make(map[string]interface{})
d["id"] = sql.RawBytes{0x30}
d["name"] = sql.RawBytes{0x31, 0x32}
err := dbtool.MapToStruct(d, pve)
handleError(err)
fmt.Println(pve)
// for i := 0; i < pve.NumField(); i++ {
// fmt.Println(pve.Type().Field(i).Name)
// }
vv.Set(reflect.Append(vv, reflect.ValueOf(pve).Elem()))
fmt.Println("test :::::::::")
return nil
}
func handleError(err error) {