-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwriter.go
69 lines (63 loc) · 1.66 KB
/
writer.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package sql
import (
"context"
"database/sql"
"database/sql/driver"
"fmt"
"reflect"
q "github.com/core-go/sql"
)
type Writer[T any] struct {
db *sql.DB
tableName string
BuildParam func(i int) string
Map func(T)
BoolSupport bool
schema *q.Schema
Driver string
ToArray func(interface{}) interface {
driver.Valuer
sql.Scanner
}
}
func NewWriterWithMap[T any](db *sql.DB, tableName string, mp func(T), toArray func(interface{}) interface {
driver.Valuer
sql.Scanner
}, options ...func(i int) string) *Writer[T] {
var buildParam func(i int) string
if len(options) > 0 && options[0] != nil {
buildParam = options[0]
} else {
buildParam = q.GetBuild(db)
}
driver := q.GetDriver(db)
boolSupport := driver == q.DriverPostgres
var t T
modelType := reflect.TypeOf(t)
if modelType.Kind() == reflect.Ptr {
modelType = modelType.Elem()
}
schema := q.CreateSchema(modelType)
if len(schema.Keys) <= 0 {
panic(fmt.Sprintf("require primary key for table '%s'", tableName))
}
return &Writer[T]{db: db, tableName: tableName, BuildParam: buildParam, Map: mp, BoolSupport: boolSupport, schema: schema, Driver: driver, ToArray: toArray}
}
func NewWriter[T any](db *sql.DB, tableName string, opts ...func(T)) *Writer[T] {
var mp func(T)
if len(opts) >= 1 {
mp = opts[0]
}
return NewWriterWithMap[T](db, tableName, mp, nil)
}
func (w *Writer[T]) Write(ctx context.Context, model T) error {
if w.Map != nil {
w.Map(model)
}
query, args, err := q.BuildToSaveWithSchema(w.tableName, model, w.Driver, w.BuildParam, w.ToArray, w.schema)
if err != nil {
return err
}
_, er2 := w.db.ExecContext(ctx, query, args...)
return er2
}