-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsert.go
More file actions
58 lines (48 loc) · 1.43 KB
/
insert.go
File metadata and controls
58 lines (48 loc) · 1.43 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
package querybuilder
import (
"errors"
"log"
"strings"
)
type InsertQuery struct {
table string
indexedColumnValues IndexedColumnValues
}
// MapValues gets columns and values,
// Enter Column/Values as a key/value map
func (s *InsertQuery) MapValues(columnValues map[string]interface{}) *InsertQuery {
newQuery := *s
newQuery.indexedColumnValues = mapToIndexColumnValue(columnValues)
return &newQuery
}
// StructValues gets and struct and extract column/values,
func (s *InsertQuery) StructValues(structure interface{}) *InsertQuery {
newQuery := *s
m, err := structToMap(structure)
if err != nil {
log.Panic(err)
}
newQuery.indexedColumnValues = m
return &newQuery
}
func (s *InsertQuery) Build() (string, []interface{}, error) {
if s.table == "" {
return "", nil, errors.New(ErrTableIsEmpty)
}
if len(s.indexedColumnValues) == 0 {
return "", nil, errors.New(ErrColumnValueMapIsEmpty)
}
var query string
args := make([]interface{}, len(s.indexedColumnValues))
// make column slice
columns := make([]string, len(s.indexedColumnValues))
for i := 0; i < len(s.indexedColumnValues); i++ {
indexedColumnValue := s.indexedColumnValues[i]
columns[i] = indexedColumnValue.Key
args[i] = indexedColumnValue.Value
}
//
// add table name
query = "INSERT INTO " + s.table + "(" + strings.Join(columns, ",") + ") VALUES(" + strings.TrimSuffix(strings.Repeat("?,", len(columns)), ",") + ")"
return query, args, nil
}