forked from uadmin/uadmin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
1593 lines (1446 loc) · 44.9 KB
/
db.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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package uadmin
import (
"database/sql"
"fmt"
"os"
"reflect"
"strconv"
"strings"
"gorm.io/gorm"
//_ "github.com/jinzhu/gorm/dialects/mssql"
// Enable MYSQL
"gorm.io/driver/mysql"
"gorm.io/gorm/logger"
// Enable PostgreSQL
"gorm.io/driver/postgres"
"encoding/json"
"io/ioutil"
"net/http"
"time"
// Enable SQLLite
"github.com/PesTospertnyj/uadmin/colors"
"gorm.io/driver/sqlite"
"github.com/thlib/go-timezone-local/tzlocal"
)
var db *gorm.DB
var sqlDialect = map[string]map[string]string{
"mysql": {
"createM2MTable": "CREATE TABLE `{TABLE1}_{TABLE2}` (`table1_id` int(10) unsigned NOT NULL, `table2_id` int(10) unsigned NOT NULL, PRIMARY KEY (`table1_id`,`table2_id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
"selectM2M": "SELECT `table2_id` FROM `{TABLE1}_{TABLE2}` WHERE table1_id=?;",
"deleteM2M": "DELETE FROM `{TABLE1}_{TABLE2}` WHERE `table1_id`=?;",
"insertM2M": "INSERT INTO `{TABLE1}_{TABLE2}` VALUES (?, ?);",
},
"postgres": {
"createM2MTable": `CREATE TABLE "{TABLE1}_{TABLE2}" ("table1_id" BIGINT NOT NULL, "table2_id" BIGINT NOT NULL, PRIMARY KEY ("table1_id","table2_id"))`,
"selectM2M": `SELECT "table2_id" FROM "{TABLE1}_{TABLE2}" WHERE table1_id=?;`,
"deleteM2M": `DELETE FROM "{TABLE1}_{TABLE2}" WHERE "table1_id"=?;`,
"insertM2M": `INSERT INTO "{TABLE1}_{TABLE2}" VALUES (?, ?);`,
},
"sqlite": {
//"createM2MTable": "CREATE TABLE `{TABLE1}_{TABLE2}` (`{TABLE1}_id` INTEGER NOT NULL,`{TABLE2}_id` INTEGER NOT NULL, PRIMARY KEY(`{TABLE1}_id`,`{TABLE2}_id`));",
"createM2MTable": "CREATE TABLE `{TABLE1}_{TABLE2}` (`table1_id` INTEGER NOT NULL,`table2_id` INTEGER NOT NULL, PRIMARY KEY(`table1_id`,`table2_id`));",
"selectM2M": "SELECT `table2_id` FROM `{TABLE1}_{TABLE2}` WHERE table1_id=?;",
"deleteM2M": "DELETE FROM `{TABLE1}_{TABLE2}` WHERE `table1_id`=?;",
"insertM2M": "INSERT INTO `{TABLE1}_{TABLE2}` VALUES (?, ?);",
},
}
// Database is the active Database settings
var Database *DBSettings
var dbOK = false
// DBSettings !
type DBSettings struct {
Type string `json:"type"` // sqlite, mysql, postgres
Name string `json:"name"` // File/DB name
User string `json:"user"`
Password string `json:"password"`
Host string `json:"host"`
Port int `json:"port"`
Timezone string `json:"timezone"`
}
// initializeDB opens the connection the DB
func initializeDB(a ...interface{}) {
// Open the connection the the DB
db = GetDB()
// Migrate schema
for i, model := range a {
Trail(INFO, "Initializing DB: [%s%d/%d%s]", colors.FGGreenB, i+1, len(a), colors.FGNormal)
err := db.AutoMigrate(model)
if err != nil {
Trail(ERROR, "Unable to migrate schema of %s. %s", reflect.TypeOf(model).Name(), err)
}
err = customMigration(model)
if err != nil {
Trail(ERROR, "Unable to custom migrate schema of %s. %s", reflect.TypeOf(model).Name(), err)
}
}
Trail(OK, "Initializing DB: [%s%d/%d%s]", colors.FGGreenB, len(a), len(a), colors.FGNormal)
db.AllowGlobalUpdate = true
}
func customMigration(a interface{}) (err error) {
t := reflect.TypeOf(a)
for i := 0; i < t.NumField(); i++ {
// Check if there is any m2m fields
if t.Field(i).Type.Kind() == reflect.Slice && t.Field(i).Type.Elem().Kind() == reflect.Struct {
table1 := strings.ToLower(t.Name())
table2 := strings.ToLower(t.Field(i).Type.Elem().Name())
//Check if the table is created for the m2m field
if !db.Migrator().HasTable(table1 + "_" + table2) {
sql := sqlDialect[Database.Type]["createM2MTable"]
sql = strings.Replace(sql, "{TABLE1}", table1, -1)
sql = strings.Replace(sql, "{TABLE2}", table2, -1)
err = db.Exec(sql).Error
if err != nil {
Trail(ERROR, "Unable to create M2M table. %s", err)
Trail(ERROR, sql)
return err
}
}
}
}
return err
}
// GetDB returns a pointer to the DB
func GetDB() *gorm.DB {
if db != nil {
return db
}
var err error
// Check if there is a database config file
if Database == nil {
buf, err := ioutil.ReadFile(".database")
if err == nil {
err = json.Unmarshal(buf, &Database)
if err != nil {
Trail(WARNING, ".database file is not a valid json file. %s", err)
}
}
// Get environment variables for db settings
if v := os.Getenv("UADMIN_DB_TYPE"); v != "" {
if Database == nil {
Database = &DBSettings{}
}
Database.Type = v
}
if v := os.Getenv("UADMIN_DB_HOST"); v != "" {
Database.Host = v
if Database == nil {
Database = &DBSettings{}
}
}
if v := os.Getenv("UADMIN_DB_PORT"); v != "" {
if Database == nil {
Database = &DBSettings{}
}
port, err := strconv.ParseInt(v, 10, 64)
if err == nil {
Database.Port = int(port)
} else {
Trail(WARNING, "Environment vaiable UADMIN_DB_PORT should be a number but got (%s)", v)
}
}
if v := os.Getenv("UADMIN_DB_NAME"); v != "" {
if Database == nil {
Database = &DBSettings{}
}
Database.Name = v
}
if v := os.Getenv("UADMIN_DB_USER"); v != "" {
if Database == nil {
Database = &DBSettings{}
}
Database.User = v
}
if v := os.Getenv("UADMIN_DB_PASSWORD"); v != "" {
if Database == nil {
Database = &DBSettings{}
}
Database.Password = v
}
}
if Database == nil {
Database = &DBSettings{
Type: "sqlite",
}
}
if strings.ToLower(Database.Type) == "sqlite" {
dbName := Database.Name
if dbName == "" {
dbName = "uadmin.db"
}
db, err = gorm.Open(sqlite.Open(dbName), &gorm.Config{
Logger: func() logger.Interface {
if DebugDB {
return logger.Default.LogMode(logger.Info)
}
return logger.Default.LogMode(logger.Silent)
}(),
})
} else if strings.ToLower(Database.Type) == "mysql" {
if Database.Host == "" || Database.Host == "localhost" {
Database.Host = "127.0.0.1"
}
if Database.Port == 0 {
Database.Port = 3306
}
if Database.User == "" {
Database.User = "root"
}
credential := Database.User
if Database.Password != "" {
credential = fmt.Sprintf("%s:%s", Database.User, Database.Password)
}
tz := "Local"
if Database.Timezone != "" {
tz = Database.Timezone
}
dsn := fmt.Sprintf("%s@(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=%s",
credential,
Database.Host,
Database.Port,
Database.Name,
tz,
)
db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
Logger: func() logger.Interface {
if DebugDB {
return logger.Default.LogMode(logger.Info)
}
return logger.Default.LogMode(logger.Silent)
}(),
DisableForeignKeyConstraintWhenMigrating: true,
})
// Check if the error is DB doesn't exist and create it
if err != nil && err.Error() == "Error 1049: Unknown database '"+Database.Name+"'" {
err = createDB()
if err == nil {
db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
Logger: func() logger.Interface {
if DebugDB {
return logger.Default.LogMode(logger.Info)
}
return logger.Default.LogMode(logger.Silent)
}(),
DisableForeignKeyConstraintWhenMigrating: true,
})
}
}
// fail if we could not connect to DB
if err != nil {
Trail(ERROR, "Unable to connect to db. %s", err)
os.Exit(2)
}
// Temp solution for 0 foreign key
err = db.Exec("SET PERSIST FOREIGN_KEY_CHECKS=0;").Error
if err != nil {
err = db.Exec("SET GLOBAL FOREIGN_KEY_CHECKS=0;").Error
if err != nil {
err = db.Exec("SET FOREIGN_KEY_CHECKS=0;").Error
if err != nil {
Trail(ERROR, "Unable to run FOREIGN_KEY_CHECKS=0. %s", err)
}
}
}
} else if strings.ToLower(Database.Type) == "postgres" {
if Database.Host == "" || Database.Host == "localhost" {
Database.Host = "127.0.0.1"
}
if Database.Port == 0 {
Database.Port = 5432
}
if Database.User == "" {
Database.User = "postgres"
}
tz, _ := tzlocal.RuntimeTZ()
if Database.Timezone != "" {
tz = Database.Timezone
}
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d sslmode=disable TimeZone=%s",
Database.Host,
Database.User,
Database.Password,
Database.Name,
Database.Port,
tz,
)
db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{
Logger: func() logger.Interface {
if DebugDB {
return logger.Default.LogMode(logger.Info)
}
return logger.Default.LogMode(logger.Silent)
}(),
DisableForeignKeyConstraintWhenMigrating: true,
})
if err != nil && strings.HasSuffix(err.Error(), "server error (FATAL: database \""+Database.Name+"\" does not exist (SQLSTATE 3D000))") {
err = createDB()
if err == nil {
db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{
Logger: func() logger.Interface {
if DebugDB {
return logger.Default.LogMode(logger.Info)
}
return logger.Default.LogMode(logger.Silent)
}(),
DisableForeignKeyConstraintWhenMigrating: true,
})
}
}
// fail if we could not connect to DB
if err != nil {
Trail(ERROR, "Unable to connect to db. %s", err)
os.Exit(2)
}
}
if err != nil {
Trail(ERROR, "unable to connect to DB. %s", err)
db.Error = fmt.Errorf("unable to connect to DB. %s", err)
}
return db
}
func createDB() error {
if Database.Type == "mysql" {
credential := Database.User
if Database.Password != "" {
credential = fmt.Sprintf("%s:%s", Database.User, Database.Password)
}
dsn := fmt.Sprintf("%s@(%s:%d)/?charset=utf8mb4&parseTime=True&loc=Local",
credential,
Database.Host,
Database.Port,
)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
Logger: func() logger.Interface {
if DebugDB {
return logger.Default.LogMode(logger.Info)
}
return logger.Default.LogMode(logger.Silent)
}(),
})
if err != nil {
return err
}
Trail(INFO, "Database doens't exist, creating a new database")
db = db.Exec("CREATE SCHEMA `" + Database.Name + "` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci")
if db.Error != nil {
return fmt.Errorf(db.Error.Error())
}
return nil
} else if Database.Type == "postgres" {
if Database.Host == "" || Database.Host == "localhost" {
Database.Host = "127.0.0.1"
}
if Database.Port == 0 {
Database.Port = 5432
}
if Database.User == "" {
Database.User = "postgres"
}
tz, _ := tzlocal.RuntimeTZ()
if Database.Timezone != "" {
tz = Database.Timezone
}
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=postgres port=%d sslmode=disable TimeZone=%s",
Database.Host,
Database.User,
Database.Password,
Database.Port,
tz,
)
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
Logger: func() logger.Interface {
if DebugDB {
return logger.Default.LogMode(logger.Info)
}
return logger.Default.LogMode(logger.Silent)
}(),
DisableForeignKeyConstraintWhenMigrating: true,
})
if err != nil {
return err
}
Trail(INFO, "Database doens't exist, creating a new database")
db = db.Exec("CREATE DATABASE " + Database.Name + " WITH OWNER = " + Database.User + " ENCODING = 'UTF8' CONNECTION LIMIT = -1 IS_TEMPLATE = False;")
if db.Error != nil {
return fmt.Errorf(db.Error.Error())
}
return nil
}
return fmt.Errorf("CreateDB: Unknown database type " + Database.Type)
}
// ClearDB clears the db object
func ClearDB() {
db = nil
}
// All fetches all object in the database
func All(a interface{}) (err error) {
TimeMetric("uadmin/db/duration", 1000, func() {
err = db.Find(a).Error
for fmt.Sprint(err) == "database is locked" {
time.Sleep(time.Millisecond * 100)
err = db.Find(a).Error
}
})
if err != nil {
Trail(ERROR, "DB error in All(%v). %s", getModelName(a), err.Error())
return err
}
decryptArray(a)
return nil
}
// Save saves the object in the database
func Save(a interface{}) (err error) {
encryptRecord(a)
TimeMetric("uadmin/db/duration", 1000, func() {
err = db.Save(a).Error
for fmt.Sprint(err) == "database is locked" {
time.Sleep(time.Millisecond * 100)
err = db.Save(a).Error
}
})
if err != nil {
Trail(ERROR, "DB error in Save(%v). %s", getModelName(a), err.Error())
return err
}
err = customSave(a)
if err != nil {
Trail(ERROR, "DB error in customSave(%v). %s", getModelName(a), err.Error())
return err
}
return nil
}
func customSave(m interface{}) (err error) {
a := m
t := reflect.TypeOf(a)
if t.Kind() == reflect.Ptr {
a = reflect.ValueOf(m).Elem().Interface()
t = reflect.TypeOf(a)
}
value := reflect.ValueOf(a)
for i := 0; i < t.NumField(); i++ {
// Check if there is any m2m fields
if t.Field(i).Type.Kind() == reflect.Slice && t.Field(i).Type.Elem().Kind() == reflect.Struct {
table1 := strings.ToLower(t.Name())
table2 := strings.ToLower(t.Field(i).Type.Elem().Name())
// Delete existing records
sql := sqlDialect[Database.Type]["deleteM2M"]
sql = strings.Replace(sql, "{TABLE1}", table1, -1)
sql = strings.Replace(sql, "{TABLE2}", table2, -1)
TimeMetric("uadmin/db/duration", 1000, func() {
err = db.Exec(sql, GetID(value)).Error
for fmt.Sprint(err) == "database is locked" {
time.Sleep(time.Millisecond * 100)
err = db.Exec(sql, GetID(value)).Error
}
})
if err != nil {
Trail(ERROR, "Unable to delete m2m records. %s", err)
Trail(ERROR, sql)
return err
}
// Insert records
for index := 0; index < value.Field(i).Len(); index++ {
sql := sqlDialect[Database.Type]["insertM2M"]
sql = strings.Replace(sql, "{TABLE1}", table1, -1)
sql = strings.Replace(sql, "{TABLE2}", table2, -1)
TimeMetric("uadmin/db/duration", 1000, func() {
err = db.Exec(sql, GetID(value), GetID(value.Field(i).Index(index))).Error
for fmt.Sprint(err) == "database is locked" {
time.Sleep(time.Millisecond * 100)
err = db.Exec(sql, GetID(value), GetID(value.Field(i).Index(index))).Error
}
})
if err != nil {
Trail(ERROR, "Unable to insert m2m records. %s", err)
Trail(ERROR, sql)
return err
}
}
}
}
return nil
}
// Get fetches the first record from the database matching query and args
func Get(a interface{}, query interface{}, args ...interface{}) (err error) {
if val, ok := query.(string); ok {
query = fixQueryEnclosure(val)
}
TimeMetric("uadmin/db/duration", 1000, func() {
err = db.Where(query, args...).First(a).Error
for fmt.Sprint(err) == "database is locked" {
time.Sleep(time.Millisecond * 100)
err = db.Where(query, args...).First(a).Error
}
})
if err != nil {
if err.Error() != "record not found" {
Trail(ERROR, "DB error in Get(%s)-(%v). %s", getModelName(a), a, err.Error())
}
return err
}
err = customGet(a)
if err != nil {
Trail(ERROR, "DB error in customGet(%v). %s", getModelName(a), err.Error())
return err
}
decryptRecord(a)
return nil
}
// Get fetches the first record from the database matching query and args with sorting
func GetTable(table string, a interface{}, query interface{}, args ...interface{}) (err error) {
if val, ok := query.(string); ok {
query = fixQueryEnclosure(val)
}
TimeMetric("uadmin/db/duration", 1000, func() {
err = db.Table(table).Where(query, args...).First(a).Error
for fmt.Sprint(err) == "database is locked" {
time.Sleep(time.Millisecond * 100)
err = db.Table(table).Where(query, args...).First(a).Error
}
})
if err != nil {
if err.Error() != "record not found" {
Trail(ERROR, "DB error in GetSorted(%s)-(%v). %s", getModelName(a), a, err.Error())
}
return err
}
err = customGet(a)
if err != nil {
Trail(ERROR, "DB error in customGet(%v). %s", getModelName(a), err.Error())
return err
}
decryptRecord(a)
return nil
}
// Get fetches the first record from the database matching query and args with sorting
func GetSorted(order string, asc bool, a interface{}, query interface{}, args ...interface{}) (err error) {
if val, ok := query.(string); ok {
query = fixQueryEnclosure(val)
}
if order != "" {
orderby := " desc"
if asc {
orderby = " asc"
}
order = columnEnclosure() + order + columnEnclosure()
orderby += " "
order += orderby
} else {
order = "id desc"
}
TimeMetric("uadmin/db/duration", 1000, func() {
err = db.Where(query, args...).Order(order).First(a).Error
for fmt.Sprint(err) == "database is locked" {
time.Sleep(time.Millisecond * 100)
err = db.Where(query, args...).Order(order).First(a).Error
}
})
if err != nil {
if err.Error() != "record not found" {
Trail(ERROR, "DB error in GetSorted(%s)-(%v). %s", getModelName(a), a, err.Error())
}
return err
}
err = customGet(a)
if err != nil {
Trail(ERROR, "DB error in customGet(%v). %s", getModelName(a), err.Error())
return err
}
decryptRecord(a)
return nil
}
// Get fetches the first record from the database matching query and args with sorting
func GetSortedTable(table string, order string, asc bool, a interface{}, query interface{}, args ...interface{}) (err error) {
if val, ok := query.(string); ok {
query = fixQueryEnclosure(val)
}
if order != "" {
orderby := " desc"
if asc {
orderby = " asc"
}
order = columnEnclosure() + order + columnEnclosure()
orderby += " "
order += orderby
} else {
order = "id desc"
}
TimeMetric("uadmin/db/duration", 1000, func() {
err = db.Table(table).Where(query, args...).Order(order).First(a).Error
for fmt.Sprint(err) == "database is locked" {
time.Sleep(time.Millisecond * 100)
err = db.Table(table).Where(query, args...).Order(order).First(a).Error
}
})
if err != nil {
if err.Error() != "record not found" {
Trail(ERROR, "DB error in GetSorted(%s)-(%v). %s", getModelName(a), a, err.Error())
}
return err
}
err = customGet(a)
if err != nil {
Trail(ERROR, "DB error in customGet(%v). %s", getModelName(a), err.Error())
return err
}
decryptRecord(a)
return nil
}
// Get fetches the first record from the database matching query and args with sorting
func GetValueSorted(table string, column string, order string, asc bool, a interface{}, query interface{}, args ...interface{}) (err error) {
if val, ok := query.(string); ok {
query = fixQueryEnclosure(val)
}
if order != "" {
orderby := " desc"
if asc {
orderby = " asc"
}
order = columnEnclosure() + order + columnEnclosure()
orderby += " "
order += orderby
} else {
order = "id desc"
}
TimeMetric("uadmin/db/duration", 1000, func() {
err = db.Table(table).Where(query, args...).Order(order).Limit(1).Pluck(column, a).Error
for fmt.Sprint(err) == "database is locked" {
time.Sleep(time.Millisecond * 100)
err = db.Table(table).Where(query, args...).Order(order).Limit(1).Pluck(column, a).Error
}
})
if err != nil {
if err.Error() != "record not found" {
Trail(ERROR, "DB error in GetValueSorted(%s)-(%v). %s", getModelName(a), a, err.Error())
}
return err
}
return nil
}
// GetABTest is like Get function but implements AB testing for the results
func GetABTest(r *http.Request, a interface{}, query interface{}, args ...interface{}) (err error) {
if val, ok := query.(string); ok {
query = fixQueryEnclosure(val)
}
TimeMetric("uadmin/db/duration", 1000, func() {
Get(a, query, args...)
})
// Check if there are any active A/B tests for any field in this model
abt := getABT(r)
modelName := getModelName(a)
abTestsMutex.Lock()
for k, v := range modelABTests {
if strings.HasPrefix(k, modelName+"__") && strings.HasSuffix(k, "__"+fmt.Sprint(GetID(reflect.ValueOf(a)))) {
if len(v) != 0 {
index := abt % len(v)
fName := Schema[modelName].Fields[v[index].fname].Name
// TODO: Support more data types
switch Schema[modelName].Fields[v[index].fname].Type {
case cSTRING:
reflect.ValueOf(a).Elem().FieldByName(fName).SetString(v[index].v)
case cIMAGE:
reflect.ValueOf(a).Elem().FieldByName(fName).SetString(v[index].v)
}
// Increment impressions
v[index].imp++
modelABTests[k] = v
}
}
}
abTestsMutex.Unlock()
return nil
}
// GetStringer fetches the first record from the database matching query and args
// and get only fields tagged with `stringer` tag. If no field has `stringer` tag
// then it gets all the fields
func GetStringer(a interface{}, query interface{}, args ...interface{}) (err error) {
if val, ok := query.(string); ok {
query = fixQueryEnclosure(val)
}
stringers := []string{}
modelName := getModelName(a)
for _, f := range Schema[modelName].Fields {
if f.Stringer {
stringers = append(stringers, GetDB().Config.NamingStrategy.ColumnName("", f.Name))
}
}
TimeMetric("uadmin/db/duration", 1000, func() {
if len(stringers) == 0 {
err = db.Where(query, args...).First(a).Error
for fmt.Sprint(err) == "database is locked" {
time.Sleep(time.Millisecond * 100)
err = db.Where(query, args...).First(a).Error
}
} else {
err = db.Select(stringers).Where(query, args...).First(a).Error
for fmt.Sprint(err) == "database is locked" {
time.Sleep(time.Millisecond * 100)
err = db.Select(stringers).Where(query, args...).First(a).Error
}
}
})
if err != nil {
if err.Error() != "record not found" {
Trail(ERROR, "DB error in Get(%s)-(%v). %s", getModelName(a), a, err.Error())
}
return err
}
//err = customGet(a)
if err != nil {
Trail(ERROR, "DB error in customGet(%v). %s", getModelName(a), err.Error())
return err
}
decryptRecord(a)
return nil
}
// GetForm fetches the first record from the database matching query and args
// where it selects only visible fields in the form based on given schema
func GetForm(a interface{}, s *ModelSchema, query interface{}, args ...interface{}) (err error) {
if val, ok := query.(string); ok {
query = fixQueryEnclosure(val)
}
// get a list of visible fields
columnList := []string{}
m2mList := []string{}
for _, f := range s.Fields {
if !f.Hidden {
if f.Type == cM2M {
m2mList = append(m2mList, f.ColumnName)
} else if f.Type == cFK {
columnList = append(columnList, columnEnclosure()+f.ColumnName+"_id"+columnEnclosure())
// } else if f.IsMethod {
} else {
columnList = append(columnList, columnEnclosure()+f.ColumnName+columnEnclosure())
}
}
}
TimeMetric("uadmin/db/duration", 1000, func() {
err = db.Select(columnList).Where(query, args...).First(a).Error
for fmt.Sprint(err) == "database is locked" {
time.Sleep(time.Millisecond * 100)
err = db.Select(columnList).Where(query, args...).First(a).Error
}
})
if err != nil {
if err.Error() != "record not found" {
Trail(ERROR, "DB error in Get(%s)-(%v). %s", getModelName(a), a, err.Error())
}
return err
}
err = customGet(a, m2mList...)
if err != nil {
Trail(ERROR, "DB error in customGet(%v). %s", getModelName(a), err.Error())
return err
}
decryptRecord(a)
return nil
}
func customGet(m interface{}, m2m ...string) (err error) {
a := m
t := reflect.TypeOf(a)
var ignore bool
if t.Kind() == reflect.Ptr {
a = reflect.ValueOf(m).Elem().Interface()
t = reflect.TypeOf(a)
}
value := reflect.ValueOf(a)
for i := 0; i < t.NumField(); i++ {
ignore = false
if len(m2m) != 0 {
ignore = true
for _, fName := range m2m {
if fName == t.Field(i).Name {
ignore = false
break
}
}
}
if ignore {
continue
}
// Skip private fields
if t.Field(i).Anonymous || t.Field(i).Name[0:1] != strings.ToUpper(t.Field(i).Name[0:1]) {
continue
}
// Check if there is any m2m fields
if t.Field(i).Type.Kind() == reflect.Slice && t.Field(i).Type.Elem().Kind() == reflect.Struct {
table1 := strings.ToLower(t.Name())
table2 := strings.ToLower(t.Field(i).Type.Elem().Name())
sqlSelect := sqlDialect[Database.Type]["selectM2M"]
sqlSelect = strings.Replace(sqlSelect, "{TABLE1}", table1, -1)
sqlSelect = strings.Replace(sqlSelect, "{TABLE2}", table2, -1)
var rows *sql.Rows
rows, err = db.Raw(sqlSelect, GetID(value)).Rows()
if err != nil {
Trail(ERROR, "Unable to get m2m records. %s", err)
Trail(ERROR, sqlSelect)
return err
}
defer rows.Close()
var fkID uint
tmpDst := reflect.New(reflect.SliceOf(t.Field(i).Type.Elem())).Elem()
for rows.Next() {
rows.Scan(&fkID)
tempModel := reflect.New(t.Field(i).Type.Elem()).Elem()
Get(tempModel.Addr().Interface(), "id = ?", fkID)
tmpDst = reflect.Append(tmpDst, tempModel)
}
reflect.ValueOf(m).Elem().Field(i).Set(tmpDst)
}
}
return nil
}
// Filter fetches records from the database
func Filter(a interface{}, query interface{}, args ...interface{}) (err error) {
if val, ok := query.(string); ok {
query = fixQueryEnclosure(val)
}
TimeMetric("uadmin/db/duration", 1000, func() {
err = db.Where(query, args...).Find(a).Error
for fmt.Sprint(err) == "database is locked" {
time.Sleep(time.Millisecond * 100)
err = db.Where(query, args...).Find(a).Error
}
})
if err != nil {
Trail(ERROR, "DB error in Filter(%v). %s\n", getModelName(a), err.Error())
return err
}
decryptArray(a)
return nil
}
// Filter fetches records from the database
func FilterSorted(order string, asc bool, a interface{}, query interface{}, args ...interface{}) (err error) {
if val, ok := query.(string); ok {
query = fixQueryEnclosure(val)
}
if order != "" {
orderby := " desc"
if asc {
orderby = " asc"
}
order = columnEnclosure() + order + columnEnclosure()
orderby += " "
order += orderby
} else {
order = "id desc"
}
TimeMetric("uadmin/db/duration", 1000, func() {
err = db.Where(query, args...).Order(order).Find(a).Error
for fmt.Sprint(err) == "database is locked" {
time.Sleep(time.Millisecond * 100)
err = db.Where(query, args...).Order(order).Find(a).Error
}
})
if err != nil {
Trail(ERROR, "DB error in Filter(%v). %s\n", getModelName(a), err.Error())
return err
}
decryptArray(a)
return nil
}
// Filter fetches records from the database
func FilterTable(table string, a interface{}, query interface{}, args ...interface{}) (err error) {
if val, ok := query.(string); ok {
query = fixQueryEnclosure(val)
}
TimeMetric("uadmin/db/duration", 1000, func() {
err = db.Table(table).Where(query, args...).Find(a).Error
for fmt.Sprint(err) == "database is locked" {
time.Sleep(time.Millisecond * 100)
err = db.Table(table).Where(query, args...).Find(a).Error
}
})
if err != nil {
Trail(ERROR, "DB error in Filter(%v). %s\n", getModelName(a), err.Error())
return err
}
decryptArray(a)
return nil
}
// Filter fetches records from the database
func FilterSortedTable(table string, order string, asc bool, a interface{}, query interface{}, args ...interface{}) (err error) {
if val, ok := query.(string); ok {
query = fixQueryEnclosure(val)
}
if order != "" {
orderby := " desc"
if asc {
orderby = " asc"
}
order = columnEnclosure() + order + columnEnclosure()
orderby += " "
order += orderby
} else {
order = "id desc"
}
TimeMetric("uadmin/db/duration", 1000, func() {
err = db.Table(table).Where(query, args...).Order(order).Find(a).Error
for fmt.Sprint(err) == "database is locked" {
time.Sleep(time.Millisecond * 100)
err = db.Table(table).Where(query, args...).Order(order).Find(a).Error
}
})
if err != nil {
Trail(ERROR, "DB error in Filter(%v). %s\n", getModelName(a), err.Error())
return err
}
decryptArray(a)
return nil
}
// Filter fetches records from the database
func FilterSortedValue(table string, column string, order string, asc bool, a interface{}, query interface{}, args ...interface{}) (err error) {
if val, ok := query.(string); ok {
query = fixQueryEnclosure(val)
}
if order != "" {
orderby := " desc"
if asc {
orderby = " asc"
}
order = columnEnclosure() + order + columnEnclosure()
orderby += " "
order += orderby
} else {
order = "id desc"
}
TimeMetric("uadmin/db/duration", 1000, func() {
err = db.Table(table).Where(query, args...).Order(order).Pluck(column, a).Error
for fmt.Sprint(err) == "database is locked" {
time.Sleep(time.Millisecond * 100)