-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlbuilder_insert.go
More file actions
65 lines (59 loc) · 1.7 KB
/
sqlbuilder_insert.go
File metadata and controls
65 lines (59 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package qsql
import (
"context"
"database/sql"
"fmt"
"reflect"
"strings"
"github.com/gwaylib/errors"
)
const (
addObjSql = "INSERT INTO %s (%s) VALUES (%s);"
)
// field flag like: `db:"name"`
// more: github.com/jmoiron/sqlx
func insertStruct(exec Execer, ctx context.Context, obj interface{}, tbName string, driverName ...string) (sql.Result, error) {
drvName := getDrvName(exec, driverName...)
fields, err := reflectInsertStruct(obj, drvName)
if err != nil {
return nil, errors.As(err)
}
execSql := fmt.Sprintf(addObjSql, tbName, strings.Join(fields.Names, ", "), strings.Join(fields.Stmts, ", "))
// log.Debugf("%s%+v", execSql, vals)
result, err := exec.ExecContext(ctx, execSql, fields.Values...)
if err != nil {
return nil, errors.As(err, execSql)
}
if fields.AutoIncrement != nil {
id, _ := result.LastInsertId()
var val reflect.Value
kind := fields.AutoIncrement.Kind()
switch kind {
case reflect.Int:
val = reflect.ValueOf(int(id))
case reflect.Int8:
val = reflect.ValueOf(int8(id))
case reflect.Int16:
val = reflect.ValueOf(int16(id))
case reflect.Int32:
val = reflect.ValueOf(int32(id))
case reflect.Int64:
val = reflect.ValueOf(int64(id))
case reflect.Uint: // Warnning: this maybe out of int64
val = reflect.ValueOf(uint(id))
case reflect.Uint8:
val = reflect.ValueOf(uint8(id))
case reflect.Uint16:
val = reflect.ValueOf(uint16(id))
case reflect.Uint32:
val = reflect.ValueOf(uint32(id))
case reflect.Uint64: // Warnning: this maybe out of int64
val = reflect.ValueOf(uint64(id))
default:
// unsupport other kind here
panic("unsupport auto increment kind: " + kind.String())
}
fields.AutoIncrement.Set(val)
}
return result, nil
}