Skip to content

Instantly share code, notes, and snippets.

@fuzzy
Created September 22, 2015 01:40
Show Gist options
  • Save fuzzy/fa5182310d89a476d531 to your computer and use it in GitHub Desktop.
Save fuzzy/fa5182310d89a476d531 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"reflect"
)
type ApiKey struct {
Key string
Enabled bool
Admin bool
}
func main() {
// iterate through the attributes of a Data Model instance
err := Insert(&ApiKey{Key: "blahblahblah", Enabled: true, Admin: false})
if err != nil {
fmt.Println(err)
}
}
func dump(f interface{}) (string, []string, []interface{}) {
var columns []string
var fields []interface{}
val := reflect.ValueOf(f).Elem()
typ := reflect.TypeOf(f)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
table := typ.Name()
for i := 0; i < val.NumField(); i++ {
vF := val.Field(i)
tF := val.Type().Field(i)
iF := vF.Interface()
columns = append(columns, tF.Name)
fields = append(fields, iF)
}
return table, columns, fields
}
func Insert(f interface{}) error {
table, cols, rows := dump(f)
retv := fmt.Sprintf("INSERT INTO %s (", table)
for _, k := range cols {
retv = fmt.Sprintf("%s%s, ", retv, k)
}
retv = fmt.Sprintf("%s) VALUES (", retv[:(len(retv)-2)])
for _, v := range rows {
switch x := v.(type) {
case bool:
retv = fmt.Sprintf("%s%t, ", retv, x)
case int:
retv = fmt.Sprintf("%s%d, ", retv, x)
default:
retv = fmt.Sprintf("%s'%s', ", retv, fmt.Sprint(x))
}
}
retv = fmt.Sprintf("%s)", retv[:(len(retv)-2)])
fmt.Printf("DEBUG: %s\n", retv)
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment