forked from lunny/xorm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
engine.go
1071 lines (957 loc) · 27.8 KB
/
engine.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 xorm
import (
"bufio"
"bytes"
"database/sql"
"errors"
"fmt"
"io"
"os"
"reflect"
"strconv"
"strings"
"sync"
)
const (
POSTGRES = "postgres"
SQLITE = "sqlite3"
MYSQL = "mysql"
MYMYSQL = "mymysql"
MSSQL = "mssql"
ORACLE_OCI = "oci8"
QL = "ql"
)
// a dialect is a driver's wrapper
type dialect interface {
Init(DriverName, DataSourceName string) error
URI() *uri
DBType() string
SqlType(t *Column) string
SupportInsertMany() bool
QuoteStr() string
RollBackStr() string
DropTableSql(tableName string) string
AutoIncrStr() string
SupportEngine() bool
SupportCharset() bool
IndexOnTable() bool
IndexCheckSql(tableName, idxName string) (string, []interface{})
TableCheckSql(tableName string) (string, []interface{})
ColumnCheckSql(tableName, colName string) (string, []interface{})
GetColumns(tableName string) ([]string, map[string]*Column, error)
GetTables() ([]*Table, error)
GetIndexes(tableName string) (map[string]*Index, error)
}
type PK []interface{}
// Engine is the major struct of xorm, it means a database manager.
// Commonly, an application only need one engine
type Engine struct {
columnMapper IMapper
tableMapper IMapper
TagIdentifier string
DriverName string
DataSourceName string
dialect dialect
Tables map[reflect.Type]*Table
mutex *sync.RWMutex
ShowSQL bool
ShowErr bool
ShowDebug bool
ShowWarn bool
Pool IConnectPool
Filters []Filter
Logger io.Writer
Cacher Cacher
UseCache bool
}
func (engine *Engine) SetMapper(mapper IMapper) {
engine.SetTableMapper(mapper)
engine.SetColumnMapper(mapper)
}
func (engine *Engine) SetTableMapper(mapper IMapper) {
engine.tableMapper = mapper
}
func (engine *Engine) SetColumnMapper(mapper IMapper) {
engine.columnMapper = mapper
}
// If engine's database support batch insert records like
// "insert into user values (name, age), (name, age)".
// When the return is ture, then engine.Insert(&users) will
// generate batch sql and exeute.
func (engine *Engine) SupportInsertMany() bool {
return engine.dialect.SupportInsertMany()
}
// Engine's database use which charactor as quote.
// mysql, sqlite use ` and postgres use "
func (engine *Engine) QuoteStr() string {
return engine.dialect.QuoteStr()
}
// Use QuoteStr quote the string sql
func (engine *Engine) Quote(sql string) string {
return engine.dialect.QuoteStr() + sql + engine.dialect.QuoteStr()
}
// A simple wrapper to dialect's SqlType method
func (engine *Engine) SqlType(c *Column) string {
return engine.dialect.SqlType(c)
}
// Database's autoincrement statement
func (engine *Engine) AutoIncrStr() string {
return engine.dialect.AutoIncrStr()
}
// Set engine's pool, the pool default is Go's standard library's connection pool.
func (engine *Engine) SetPool(pool IConnectPool) error {
engine.Pool = pool
return engine.Pool.Init(engine)
}
// SetMaxConns is only available for go 1.2+
func (engine *Engine) SetMaxConns(conns int) {
engine.Pool.SetMaxConns(conns)
}
// SetMaxIdleConns
func (engine *Engine) SetMaxIdleConns(conns int) {
engine.Pool.SetMaxIdleConns(conns)
}
// SetDefaltCacher set the default cacher. Xorm's default not enable cacher.
func (engine *Engine) SetDefaultCacher(cacher Cacher) {
if cacher == nil {
engine.UseCache = false
} else {
engine.UseCache = true
engine.Cacher = cacher
}
}
// If you has set default cacher, and you want temporilly stop use cache,
// you can use NoCache()
func (engine *Engine) NoCache() *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.NoCache()
}
func (engine *Engine) NoCascade() *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.NoCascade()
}
// Set a table use a special cacher
func (engine *Engine) MapCacher(bean interface{}, cacher Cacher) {
v := rValue(bean)
engine.autoMapType(v)
engine.Tables[v.Type()].Cacher = cacher
}
// OpenDB provides a interface to operate database directly.
func (engine *Engine) OpenDB() (*sql.DB, error) {
return sql.Open(engine.DriverName, engine.DataSourceName)
}
// New a session
func (engine *Engine) NewSession() *Session {
session := &Session{Engine: engine}
session.Init()
return session
}
// Close the engine
func (engine *Engine) Close() error {
return engine.Pool.Close(engine)
}
// Ping tests if database is alive.
func (engine *Engine) Ping() error {
session := engine.NewSession()
defer session.Close()
engine.LogSQL("PING DATABASE", engine.DriverName)
return session.Ping()
}
// logging sql
func (engine *Engine) LogSQL(contents ...interface{}) {
if engine.ShowSQL {
io.WriteString(engine.Logger, fmt.Sprintln(contents...))
}
}
// logging error
func (engine *Engine) LogError(contents ...interface{}) {
if engine.ShowErr {
io.WriteString(engine.Logger, fmt.Sprintln(contents...))
}
}
// logging debug
func (engine *Engine) LogDebug(contents ...interface{}) {
if engine.ShowDebug {
io.WriteString(engine.Logger, fmt.Sprintln(contents...))
}
}
// logging warn
func (engine *Engine) LogWarn(contents ...interface{}) {
if engine.ShowWarn {
io.WriteString(engine.Logger, fmt.Sprintln(contents...))
}
}
// Sql method let's you manualy write raw sql and operate
// For example:
//
// engine.Sql("select * from user").Find(&users)
//
// This code will execute "select * from user" and set the records to users
//
func (engine *Engine) Sql(querystring string, args ...interface{}) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Sql(querystring, args...)
}
// Default if your struct has "created" or "updated" filed tag, the fields
// will automatically be filled with current time when Insert or Update
// invoked. Call NoAutoTime if you dont' want to fill automatically.
func (engine *Engine) NoAutoTime() *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.NoAutoTime()
}
// Retrieve all tables, columns, indexes' informations from database.
func (engine *Engine) DBMetas() ([]*Table, error) {
tables, err := engine.dialect.GetTables()
if err != nil {
return nil, err
}
for _, table := range tables {
colSeq, cols, err := engine.dialect.GetColumns(table.Name)
if err != nil {
return nil, err
}
table.Columns = cols
table.ColumnsSeq = colSeq
indexes, err := engine.dialect.GetIndexes(table.Name)
if err != nil {
return nil, err
}
table.Indexes = indexes
for _, index := range indexes {
for _, name := range index.Cols {
if col, ok := table.Columns[name]; ok {
col.Indexes[index.Name] = true
} else {
return nil, fmt.Errorf("Unknown col "+name+" in indexes %v", table.Columns)
}
}
}
}
return tables, nil
}
// use cascade or not
func (engine *Engine) Cascade(trueOrFalse ...bool) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Cascade(trueOrFalse...)
}
// Where method provide a condition query
func (engine *Engine) Where(querystring string, args ...interface{}) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Where(querystring, args...)
}
// Id mehtod provoide a condition as (id) = ?
func (engine *Engine) Id(id interface{}) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Id(id)
}
// Apply before Processor, affected bean is passed to closure arg
func (engine *Engine) Before(closures func(interface{})) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Before(closures)
}
// Apply after insert Processor, affected bean is passed to closure arg
func (engine *Engine) After(closures func(interface{})) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.After(closures)
}
// set charset when create table, only support mysql now
func (engine *Engine) Charset(charset string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Charset(charset)
}
// set store engine when create table, only support mysql now
func (engine *Engine) StoreEngine(storeEngine string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.StoreEngine(storeEngine)
}
// use for distinct columns. Caution: when you are using cache,
// distinct will not be cached because cache system need id,
// but distinct will not provide id
func (engine *Engine) Distinct(columns ...string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Distinct(columns...)
}
// only use the paramters as select or update columns
func (engine *Engine) Cols(columns ...string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Cols(columns...)
}
func (engine *Engine) AllCols() *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.AllCols()
}
func (engine *Engine) MustCols(columns ...string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.MustCols(columns...)
}
// Xorm automatically retrieve condition according struct, but
// if struct has bool field, it will ignore them. So use UseBool
// to tell system to do not ignore them.
// If no paramters, it will use all the bool field of struct, or
// it will use paramters's columns
func (engine *Engine) UseBool(columns ...string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.UseBool(columns...)
}
// Only not use the paramters as select or update columns
func (engine *Engine) Omit(columns ...string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Omit(columns...)
}
// This method will generate "column IN (?, ?)"
func (engine *Engine) In(column string, args ...interface{}) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.In(column, args...)
}
// Temporarily change the Get, Find, Update's table
func (engine *Engine) Table(tableNameOrBean interface{}) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Table(tableNameOrBean)
}
// This method will generate "LIMIT start, limit"
func (engine *Engine) Limit(limit int, start ...int) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Limit(limit, start...)
}
// Method Desc will generate "ORDER BY column1 DESC, column2 DESC"
// This will
func (engine *Engine) Desc(colNames ...string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Desc(colNames...)
}
// Method Asc will generate "ORDER BY column1 DESC, column2 Asc"
// This method can chainable use.
//
// engine.Desc("name").Asc("age").Find(&users)
// // SELECT * FROM user ORDER BY name DESC, age ASC
//
func (engine *Engine) Asc(colNames ...string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Asc(colNames...)
}
// Method OrderBy will generate "ORDER BY order"
func (engine *Engine) OrderBy(order string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.OrderBy(order)
}
// The join_operator should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN
func (engine *Engine) Join(join_operator, tablename, condition string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Join(join_operator, tablename, condition)
}
// Generate Group By statement
func (engine *Engine) GroupBy(keys string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.GroupBy(keys)
}
// Generate Having statement
func (engine *Engine) Having(conditions string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Having(conditions)
}
func (engine *Engine) autoMapType(v reflect.Value) *Table {
t := v.Type()
engine.mutex.RLock()
table, ok := engine.Tables[t]
engine.mutex.RUnlock()
if !ok {
table = engine.mapType(v)
engine.mutex.Lock()
engine.Tables[t] = table
engine.mutex.Unlock()
}
return table
}
func (engine *Engine) autoMap(bean interface{}) *Table {
v := rValue(bean)
return engine.autoMapType(v)
}
func (engine *Engine) newTable() *Table {
table := &Table{}
table.Indexes = make(map[string]*Index)
table.Columns = make(map[string]*Column)
table.ColumnsSeq = make([]string, 0)
table.Created = make(map[string]bool)
table.Cacher = engine.Cacher
return table
}
func addIndex(indexName string, table *Table, col *Column, indexType int) {
if index, ok := table.Indexes[indexName]; ok {
index.AddColumn(col.Name)
col.Indexes[index.Name] = true
} else {
index := NewIndex(indexName, indexType)
index.AddColumn(col.Name)
table.AddIndex(index)
col.Indexes[index.Name] = true
}
}
func (engine *Engine) mapType(v reflect.Value) *Table {
t := v.Type()
table := engine.newTable()
method := v.MethodByName("TableName")
if !method.IsValid() {
method = v.Addr().MethodByName("TableName")
}
if method.IsValid() {
params := []reflect.Value{}
results := method.Call(params)
if len(results) == 1 {
table.Name = results[0].Interface().(string)
}
}
if table.Name == "" {
table.Name = engine.tableMapper.Obj2Table(t.Name())
}
table.Type = t
var idFieldColName string
var err error
for i := 0; i < t.NumField(); i++ {
tag := t.Field(i).Tag
ormTagStr := tag.Get(engine.TagIdentifier)
var col *Column
fieldValue := v.Field(i)
fieldType := fieldValue.Type()
if ormTagStr != "" {
col = &Column{FieldName: t.Field(i).Name, Nullable: true, IsPrimaryKey: false,
IsAutoIncrement: false, MapType: TWOSIDES, Indexes: make(map[string]bool)}
tags := strings.Split(ormTagStr, " ")
if len(tags) > 0 {
if tags[0] == "-" {
continue
}
if (strings.ToUpper(tags[0]) == "EXTENDS") &&
(fieldType.Kind() == reflect.Struct) {
parentTable := engine.mapType(fieldValue)
for name, col := range parentTable.Columns {
col.FieldName = fmt.Sprintf("%v.%v", fieldType.Name(), col.FieldName)
table.Columns[strings.ToLower(name)] = col
table.ColumnsSeq = append(table.ColumnsSeq, name)
}
table.PrimaryKeys = parentTable.PrimaryKeys
continue
}
indexNames := make(map[string]int)
var isIndex, isUnique bool
var preKey string
for j, key := range tags {
k := strings.ToUpper(key)
switch {
case k == "<-":
col.MapType = ONLYFROMDB
case k == "->":
col.MapType = ONLYTODB
case k == "PK":
col.IsPrimaryKey = true
col.Nullable = false
case k == "NULL":
col.Nullable = (strings.ToUpper(tags[j-1]) != "NOT")
/*case strings.HasPrefix(k, "AUTOINCR(") && strings.HasSuffix(k, ")"):
col.IsAutoIncrement = true
autoStart := k[len("AUTOINCR")+1 : len(k)-1]
autoStartInt, err := strconv.Atoi(autoStart)
if err != nil {
engine.LogError(err)
}
col.AutoIncrStart = autoStartInt*/
case k == "AUTOINCR":
col.IsAutoIncrement = true
//col.AutoIncrStart = 1
case k == "DEFAULT":
col.Default = tags[j+1]
case k == "CREATED":
col.IsCreated = true
case k == "VERSION":
col.IsVersion = true
col.Default = "1"
case k == "UPDATED":
col.IsUpdated = true
case strings.HasPrefix(k, "INDEX(") && strings.HasSuffix(k, ")"):
indexName := k[len("INDEX")+1 : len(k)-1]
indexNames[indexName] = IndexType
case k == "INDEX":
isIndex = true
case strings.HasPrefix(k, "UNIQUE(") && strings.HasSuffix(k, ")"):
indexName := k[len("UNIQUE")+1 : len(k)-1]
indexNames[indexName] = UniqueType
case k == "UNIQUE":
isUnique = true
case k == "NOTNULL":
col.Nullable = false
case k == "NOT":
default:
if strings.HasPrefix(k, "'") && strings.HasSuffix(k, "'") {
if preKey != "DEFAULT" {
col.Name = key[1 : len(key)-1]
}
} else if strings.Contains(k, "(") && strings.HasSuffix(k, ")") {
fs := strings.Split(k, "(")
if _, ok := sqlTypes[fs[0]]; !ok {
preKey = k
continue
}
col.SQLType = SQLType{fs[0], 0, 0}
fs2 := strings.Split(fs[1][0:len(fs[1])-1], ",")
if len(fs2) == 2 {
col.Length, err = strconv.Atoi(fs2[0])
if err != nil {
engine.LogError(err)
}
col.Length2, err = strconv.Atoi(fs2[1])
if err != nil {
engine.LogError(err)
}
} else if len(fs2) == 1 {
col.Length, err = strconv.Atoi(fs2[0])
if err != nil {
engine.LogError(err)
}
}
} else {
if _, ok := sqlTypes[k]; ok {
col.SQLType = SQLType{k, 0, 0}
} else if preKey != "DEFAULT" {
col.Name = key
}
}
engine.SqlType(col)
}
preKey = k
}
if col.SQLType.Name == "" {
col.SQLType = Type2SQLType(fieldType)
}
if col.Length == 0 {
col.Length = col.SQLType.DefaultLength
}
if col.Length2 == 0 {
col.Length2 = col.SQLType.DefaultLength2
}
if col.Name == "" {
col.Name = engine.columnMapper.Obj2Table(t.Field(i).Name)
}
if isUnique {
indexNames[col.Name] = UniqueType
} else if isIndex {
indexNames[col.Name] = IndexType
}
for indexName, indexType := range indexNames {
addIndex(indexName, table, col, indexType)
}
}
} else {
sqlType := Type2SQLType(fieldType)
col = &Column{
Name: engine.columnMapper.Obj2Table(t.Field(i).Name),
FieldName: t.Field(i).Name,
SQLType: sqlType,
Length: sqlType.DefaultLength,
Length2: sqlType.DefaultLength2,
Nullable: true,
Default: "",
Indexes: make(map[string]bool),
IsPrimaryKey: false,
IsAutoIncrement: false,
MapType: TWOSIDES,
IsCreated: false,
IsUpdated: false,
IsCascade: false,
IsVersion: false,
DefaultIsEmpty: false,
}
}
if col.IsAutoIncrement {
col.Nullable = false
}
table.AddColumn(col)
if fieldType.Kind() == reflect.Int64 && (col.FieldName == "Id" || strings.HasSuffix(col.FieldName, ".Id")) {
idFieldColName = col.Name
}
}
if idFieldColName != "" && len(table.PrimaryKeys) == 0 {
col := table.Columns[strings.ToLower(idFieldColName)]
col.IsPrimaryKey = true
col.IsAutoIncrement = true
col.Nullable = false
table.PrimaryKeys = append(table.PrimaryKeys, col.Name)
table.AutoIncrement = col.Name
}
return table
}
// Map a struct to a table
func (engine *Engine) mapping(beans ...interface{}) (e error) {
engine.mutex.Lock()
defer engine.mutex.Unlock()
for _, bean := range beans {
v := rValue(bean)
engine.Tables[v.Type()] = engine.mapType(v)
}
return
}
// If a table has any reocrd
func (engine *Engine) IsTableEmpty(bean interface{}) (bool, error) {
v := rValue(bean)
t := v.Type()
if t.Kind() != reflect.Struct {
return false, errors.New("bean should be a struct or struct's point")
}
engine.autoMapType(v)
session := engine.NewSession()
defer session.Close()
rows, err := session.Count(bean)
return rows > 0, err
}
// If a table is exist
func (engine *Engine) IsTableExist(bean interface{}) (bool, error) {
v := rValue(bean)
if v.Type().Kind() != reflect.Struct {
return false, errors.New("bean should be a struct or struct's point")
}
table := engine.autoMapType(v)
session := engine.NewSession()
defer session.Close()
has, err := session.isTableExist(table.Name)
return has, err
}
// create indexes
func (engine *Engine) CreateIndexes(bean interface{}) error {
session := engine.NewSession()
defer session.Close()
return session.CreateIndexes(bean)
}
// create uniques
func (engine *Engine) CreateUniques(bean interface{}) error {
session := engine.NewSession()
defer session.Close()
return session.CreateUniques(bean)
}
// If enabled cache, clear the cache bean
func (engine *Engine) ClearCacheBean(bean interface{}, id int64) error {
t := rType(bean)
if t.Kind() != reflect.Struct {
return errors.New("error params")
}
table := engine.autoMap(bean)
if table.Cacher != nil {
table.Cacher.ClearIds(table.Name)
table.Cacher.DelBean(table.Name, id)
}
return nil
}
// If enabled cache, clear some tables' cache
func (engine *Engine) ClearCache(beans ...interface{}) error {
for _, bean := range beans {
t := rType(bean)
if t.Kind() != reflect.Struct {
return errors.New("error params")
}
table := engine.autoMap(bean)
if table.Cacher != nil {
table.Cacher.ClearIds(table.Name)
table.Cacher.ClearBeans(table.Name)
}
}
return nil
}
// Sync the new struct changes to database, this method will automatically add
// table, column, index, unique. but will not delete or change anything.
// If you change some field, you should change the database manually.
func (engine *Engine) Sync(beans ...interface{}) error {
for _, bean := range beans {
table := engine.autoMap(bean)
s := engine.NewSession()
defer s.Close()
isExist, err := s.Table(bean).isTableExist(table.Name)
if err != nil {
return err
}
if !isExist {
err = engine.CreateTables(bean)
if err != nil {
return err
}
}
/*isEmpty, err := engine.IsEmptyTable(bean)
if err != nil {
return err
}*/
var isEmpty bool = false
if isEmpty {
err = engine.DropTables(bean)
if err != nil {
return err
}
err = engine.CreateTables(bean)
if err != nil {
return err
}
} else {
for _, col := range table.Columns {
session := engine.NewSession()
session.Statement.RefTable = table
defer session.Close()
isExist, err := session.isColumnExist(table.Name, col.Name)
if err != nil {
return err
}
if !isExist {
session := engine.NewSession()
session.Statement.RefTable = table
defer session.Close()
err = session.addColumn(col.Name)
if err != nil {
return err
}
}
}
for name, index := range table.Indexes {
session := engine.NewSession()
session.Statement.RefTable = table
defer session.Close()
if index.Type == UniqueType {
//isExist, err := session.isIndexExist(table.Name, name, true)
isExist, err := session.isIndexExist2(table.Name, index.Cols, true)
if err != nil {
return err
}
if !isExist {
session := engine.NewSession()
session.Statement.RefTable = table
defer session.Close()
err = session.addUnique(table.Name, name)
if err != nil {
return err
}
}
} else if index.Type == IndexType {
isExist, err := session.isIndexExist2(table.Name, index.Cols, false)
if err != nil {
return err
}
if !isExist {
session := engine.NewSession()
session.Statement.RefTable = table
defer session.Close()
err = session.addIndex(table.Name, name)
if err != nil {
return err
}
}
} else {
return errors.New("unknow index type")
}
}
}
}
return nil
}
func (engine *Engine) unMap(beans ...interface{}) (e error) {
engine.mutex.Lock()
defer engine.mutex.Unlock()
for _, bean := range beans {
t := rType(bean)
if _, ok := engine.Tables[t]; ok {
delete(engine.Tables, t)
}
}
return
}
// Drop all mapped table
func (engine *Engine) dropAll() error {
session := engine.NewSession()
defer session.Close()
err := session.Begin()
if err != nil {
return err
}
err = session.dropAll()
if err != nil {
session.Rollback()
return err
}
return session.Commit()
}
// CreateTables create tabls according bean
func (engine *Engine) CreateTables(beans ...interface{}) error {
session := engine.NewSession()
err := session.Begin()
defer session.Close()
if err != nil {
return err
}
for _, bean := range beans {
err = session.CreateTable(bean)
if err != nil {
session.Rollback()
return err
}
}
return session.Commit()
}
func (engine *Engine) DropTables(beans ...interface{}) error {
session := engine.NewSession()
err := session.Begin()
defer session.Close()
if err != nil {
return err
}
for _, bean := range beans {
err = session.DropTable(bean)
if err != nil {
session.Rollback()
return err
}
}
return session.Commit()
}
func (engine *Engine) createAll() error {
session := engine.NewSession()
defer session.Close()
return session.createAll()
}
// Exec raw sql
func (engine *Engine) Exec(sql string, args ...interface{}) (sql.Result, error) {
session := engine.NewSession()
defer session.Close()
return session.Exec(sql, args...)
}
// Exec a raw sql and return records as []map[string][]byte
func (engine *Engine) Query(sql string, paramStr ...interface{}) (resultsSlice []map[string][]byte, err error) {
session := engine.NewSession()
defer session.Close()
return session.Query(sql, paramStr...)
}
// Insert one or more records
func (engine *Engine) Insert(beans ...interface{}) (int64, error) {
session := engine.NewSession()
defer session.Close()
return session.Insert(beans...)
}
// Insert only one record
func (engine *Engine) InsertOne(bean interface{}) (int64, error) {
session := engine.NewSession()
defer session.Close()
return session.InsertOne(bean)
}
// Update records, bean's non-empty fields are updated contents,
// condiBean' non-empty filds are conditions
// CAUTION:
// 1.bool will defaultly be updated content nor conditions
// You should call UseBool if you have bool to use.
// 2.float32 & float64 may be not inexact as conditions
func (engine *Engine) Update(bean interface{}, condiBeans ...interface{}) (int64, error) {
session := engine.NewSession()
defer session.Close()
return session.Update(bean, condiBeans...)
}
// Delete records, bean's non-empty fields are conditions
func (engine *Engine) Delete(bean interface{}) (int64, error) {
session := engine.NewSession()
defer session.Close()
return session.Delete(bean)
}
// Get retrieve one record from table, bean's non-empty fields
// are conditions
func (engine *Engine) Get(bean interface{}) (bool, error) {
session := engine.NewSession()
defer session.Close()
return session.Get(bean)
}
// Find retrieve records from table, condiBeans's non-empty fields
// are conditions. beans could be []Struct, []*Struct, map[int64]Struct
// map[int64]*Struct
func (engine *Engine) Find(beans interface{}, condiBeans ...interface{}) error {
session := engine.NewSession()
defer session.Close()
return session.Find(beans, condiBeans...)
}
// Iterate record by record handle records from table, bean's non-empty fields
// are conditions.