Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Created April 17, 2019 19:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xeoncross/fddc78c2f97ff32dcd93b8c61f411702 to your computer and use it in GitHub Desktop.
Save xeoncross/fddc78c2f97ff32dcd93b8c61f411702 to your computer and use it in GitHub Desktop.
Simple helper function to reduce duplicated `rows.Scan()` code
package main
import (
"fmt"
"log"
"reflect"
"testing"
)
// What if you could provide the query, params, and the slice of objects to populate?
// All the type checks would still be performed without any lose of type safety.
// The only danger is that you don't map your result row columns to the correct
// object fields (which is a problem anyway).
//
// Query(sql string, params interface{}, result interface{}) error
//
// sqlstr := "SELECT id, name, email FROM user WHERE name LIKE ? AND age > ?"
// users := []*User{}
// params := []interface{}{"%Da%", 34}
// err := Query(sqlstr, params, &users)
//
type User struct {
Name string
Age int
}
func AddElement(a interface{}) {
if reflect.ValueOf(a).Type().Kind() != reflect.Ptr {
log.Fatalf("Needs to be a pointer: %#v\n", a)
}
v := reflect.ValueOf(a).Elem()
fmt.Println("Slice Type", v.Type())
fmt.Println("Slice Elements", v.Type().Elem())
x := reflect.New(v.Type().Elem())
// fmt.Println("New Type", x.Type().String())
// fmt.Println("New Value", reflect.ValueOf(x))
// dump(x)
DumpValue(x)
// b := x
b := reflect.ValueOf(x)
// val := reflect.Indirect(reflect.ValueOf(x))
// // DumpValue(val)
// fmt.Println("name", val.Type().Field(0).Name)
for i := 0; i < b.NumField(); i++ {
f := b.Field(i)
fmt.Printf("\t%s is %s\n", f.Type().Name(), f.Type().String())
}
}
func TestAddSliceElements(t *testing.T) {
var users []*User
AddElement(&users)
if len(users) != 1 {
t.Errorf("Expected 1 user, got %d\n", len(users))
}
}
func DumpValue(v reflect.Value) {
fmt.Printf("%s: %v: CanAddr: %v, CanSet: %v, CanInterface: %v, IsNil: %v, IsValid: %v\n", v.Type(), v.Kind(), v.CanAddr(), v.CanSet(), v.CanInterface(), v.IsNil(), v.IsValid())
}
//
// So what does this look like for a database query?
//
// var db *sql.DB
// h := reflect.ValueOf(db)
// params := []reflect.Value{reflect.ValueOf("each param")}
//
// // Call the query method
// // rows, err := db.Query(sqlstr, ...params)
// res := h.MethodByName("Query").Call(params)
//
// var rows *sql.Rows
// var err error
// rows, _ = res[0].Interface().(*sql.Rows)
// err, _ = res[1].Interface().(error)
// if err != nil {
// return
// }
//
// defer rows.Close()
//
// for rows.Next() {
// // Generate new instance of a user struct here
// // create another []reflect.Value{...} array of params with struct fields
// // convert rows to reflect.Value
// // Call res := rowsValue.MethodByName("Scan").Call(params)
// err = rows.Scan(...)
// if err != nil {
// return
// }
//
// // Append struct back to slice using reflect
// }
//
// err = rows.Err()
@xeoncross
Copy link
Author

xeoncross commented Apr 17, 2019

This isn't a complete example, I was tripping over proper use of the reflect package and could use some help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment