-
Notifications
You must be signed in to change notification settings - Fork 2
/
db_ctx.go
280 lines (253 loc) · 7.13 KB
/
db_ctx.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package goen
import (
"container/list"
"context"
"database/sql"
"fmt"
"log"
"reflect"
"github.com/kamichidu/goen/dialect"
"github.com/kamichidu/goen/internal"
sqr "gopkg.in/Masterminds/squirrel.v1"
)
// DBContext holds *sql.DB (and *sql.Tx) with contextual values.
// goen is intended to work with *sql.DB (and *sql.Tx) via DBContext.
type DBContext struct {
// This field is readonly.
// Sets via NewDBContext().
DB *sql.DB
// This field is readonly.
// Sets via UseTx(); or nil.
Tx *sql.Tx
// The patch compiler.
// This is used when need to compile patch to query.
Compiler PatchCompiler
// The logger for debugging.
// This is used when DebugMode(true).
Logger Logger
// The depth limit to avoid circular Include work.
// When this value is positive, Include works N-times.
// When this value is negative, Include works unlimited.
// When this value is 0, Include never works.
// Default is 10.
MaxIncludeDepth int
dialect dialect.Dialect
debug bool
patchBuffer *PatchList
stmtBuilder sqr.StatementBuilderType
stmtCacher sqr.DBProxyContext
}
// NewDBContext creates DBContext with given dialectName and db.
func NewDBContext(dialectName string, db *sql.DB) *DBContext {
dialectsMu.RLock()
dialect, ok := dialects[dialectName]
dialectsMu.RUnlock()
if !ok {
panic(fmt.Sprintf("goen: unknown dialect %q (forgotten import?)", dialectName))
}
return &DBContext{
DB: db,
MaxIncludeDepth: 10,
dialect: dialect,
patchBuffer: NewPatchList(),
stmtBuilder: sqr.StatementBuilder.PlaceholderFormat(dialect.PlaceholderFormat()),
stmtCacher: sqr.NewStmtCacher(db),
}
}
// Dialect returns dialect.Dialect holds by this context.
func (dbc *DBContext) Dialect() dialect.Dialect {
return dbc.dialect
}
// DebugMode sets debug flag.
func (dbc *DBContext) DebugMode(enabled bool) {
dbc.debug = enabled
}
// UseTx returns clone of current DBContext with given *sql.Tx.
func (dbc *DBContext) UseTx(tx *sql.Tx) *DBContext {
// replace db runner and copy state
clone := &DBContext{
DB: dbc.DB,
Tx: tx,
dialect: dbc.dialect,
debug: dbc.debug,
patchBuffer: NewPatchList(),
stmtBuilder: dbc.stmtBuilder,
stmtCacher: sqr.NewStmtCacher(tx),
}
clone.patchBuffer.PushBackList(dbc.patchBuffer)
return clone
}
// Patch adds raw patch into the buffer; without executing a query.
func (dbc *DBContext) Patch(v *Patch) {
dbc.patchBuffer.PushBack(v)
}
func (dbc *DBContext) Query(query string, args ...interface{}) (*sql.Rows, error) {
if dbc.debug {
dbc.debugPrintf("goen: %q with %v", query, args)
}
stmt, err := dbc.stmtCacher.Prepare(query)
if err != nil {
return nil, err
}
return stmt.Query(args...)
}
func (dbc *DBContext) QueryRow(query string, args ...interface{}) *sql.Row {
if dbc.debug {
dbc.debugPrintf("goen: %q with %v", query, args)
}
stmt, err := dbc.stmtCacher.Prepare(query)
if err != nil {
panic(err)
}
return stmt.QueryRow(args...)
}
func (dbc *DBContext) Scan(rows *sql.Rows, v interface{}) error {
out := reflect.ValueOf(v)
if out.Kind() != reflect.Ptr || out.IsNil() {
return fmt.Errorf("goen: Scan only accepts pointer of slice, but got %q", out.Type())
}
out = out.Elem()
rowTyp := out.Type().Elem()
cols, err := rows.ColumnTypes()
if err != nil {
return err
}
for rows.Next() {
rowVal, err := dbc.scanRow(rows, cols, rowTyp)
if err != nil {
return err
}
out = reflect.Append(out, rowVal)
}
reflect.ValueOf(v).Elem().Set(out)
return nil
}
func (dbc *DBContext) Include(v interface{}, sc *ScopeCache, loader IncludeLoader) error {
recordsList := list.New()
recordsList.PushBack(v)
for depth := 0; depth < dbc.MaxIncludeDepth; depth++ {
nextRecordsList := list.New()
for records := recordsList.Front(); records != nil; records = records.Next() {
if err := loader.Load((*IncludeBuffer)(nextRecordsList), sc, records.Value); err != nil {
return err
}
}
if nextRecordsList.Len() == 0 {
return nil
}
recordsList = nextRecordsList
}
return nil
}
func (dbc *DBContext) scanRow(rows sqr.RowScanner, cols []*sql.ColumnType, rowTyp reflect.Type) (reflect.Value, error) {
switch rowTyp.Kind() {
case reflect.Slice:
dest := make([]interface{}, len(cols))
args := make([]interface{}, len(cols))
for i := range cols {
// if possible to get ScanType, suggest to use its type
if typ := dbc.dialect.ScanTypeOf(cols[i]); typ != nil {
dest[i] = reflect.New(typ).Elem()
}
args[i] = &dest[i]
}
if err := rows.Scan(args...); err != nil {
return reflect.Value{}, err
}
return reflect.ValueOf(dest), nil
case reflect.Map:
res, err := dbc.scanRow(rows, cols, reflect.SliceOf(reflect.TypeOf((*interface{})(nil)).Elem()))
if err != nil {
return res, err
}
m := reflect.MakeMapWithSize(rowTyp, len(cols))
for i := range cols {
key := reflect.ValueOf(cols[i].Name())
value := res.Index(i)
m.SetMapIndex(key, value)
}
return m, nil
case reflect.Ptr:
res, err := dbc.scanRow(rows, cols, rowTyp.Elem())
if res.CanAddr() {
res = res.Addr()
}
return res, err
case reflect.Struct:
dest := reflect.New(rowTyp).Elem()
strct := internal.NewStructFromReflect(rowTyp)
fields := internal.FieldsByFunc(strct.Fields(), internal.IsColumnField)
args := make([]interface{}, len(cols))
for i := range cols {
var rfv reflect.Value
if field, ok := internal.FieldByFunc(fields, internal.EqColumnName(cols[i].Name())); ok {
rfv = dest.FieldByName(field.Name())
}
if !rfv.IsValid() {
panic(fmt.Sprintf("goen: unknown struct field for column %q on %v", cols[i].Name(), rowTyp))
}
args[i] = rfv.Addr().Interface()
}
if err := rows.Scan(args...); err != nil {
return reflect.Value{}, err
}
return dest, nil
default:
return reflect.Value{}, fmt.Errorf("goen: unsupported scan type %q", rowTyp)
}
}
func (dbc *DBContext) CompilePatch() *SqlizerList {
patches := *dbc.patchBuffer
dbc.patchBuffer.Init()
compiler := dbc.Compiler
if compiler == nil {
compiler = DefaultCompiler
}
opts := &CompilerOptions{
StmtBuilder: dbc.stmtBuilder,
Patches: &patches,
}
return compiler.Compile(opts)
}
func (dbc *DBContext) SaveChanges() error {
return dbc.SaveChangesContext(context.Background())
}
func (dbc *DBContext) SaveChangesContext(ctx context.Context) error {
sqlizers := dbc.CompilePatch()
for curr := sqlizers.Front(); curr != nil; curr = curr.Next() {
sqlizer := curr.GetValue()
query, args, err := sqlizer.ToSql()
if err != nil {
return err
}
if dbc.debug {
dbc.debugPrintf("goen: %q with %v", query, args)
}
stmt, err := dbc.stmtCacher.PrepareContext(ctx, query)
if err != nil {
return err
}
if _, err := stmt.ExecContext(ctx, args...); err != nil {
return err
}
}
return nil
}
func (dbc *DBContext) debugPrint(v ...interface{}) {
if l, ok := dbc.Logger.(leveledLogger); ok {
l.Debug(v...)
} else if dbc.Logger != nil {
dbc.Logger.Print(v...)
} else {
log.Print(v...)
}
}
func (dbc *DBContext) debugPrintf(format string, args ...interface{}) {
if l, ok := dbc.Logger.(leveledLogger); ok {
l.Debugf(format, args...)
} else if dbc.Logger != nil {
dbc.Logger.Printf(format, args...)
} else {
log.Printf(format, args...)
}
}