-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathinsert.go
49 lines (42 loc) · 1.41 KB
/
insert.go
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
package goqux
import (
"github.com/doug-martin/goqu/v9"
"github.com/doug-martin/goqu/v9/exp"
)
type InsertOption func(table exp.IdentifierExpression, s *goqu.InsertDataset) *goqu.InsertDataset
func WithInsertDialect(dialect string) InsertOption {
return func(table exp.IdentifierExpression, s *goqu.InsertDataset) *goqu.InsertDataset {
return s.WithDialect(dialect)
}
}
func WithInsertReturningAll() InsertOption {
return func(table exp.IdentifierExpression, s *goqu.InsertDataset) *goqu.InsertDataset {
return s.Returning(goqu.Star())
}
}
func WithInsertReturning(columns ...string) InsertOption {
return func(table exp.IdentifierExpression, s *goqu.InsertDataset) *goqu.InsertDataset {
cols := make([]any, 0, len(columns))
for _, c := range columns {
cols = append(cols, table.Col(c))
}
return s.Returning(cols...)
}
}
func WithInsertNotPrepared() InsertOption {
return func(table exp.IdentifierExpression, s *goqu.InsertDataset) *goqu.InsertDataset {
return s.Prepared(false)
}
}
func BuildInsert(tableName string, values []any, options ...InsertOption) (string, []any, error) {
table := goqu.T(tableName)
q := goqu.Insert(table).WithDialect(defaultDialect)
encodedValues := make([]map[string]SQLValuer, len(values))
for i, value := range values {
encodedValues[i] = encodeValues(value, skipInsert, false)
}
for _, o := range options {
q = o(table, q)
}
return q.Rows(encodedValues).ToSQL()
}