-
Notifications
You must be signed in to change notification settings - Fork 166
/
beedb.go
676 lines (629 loc) · 16.7 KB
/
beedb.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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
package beedb
import (
"database/sql"
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"time"
)
var OnDebug = false
var PluralizeTableNames = false
type Model struct {
Db *sql.DB
TableName string
LimitStr int
OffsetStr int
WhereStr string
ParamStr []interface{}
OrderStr string
ColumnStr string
PrimaryKey string
JoinStr string
GroupByStr string
HavingStr string
QuoteIdentifier string
ParamIdentifier string
ParamIteration int
}
/**
* Add New sql.DB in the future i will add ConnectionPool.Get()
*/
func New(db *sql.DB, options ...interface{}) (m Model) {
if len(options) == 0 {
m = Model{Db: db, ColumnStr: "*", PrimaryKey: "Id", QuoteIdentifier: "`", ParamIdentifier: "?", ParamIteration: 1}
} else if options[0] == "pg" {
m = Model{Db: db, ColumnStr: "id", PrimaryKey: "Id", QuoteIdentifier: "\"", ParamIdentifier: options[0].(string), ParamIteration: 1}
} else if options[0] == "mssql" {
m = Model{Db: db, ColumnStr: "id", PrimaryKey: "id", QuoteIdentifier: "", ParamIdentifier: options[0].(string), ParamIteration: 1}
}
return
}
func (orm *Model) SetTable(tbname string) *Model {
orm.TableName = tbname
return orm
}
func (orm *Model) SetPK(pk string) *Model {
orm.PrimaryKey = pk
return orm
}
func (orm *Model) Where(querystring interface{}, args ...interface{}) *Model {
switch querystring := querystring.(type) {
case string:
orm.WhereStr = querystring
case int:
if orm.ParamIdentifier == "pg" {
orm.WhereStr = fmt.Sprintf("%v%v%v = $%v", orm.QuoteIdentifier, orm.PrimaryKey, orm.QuoteIdentifier, orm.ParamIteration)
} else {
orm.WhereStr = fmt.Sprintf("%v%v%v = ?", orm.QuoteIdentifier, orm.PrimaryKey, orm.QuoteIdentifier)
orm.ParamIteration++
}
args = append(args, querystring)
}
orm.ParamStr = args
return orm
}
func (orm *Model) Limit(start int, size ...int) *Model {
orm.LimitStr = start
if len(size) > 0 {
orm.OffsetStr = size[0]
}
return orm
}
func (orm *Model) Offset(offset int) *Model {
orm.OffsetStr = offset
return orm
}
func (orm *Model) OrderBy(order string) *Model {
orm.OrderStr = order
return orm
}
func (orm *Model) Select(colums string) *Model {
orm.ColumnStr = colums
return orm
}
func (orm *Model) ScanPK(output interface{}) *Model {
if reflect.TypeOf(reflect.Indirect(reflect.ValueOf(output)).Interface()).Kind() == reflect.Slice {
sliceValue := reflect.Indirect(reflect.ValueOf(output))
sliceElementType := sliceValue.Type().Elem()
for i := 0; i < sliceElementType.NumField(); i++ {
bb := sliceElementType.Field(i).Tag
if bb.Get("beedb") == "PK" || reflect.ValueOf(bb).String() == "PK" {
orm.PrimaryKey = sliceElementType.Field(i).Name
}
}
} else {
tt := reflect.TypeOf(reflect.Indirect(reflect.ValueOf(output)).Interface())
for i := 0; i < tt.NumField(); i++ {
bb := tt.Field(i).Tag
if bb.Get("beedb") == "PK" || reflect.ValueOf(bb).String() == "PK" {
orm.PrimaryKey = tt.Field(i).Name
}
}
}
return orm
}
//The join_operator should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN
func (orm *Model) Join(join_operator, tablename, condition string) *Model {
if orm.JoinStr != "" {
orm.JoinStr = orm.JoinStr + fmt.Sprintf(" %v JOIN %v ON %v", join_operator, tablename, condition)
} else {
orm.JoinStr = fmt.Sprintf("%v JOIN %v ON %v", join_operator, tablename, condition)
}
return orm
}
func (orm *Model) GroupBy(keys string) *Model {
orm.GroupByStr = fmt.Sprintf("GROUP BY %v", keys)
return orm
}
func (orm *Model) Having(conditions string) *Model {
orm.HavingStr = fmt.Sprintf("HAVING %v", conditions)
return orm
}
func (orm *Model) Find(output interface{}) error {
orm.ScanPK(output)
var keys []string
results, err := scanStructIntoMap(output)
if err != nil {
return err
}
if orm.TableName == "" {
orm.TableName = getTableName(output)
}
// If we've already specific columns with Select(), use that
if orm.ColumnStr == "*" {
for key, _ := range results {
keys = append(keys, key)
}
orm.ColumnStr = strings.Join(keys, ", ")
}
orm.Limit(1)
resultsSlice, err := orm.FindMap()
if err != nil {
return err
}
if len(resultsSlice) == 0 {
return errors.New("No record found")
} else if len(resultsSlice) == 1 {
results := resultsSlice[0]
err := scanMapIntoStruct(output, results)
if err != nil {
return err
}
} else {
return errors.New("More than one record")
}
return nil
}
func (orm *Model) FindAll(rowsSlicePtr interface{}) error {
orm.ScanPK(rowsSlicePtr)
sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr))
if sliceValue.Kind() != reflect.Slice {
return errors.New("needs a pointer to a slice")
}
sliceElementType := sliceValue.Type().Elem()
st := reflect.New(sliceElementType)
var keys []string
results, err := scanStructIntoMap(st.Interface())
if err != nil {
return err
}
if orm.TableName == "" {
orm.TableName = getTableName(getTypeName(rowsSlicePtr))
}
// If we've already specific columns with Select(), use that
if orm.ColumnStr == "*" {
for key, _ := range results {
keys = append(keys, key)
}
orm.ColumnStr = strings.Join(keys, ", ")
}
resultsSlice, err := orm.FindMap()
if err != nil {
return err
}
for _, results := range resultsSlice {
newValue := reflect.New(sliceElementType)
err := scanMapIntoStruct(newValue.Interface(), results)
if err != nil {
return err
}
sliceValue.Set(reflect.Append(sliceValue, reflect.Indirect(reflect.ValueOf(newValue.Interface()))))
}
return nil
}
func (orm *Model) FindMap() (resultsSlice []map[string][]byte, err error) {
defer orm.InitModel()
sqls := orm.generateSql()
if OnDebug {
fmt.Println(sqls)
fmt.Println(orm)
}
s, err := orm.Db.Prepare(sqls)
if err != nil {
return nil, err
}
defer s.Close()
res, err := s.Query(orm.ParamStr...)
if err != nil {
return nil, err
}
defer res.Close()
fields, err := res.Columns()
if err != nil {
return nil, err
}
for res.Next() {
result := make(map[string][]byte)
var scanResultContainers []interface{}
for i := 0; i < len(fields); i++ {
var scanResultContainer interface{}
scanResultContainers = append(scanResultContainers, &scanResultContainer)
}
if err := res.Scan(scanResultContainers...); err != nil {
return nil, err
}
for ii, key := range fields {
rawValue := reflect.Indirect(reflect.ValueOf(scanResultContainers[ii]))
//if row is null then ignore
if rawValue.Interface() == nil {
continue
}
aa := reflect.TypeOf(rawValue.Interface())
vv := reflect.ValueOf(rawValue.Interface())
var str string
switch aa.Kind() {
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
str = strconv.FormatInt(vv.Int(), 10)
result[key] = []byte(str)
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
str = strconv.FormatUint(vv.Uint(), 10)
result[key] = []byte(str)
case reflect.Float32, reflect.Float64:
str = strconv.FormatFloat(vv.Float(), 'f', -1, 64)
result[key] = []byte(str)
case reflect.Slice:
if aa.Elem().Kind() == reflect.Uint8 {
result[key] = rawValue.Interface().([]byte)
break
}
case reflect.String:
str = vv.String()
result[key] = []byte(str)
//时间类型
case reflect.Struct:
str = rawValue.Interface().(time.Time).Format("2006-01-02 15:04:05.000 -0700")
result[key] = []byte(str)
case reflect.Bool:
if vv.Bool() {
result[key] = []byte("1")
} else {
result[key] = []byte("0")
}
}
}
resultsSlice = append(resultsSlice, result)
}
return resultsSlice, nil
}
func (orm *Model) generateSql() (a string) {
if orm.ParamIdentifier == "mssql" {
if orm.OffsetStr > 0 {
a = fmt.Sprintf("select ROW_NUMBER() OVER(order by %v )as rownum,%v from %v",
orm.PrimaryKey,
orm.ColumnStr,
orm.TableName)
if orm.WhereStr != "" {
a = fmt.Sprintf("%v WHERE %v", a, orm.WhereStr)
}
a = fmt.Sprintf("select * from (%v) "+
"as a where rownum between %v and %v",
a,
orm.OffsetStr,
orm.LimitStr)
} else if orm.LimitStr > 0 {
a = fmt.Sprintf("SELECT top %v %v FROM %v", orm.LimitStr, orm.ColumnStr, orm.TableName)
if orm.WhereStr != "" {
a = fmt.Sprintf("%v WHERE %v", a, orm.WhereStr)
}
if orm.GroupByStr != "" {
a = fmt.Sprintf("%v %v", a, orm.GroupByStr)
}
if orm.HavingStr != "" {
a = fmt.Sprintf("%v %v", a, orm.HavingStr)
}
if orm.OrderStr != "" {
a = fmt.Sprintf("%v ORDER BY %v", a, orm.OrderStr)
}
} else {
a = fmt.Sprintf("SELECT %v FROM %v", orm.ColumnStr, orm.TableName)
if orm.WhereStr != "" {
a = fmt.Sprintf("%v WHERE %v", a, orm.WhereStr)
}
if orm.GroupByStr != "" {
a = fmt.Sprintf("%v %v", a, orm.GroupByStr)
}
if orm.HavingStr != "" {
a = fmt.Sprintf("%v %v", a, orm.HavingStr)
}
if orm.OrderStr != "" {
a = fmt.Sprintf("%v ORDER BY %v", a, orm.OrderStr)
}
}
} else {
a = fmt.Sprintf("SELECT %v FROM %v", orm.ColumnStr, orm.TableName)
if orm.JoinStr != "" {
a = fmt.Sprintf("%v %v", a, orm.JoinStr)
}
if orm.WhereStr != "" {
a = fmt.Sprintf("%v WHERE %v", a, orm.WhereStr)
}
if orm.GroupByStr != "" {
a = fmt.Sprintf("%v %v", a, orm.GroupByStr)
}
if orm.HavingStr != "" {
a = fmt.Sprintf("%v %v", a, orm.HavingStr)
}
if orm.OrderStr != "" {
a = fmt.Sprintf("%v ORDER BY %v", a, orm.OrderStr)
}
if orm.OffsetStr > 0 {
a = fmt.Sprintf("%v LIMIT %v OFFSET %v", a, orm.LimitStr, orm.OffsetStr)
} else if orm.LimitStr > 0 {
a = fmt.Sprintf("%v LIMIT %v", a, orm.LimitStr)
}
}
return
}
//Execute sql
func (orm *Model) Exec(finalQueryString string, args ...interface{}) (sql.Result, error) {
rs, err := orm.Db.Prepare(finalQueryString)
if err != nil {
return nil, err
}
defer rs.Close()
res, err := rs.Exec(args...)
if err != nil {
return nil, err
}
return res, nil
}
//if the struct has PrimaryKey == 0 insert else update
func (orm *Model) Save(output interface{}) error {
orm.ScanPK(output)
results, err := scanStructIntoMap(output)
if err != nil {
return err
}
if orm.TableName == "" {
orm.TableName = getTableName(output)
}
id := results[orm.PrimaryKey]
delete(results, orm.PrimaryKey)
if id == nil {
return fmt.Errorf("Unable to save because primary key %q was not found in struct", orm.PrimaryKey)
}
if reflect.ValueOf(id).Int() == 0 {
structPtr := reflect.ValueOf(output)
structVal := structPtr.Elem()
structField := structVal.FieldByName(orm.PrimaryKey)
id, err := orm.Insert(results)
if err != nil {
return err
}
var v interface{}
x, err := strconv.Atoi(strconv.FormatInt(id, 10))
if err != nil {
return err
}
v = x
structField.Set(reflect.ValueOf(v))
return nil
} else {
var condition string
if orm.ParamIdentifier == "pg" {
condition = fmt.Sprintf("%v%v%v=$%v", orm.QuoteIdentifier, strings.ToLower(orm.PrimaryKey), orm.QuoteIdentifier, orm.ParamIteration)
} else {
condition = fmt.Sprintf("%v%v%v=?", orm.QuoteIdentifier, orm.PrimaryKey, orm.QuoteIdentifier)
}
orm.Where(condition, id)
_, err := orm.Update(results)
if err != nil {
return err
}
}
return nil
}
//inert one info
func (orm *Model) Insert(properties map[string]interface{}) (int64, error) {
defer orm.InitModel()
var keys []string
var placeholders []string
var args []interface{}
for key, val := range properties {
keys = append(keys, key)
if orm.ParamIdentifier == "pg" {
ds := fmt.Sprintf("$%d", orm.ParamIteration)
placeholders = append(placeholders, ds)
} else {
placeholders = append(placeholders, "?")
}
orm.ParamIteration++
args = append(args, val)
}
ss := fmt.Sprintf("%v,%v", orm.QuoteIdentifier, orm.QuoteIdentifier)
statement := fmt.Sprintf("INSERT INTO %v%v%v (%v%v%v) VALUES (%v)",
orm.QuoteIdentifier,
orm.TableName,
orm.QuoteIdentifier,
orm.QuoteIdentifier,
strings.Join(keys, ss),
orm.QuoteIdentifier,
strings.Join(placeholders, ", "))
if OnDebug {
fmt.Println(statement)
fmt.Println(orm)
}
if orm.ParamIdentifier == "pg" {
statement = fmt.Sprintf("%v RETURNING %v", statement, snakeCasedName(orm.PrimaryKey))
var id int64
orm.Db.QueryRow(statement, args...).Scan(&id)
return id, nil
} else {
res, err := orm.Exec(statement, args...)
if err != nil {
return -1, err
}
id, err := res.LastInsertId()
if err != nil {
return -1, err
}
return id, nil
}
return -1, nil
}
//insert batch info
func (orm *Model) InsertBatch(rows []map[string]interface{}) ([]int64, error) {
var ids []int64
tablename := orm.TableName
if len(rows) <= 0 {
return ids, nil
}
for i := 0; i < len(rows); i++ {
orm.TableName = tablename
id, err := orm.Insert(rows[i])
if err != nil {
return ids, err
}
ids = append(ids, id)
}
return ids, nil
}
// update info
func (orm *Model) Update(properties map[string]interface{}) (int64, error) {
defer orm.InitModel()
var updates []string
var args []interface{}
for key, val := range properties {
if orm.ParamIdentifier == "pg" {
ds := fmt.Sprintf("$%d", orm.ParamIteration)
updates = append(updates, fmt.Sprintf("%v%v%v = %v", orm.QuoteIdentifier, key, orm.QuoteIdentifier, ds))
} else {
updates = append(updates, fmt.Sprintf("%v%v%v = ?", orm.QuoteIdentifier, key, orm.QuoteIdentifier))
}
args = append(args, val)
orm.ParamIteration++
}
args = append(args, orm.ParamStr...)
if orm.ParamIdentifier == "pg" {
if n := len(orm.ParamStr); n > 0 {
for i := 1; i <= n; i++ {
orm.WhereStr = strings.Replace(orm.WhereStr, "$"+strconv.Itoa(i), "$"+strconv.Itoa(orm.ParamIteration), 1)
}
}
}
var condition string
if orm.WhereStr != "" {
condition = fmt.Sprintf("WHERE %v", orm.WhereStr)
} else {
condition = ""
}
statement := fmt.Sprintf("UPDATE %v%v%v SET %v %v",
orm.QuoteIdentifier,
orm.TableName,
orm.QuoteIdentifier,
strings.Join(updates, ", "),
condition)
if OnDebug {
fmt.Println(statement)
fmt.Println(orm)
}
res, err := orm.Exec(statement, args...)
if err != nil {
return -1, err
}
id, err := res.RowsAffected()
if err != nil {
return -1, err
}
return id, nil
}
func (orm *Model) Delete(output interface{}) (int64, error) {
defer orm.InitModel()
orm.ScanPK(output)
results, err := scanStructIntoMap(output)
if err != nil {
return 0, err
}
if orm.TableName == "" {
orm.TableName = getTableName(output)
}
id := results[strings.ToLower(orm.PrimaryKey)]
condition := fmt.Sprintf("%v%v%v='%v'", orm.QuoteIdentifier, strings.ToLower(orm.PrimaryKey), orm.QuoteIdentifier, id)
statement := fmt.Sprintf("DELETE FROM %v%v%v WHERE %v",
orm.QuoteIdentifier,
orm.TableName,
orm.QuoteIdentifier,
condition)
if OnDebug {
fmt.Println(statement)
fmt.Println(orm)
}
res, err := orm.Exec(statement)
if err != nil {
return -1, err
}
Affectid, err := res.RowsAffected()
if err != nil {
return -1, err
}
return Affectid, nil
}
func (orm *Model) DeleteAll(rowsSlicePtr interface{}) (int64, error) {
defer orm.InitModel()
orm.ScanPK(rowsSlicePtr)
if orm.TableName == "" {
//TODO: fix table name
orm.TableName = getTableName(getTypeName(rowsSlicePtr))
}
var ids []string
val := reflect.Indirect(reflect.ValueOf(rowsSlicePtr))
if val.Len() == 0 {
return 0, nil
}
for i := 0; i < val.Len(); i++ {
results, err := scanStructIntoMap(val.Index(i).Interface())
if err != nil {
return 0, err
}
id := results[strings.ToLower(orm.PrimaryKey)]
switch id.(type) {
case string:
ids = append(ids, id.(string))
case int, int64, int32:
str := strconv.Itoa(id.(int))
ids = append(ids, str)
}
}
condition := fmt.Sprintf("%v%v%v in ('%v')", orm.QuoteIdentifier, strings.ToLower(orm.PrimaryKey), orm.QuoteIdentifier, strings.Join(ids, "','"))
statement := fmt.Sprintf("DELETE FROM %v%v%v WHERE %v",
orm.QuoteIdentifier,
orm.TableName,
orm.QuoteIdentifier,
condition)
if OnDebug {
fmt.Println(statement)
fmt.Println(orm)
}
res, err := orm.Exec(statement)
if err != nil {
return -1, err
}
Affectid, err := res.RowsAffected()
if err != nil {
return -1, err
}
return Affectid, nil
}
func (orm *Model) DeleteRow() (int64, error) {
defer orm.InitModel()
var condition string
if orm.WhereStr != "" {
condition = fmt.Sprintf("WHERE %v", orm.WhereStr)
} else {
condition = ""
}
statement := fmt.Sprintf("DELETE FROM %v%v%v %v",
orm.QuoteIdentifier,
orm.TableName,
orm.QuoteIdentifier,
condition)
if OnDebug {
fmt.Println(statement)
fmt.Println(orm)
}
res, err := orm.Exec(statement, orm.ParamStr...)
if err != nil {
return -1, err
}
Affectid, err := res.RowsAffected()
if err != nil {
return -1, err
}
return Affectid, nil
}
func (orm *Model) InitModel() {
orm.TableName = ""
orm.LimitStr = 0
orm.OffsetStr = 0
orm.WhereStr = ""
orm.ParamStr = make([]interface{}, 0)
orm.OrderStr = ""
orm.ColumnStr = "*"
orm.PrimaryKey = "id"
orm.JoinStr = ""
orm.GroupByStr = ""
orm.HavingStr = ""
orm.ParamIteration = 1
}