Created
July 18, 2017 13:25
-
-
Save hugows/cebf8318aad7d6bf62a4f26d8c91ffe7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A slower insert that is faster to type. | |
func (db *DB) ReflectInsert(tablename string, obj interface{}) error { | |
base := "INSERT INTO %s(%s) VALUES (%s)" | |
count := 1 | |
var columns []string | |
var placeholders []string | |
var vals []interface{} | |
v := reflect.ValueOf(obj).Elem() | |
t := v.Type() | |
for index := 0; index < v.NumField(); index++ { | |
// // Skip autogenerated fields on insert | |
tag := t.Field(index).Tag.Get("db") | |
tagName, opts := parseTag(tag) | |
if opts.Contains("noinsert") { | |
continue | |
} | |
vals = append(vals, v.Field(index).Interface()) | |
columns = append(columns, tagName) | |
placeholders = append(placeholders, fmt.Sprintf("$%d", count)) | |
count++ | |
} | |
insert := fmt.Sprintf( | |
base, | |
tablename, | |
strings.Join(columns, ","), | |
strings.Join(placeholders, ",")) | |
// Actual insert | |
fmt.Println(insert, vals) | |
_, err := db.Exec(insert, vals...) | |
return err | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment