This repository has been archived by the owner on Jan 8, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
table.go
394 lines (321 loc) · 10.3 KB
/
table.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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
package gomodel
import (
"fmt"
"reflect"
"strconv"
"github.com/cosiner/gomodel/utils"
)
type (
// SQLBuilder build sql for model using fields and where fields
SQLBuilder func(driver Driver, fields, whereFields uint64) string
// Table represent information of type
// contains field count, table name, field names, field offsets
//
// because count sql and limit select sql is both stored in the same cache,
// you should not use a empty fields for limit select, that will conflict with
// count sql and get the wrong sql statement.
Table struct {
Name string
NumFields uint64
cache cache
columns []string
prefix string // Name + "."
colsCache map[uint64]Cols
}
)
// FieldsIdentity create signature from fields
func FieldsIdentity(sqlType SQLType, numField, fields, whereFields uint64) uint64 {
return fields<<numField | whereFields | uint64(sqlType)
}
// Stmt get sql from cache container, if cache not exist, then create new
func (t *Table) Stmt(exec Executor, sqlType SQLType, fields, whereFields uint64, build SQLBuilder) (Stmt, error) {
id := FieldsIdentity(sqlType, t.NumFields, fields, whereFields)
sql_, stmt, err := t.cache.GetStmt(exec, id)
if err != nil {
return nil, err
}
if stmt == nil {
dri := exec.Driver()
sql_ = build(dri, fields, whereFields)
sql_ = dri.Prepare(sql_)
sqlPrinter.Print(false, sql_)
stmt, err = t.cache.SetStmt(exec, id, sql_)
if err != nil {
return nil, err
}
} else {
sqlPrinter.Print(true, sql_)
}
return WrapStmt(STMT_NOPCLOSE, stmt, nil)
}
func (t *Table) StmtInsert(exec Executor, fields uint64) (Stmt, error) {
return t.Stmt(exec, INSERT, fields, 0, t.SQLInsert)
}
func (t *Table) StmtUpdate(exec Executor, fields, whereFields uint64) (Stmt, error) {
return t.Stmt(exec, UPDATE, fields, whereFields, t.SQLUpdate)
}
func (t *Table) StmtDelete(exec Executor, whereFields uint64) (Stmt, error) {
return t.Stmt(exec, DELETE, 0, whereFields, t.SQLDelete)
}
func (t *Table) StmtLimit(exec Executor, fields, whereFields uint64) (Stmt, error) {
stmt, err := t.Stmt(exec, LIMIT, fields, whereFields, t.SQLLimit)
return stmt, err
}
func (t *Table) StmtOne(exec Executor, fields, whereFields uint64) (Stmt, error) {
return t.Stmt(exec, ONE, fields, whereFields, t.SQLOne)
}
func (t *Table) StmtAll(exec Executor, fields, whereFields uint64) (Stmt, error) {
return t.Stmt(exec, ALL, fields, whereFields, t.SQLAll)
}
func (t *Table) StmtCount(exec Executor, whereFields uint64) (Stmt, error) {
return t.Stmt(exec, COUNT, 0, whereFields, t.SQLCount)
}
func (t *Table) StmtIncrBy(exec Executor, fields, whereFields uint64) (Stmt, error) {
return t.Stmt(exec, INCRBY, fields, whereFields, t.SQLIncrBy)
}
func (t *Table) StmtExists(exec Executor, field, whereFields uint64) (Stmt, error) {
return t.Stmt(exec, EXISTS, field, whereFields, t.SQLExists)
}
func (t *Table) Prepare(exec Executor, sqlType SQLType, fields, whereFields uint64, build SQLBuilder) (Stmt, error) {
id := FieldsIdentity(sqlType, t.NumFields, fields, whereFields)
sql_, stmt, err := t.cache.PrepareSQL(exec, id)
if err != nil {
return nil, err
}
if stmt == nil {
dri := exec.Driver()
sql_ = build(dri, fields, whereFields)
sql_ = dri.Prepare(sql_)
t.cache.SetSQL(id, sql_)
sqlPrinter.Print(false, sql_)
stmt, err = exec.Prepare(sql_)
} else {
sqlPrinter.Print(true, sql_)
}
return WrapStmt(STMT_CLOSEABLE, stmt, err)
}
func (t *Table) PrepareInsert(exec Executor, fields uint64) (Stmt, error) {
return t.Prepare(exec, INSERT, fields, 0, t.SQLInsert)
}
func (t *Table) PrepareUpdate(exec Executor, fields, whereFields uint64) (Stmt, error) {
return t.Prepare(exec, UPDATE, fields, whereFields, t.SQLUpdate)
}
func (t *Table) PrepareDelete(exec Executor, whereFields uint64) (Stmt, error) {
return t.Prepare(exec, DELETE, 0, whereFields, t.SQLDelete)
}
func (t *Table) PrepareLimit(exec Executor, fields, whereFields uint64) (Stmt, error) {
return t.Prepare(exec, LIMIT, fields, whereFields, t.SQLLimit)
}
func (t *Table) PrepareOne(exec Executor, fields, whereFields uint64) (Stmt, error) {
return t.Prepare(exec, ONE, fields, whereFields, t.SQLOne)
}
func (t *Table) PrepareAll(exec Executor, fields, whereFields uint64) (Stmt, error) {
return t.Prepare(exec, ALL, fields, whereFields, t.SQLAll)
}
func (t *Table) PrepareCount(exec Executor, whereFields uint64) (Stmt, error) {
return t.Prepare(exec, COUNT, 0, whereFields, t.SQLCount)
}
func (t *Table) PrepareIncrBy(exec Executor, fields, whereFields uint64) (Stmt, error) {
return t.Prepare(exec, INCRBY, fields, whereFields, t.SQLIncrBy)
}
func (t *Table) PrepareExists(exec Executor, field, whereFields uint64) (Stmt, error) {
return t.Prepare(exec, EXISTS, field, whereFields, t.SQLExists)
}
// InsertSQL create insert sql for given fields
func (t *Table) SQLInsert(_ Driver, fields, _ uint64) string {
cols := t.Cols(fields)
return fmt.Sprintf("INSERT INTO %s(%s) VALUES(%s)",
t.Name,
cols.String(),
cols.OnlyParam())
}
// UpdateSQL create update sql for given fields
func (t *Table) SQLUpdate(_ Driver, fields, whereFields uint64) string {
return fmt.Sprintf("UPDATE %s SET %s %s",
t.Name,
t.Cols(fields).Paramed(),
t.Where(whereFields))
}
// DeleteSQL create delete sql for given fields
func (t *Table) SQLDelete(_ Driver, _, whereFields uint64) string {
return fmt.Sprintf("DELETE FROM %s %s", t.Name, t.Where(whereFields))
}
// LimitSQL create select sql for given fields
func (t *Table) SQLLimit(driver Driver, fields, whereFields uint64) string {
return fmt.Sprintf("SELECT %s FROM %s %s "+driver.SQLLimit(),
t.Cols(fields),
t.Name,
t.Where(whereFields))
}
// LimitSQL create select sql for given fields
func (t *Table) SQLOne(_ Driver, fields, whereFields uint64) string {
return fmt.Sprintf("SELECT %s FROM %s %s LIMIT 1",
t.Cols(fields),
t.Name,
t.Where(whereFields))
}
// AllSQL create select sql for given fields
func (t *Table) SQLAll(_ Driver, fields, whereFields uint64) string {
return fmt.Sprintf("SELECT %s FROM %s %s",
t.Cols(fields),
t.Name,
t.Where(whereFields))
}
// SQLForCount create select count sql
func (t *Table) SQLCount(_ Driver, _, whereFields uint64) string {
return fmt.Sprintf("SELECT COUNT(*) FROM %s %s",
t.Name,
t.Where(whereFields))
}
// SQLIncrBy create sql for increase/decrease field value
func (t *Table) SQLIncrBy(_ Driver, fields, whereFields uint64) string {
return fmt.Sprintf("UPDATE %s SET %s %s",
t.Name,
t.Cols(fields).IncrParamed(),
t.Where(whereFields),
)
}
// SQLExists create sql for checking whether model exists
func (t *Table) SQLExists(_ Driver, field, whereFields uint64) string {
col := t.Col(field)
return fmt.Sprintf("SELECT EXISTS(SELECT %s FROM %s %s) FROM DUAL",
col,
t.Name,
t.Where(whereFields),
)
}
// Where create where clause for given fields, the 'WHERE' word is included
func (t *Table) Where(fields uint64) string {
cols := t.Cols(fields)
if cols.Length() == 0 {
return ""
}
return "WHERE " + cols.Join("=?", " AND ")
}
// TabWhere is slimilar with Where, but prepend a table name for each column
func (t *Table) TabWhere(fields uint64) string {
cols := t.TabCols(fields)
if cols.Length() != 0 {
return ""
}
return "WHERE " + cols.Join("=?", " AND ")
}
// Cols return column names for given fields
// if fields is only one, return single column
// else return column slice
func (t *Table) Cols(fields uint64) Cols {
return t.colsByType(_COLS, fields)
}
// Col return column name of field
func (t *Table) Col(field uint64) string {
return t.Cols(field).String()
}
// TabCols return column names for given fields with type's table name as prefix
// like table.column
func (t *Table) TabCols(fields uint64) Cols {
return t.colsByType(_TAB_COLS, fields)
}
// Col return column name of field
func (t *Table) TabCol(field uint64) string {
return t.TabCols(field).String()
}
const (
_COLS = iota + 1<<(2*MAX_NUMFIELDS)
_TAB_COLS
)
func (t *Table) colsByType(typ, fields uint64) Cols {
cols := t.colsCache[typ|fields]
if cols == nil {
cols = t.cols(fields, "")
t.colsCache[typ|fields] = cols
}
return cols
}
// cols get fields names, each field prepend a prefix string
// if fields count is 0, type emptyCols was returned
// if fields count is 1, type singleCols was returned
// otherwise, type cols was returned
func (t *Table) cols(fields uint64, prefix string) Cols {
fieldNames := t.columns
if colCount := NumFields(fields); colCount > 1 {
names := make([]string, colCount)
var index int
for i, l := uint64(0), uint64(len(fieldNames)); i < l; i++ {
if (1<<i)&fields != 0 {
names[index] = prefix + fieldNames[i]
index++
}
}
return &MultipleCols{Cols: names}
} else if colCount == 1 {
for i, l := uint64(0), uint64(len(fieldNames)); i < l; i++ {
if (1<<i)&fields != 0 {
return SingleCol(prefix + fieldNames[i])
}
}
}
return _emptyCols
}
// parseModel will first use field tag as column name, the tag key is 'column',
// if no tag specified, use field name's camel_case, disable a field or model
// by set '-' as field tag value
func parseModel(v Model, db *DB) *Table {
var nocache bool
if nc, is := v.(Nocacher); is {
nocache = nc.Nocache()
}
if c, is := v.(Columner); is {
return newTable(v.Table(), c.Columns(), nocache)
}
typ := reflect.TypeOf(v)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
num := typ.NumField()
cols := make([]string, 0)
for i := 0; i < num; i++ {
field := typ.Field(i)
col := utils.ToSnakeCase(field.Name)
b, err := strconv.ParseBool(field.Tag.Get("nocache"))
if err == nil {
nocache = b
}
if nocache {
break
}
if !field.Anonymous ||
field.Type.Kind() != reflect.Struct {
colTag := field.Tag.Get("column")
if colTag == "-" {
continue
}
if colTag != "" {
col = colTag
}
cols = append(cols, col)
}
}
return newTable(
v.Table(),
utils.TruncCapToLen(cols),
nocache,
)
}
// newTable create Table for a Model with the table name and columns, if nocache,
// it will not allocate cache memory
func newTable(table string, cols []string, nocache bool) *Table {
if len(cols) > MAX_NUMFIELDS {
panic(fmt.Sprint("can't register model with fields count over ", MAX_NUMFIELDS))
}
t := &Table{
NumFields: uint64(len(cols)),
Name: table,
}
if !nocache {
t.prefix = table + "."
t.columns = cols
t.cache = newCache()
t.colsCache = make(map[uint64]Cols)
}
return t
}