Import upstream version 1.9.8, md5 f052277d9a9121d74defdb2c03035d22
Debian Janitor
4 years ago
0 | --- | |
1 | engines: | |
2 | gofmt: | |
3 | enabled: true | |
4 | govet: | |
5 | enabled: true | |
6 | golint: | |
7 | enabled: true | |
8 | ratings: | |
9 | paths: | |
10 | - "**.go" |
3 | 3 | |
4 | 4 | [![go report card](https://goreportcard.com/badge/github.com/jinzhu/gorm "go report card")](https://goreportcard.com/report/github.com/jinzhu/gorm) |
5 | 5 | [![wercker status](https://app.wercker.com/status/8596cace912c9947dd9c8542ecc8cb8b/s/master "wercker status")](https://app.wercker.com/project/byKey/8596cace912c9947dd9c8542ecc8cb8b) |
6 | [![codecov](https://codecov.io/gh/jinzhu/gorm/branch/master/graph/badge.svg)](https://codecov.io/gh/jinzhu/gorm) | |
6 | 7 | [![Join the chat at https://gitter.im/jinzhu/gorm](https://img.shields.io/gitter/room/jinzhu/gorm.svg)](https://gitter.im/jinzhu/gorm?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) |
7 | 8 | [![Open Collective Backer](https://opencollective.com/gorm/tiers/backer/badge.svg?label=backer&color=brightgreen "Open Collective Backer")](https://opencollective.com/gorm) |
8 | 9 | [![Open Collective Sponsor](https://opencollective.com/gorm/tiers/sponsor/badge.svg?label=sponsor&color=brightgreen "Open Collective Sponsor")](https://opencollective.com/gorm) |
9 | [![MIT license](http://img.shields.io/badge/license-MIT-brightgreen.svg)](http://opensource.org/licenses/MIT) | |
10 | [![MIT license](https://img.shields.io/badge/license-MIT-brightgreen.svg)](https://opensource.org/licenses/MIT) | |
10 | 11 | [![GoDoc](https://godoc.org/github.com/jinzhu/gorm?status.svg)](https://godoc.org/github.com/jinzhu/gorm) |
11 | 12 | |
12 | 13 | ## Overview |
26 | 27 | |
27 | 28 | ## Getting Started |
28 | 29 | |
29 | * GORM Guides [http://gorm.io](http://gorm.io) | |
30 | * GORM Guides [https://gorm.io](https://gorm.io) | |
30 | 31 | |
31 | 32 | ## Contributing |
32 | 33 | |
33 | [You can help to deliver a better GORM, check out things you can do](http://gorm.io/contribute.html) | |
34 | [You can help to deliver a better GORM, check out things you can do](https://gorm.io/contribute.html) | |
34 | 35 | |
35 | 36 | ## License |
36 | 37 |
266 | 266 | query = scope.DB() |
267 | 267 | ) |
268 | 268 | |
269 | if relationship.Kind == "many_to_many" { | |
269 | switch relationship.Kind { | |
270 | case "many_to_many": | |
270 | 271 | query = relationship.JoinTableHandler.JoinWith(relationship.JoinTableHandler, query, scope.Value) |
271 | } else if relationship.Kind == "has_many" || relationship.Kind == "has_one" { | |
272 | case "has_many", "has_one": | |
272 | 273 | primaryKeys := scope.getColumnAsArray(relationship.AssociationForeignFieldNames, scope.Value) |
273 | 274 | query = query.Where( |
274 | 275 | fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, relationship.ForeignDBNames), toQueryMarks(primaryKeys)), |
275 | 276 | toQueryValues(primaryKeys)..., |
276 | 277 | ) |
277 | } else if relationship.Kind == "belongs_to" { | |
278 | case "belongs_to": | |
278 | 279 | primaryKeys := scope.getColumnAsArray(relationship.ForeignFieldNames, scope.Value) |
279 | 280 | query = query.Where( |
280 | 281 | fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, relationship.AssociationForeignDBNames), toQueryMarks(primaryKeys)), |
366 | 367 | return association |
367 | 368 | } |
368 | 369 | |
370 | // setErr set error when the error is not nil. And return Association. | |
369 | 371 | func (association *Association) setErr(err error) *Association { |
370 | 372 | if err != nil { |
371 | 373 | association.Error = err |
0 | 0 | package gorm |
1 | 1 | |
2 | import "log" | |
2 | import "fmt" | |
3 | 3 | |
4 | 4 | // DefaultCallback default callbacks defined by gorm |
5 | 5 | var DefaultCallback = &Callback{} |
12 | 12 | // Field `rowQueries` contains callbacks will be call when querying object with Row, Rows... |
13 | 13 | // Field `processors` contains all callback processors, will be used to generate above callbacks in order |
14 | 14 | type Callback struct { |
15 | logger logger | |
15 | 16 | creates []*func(scope *Scope) |
16 | 17 | updates []*func(scope *Scope) |
17 | 18 | deletes []*func(scope *Scope) |
22 | 23 | |
23 | 24 | // CallbackProcessor contains callback informations |
24 | 25 | type CallbackProcessor struct { |
26 | logger logger | |
25 | 27 | name string // current callback's name |
26 | 28 | before string // register current callback before a callback |
27 | 29 | after string // register current callback after a callback |
32 | 34 | parent *Callback |
33 | 35 | } |
34 | 36 | |
35 | func (c *Callback) clone() *Callback { | |
37 | func (c *Callback) clone(logger logger) *Callback { | |
36 | 38 | return &Callback{ |
39 | logger: logger, | |
37 | 40 | creates: c.creates, |
38 | 41 | updates: c.updates, |
39 | 42 | deletes: c.deletes, |
52 | 55 | // scope.Err(errors.New("error")) |
53 | 56 | // }) |
54 | 57 | func (c *Callback) Create() *CallbackProcessor { |
55 | return &CallbackProcessor{kind: "create", parent: c} | |
58 | return &CallbackProcessor{logger: c.logger, kind: "create", parent: c} | |
56 | 59 | } |
57 | 60 | |
58 | 61 | // Update could be used to register callbacks for updating object, refer `Create` for usage |
59 | 62 | func (c *Callback) Update() *CallbackProcessor { |
60 | return &CallbackProcessor{kind: "update", parent: c} | |
63 | return &CallbackProcessor{logger: c.logger, kind: "update", parent: c} | |
61 | 64 | } |
62 | 65 | |
63 | 66 | // Delete could be used to register callbacks for deleting object, refer `Create` for usage |
64 | 67 | func (c *Callback) Delete() *CallbackProcessor { |
65 | return &CallbackProcessor{kind: "delete", parent: c} | |
68 | return &CallbackProcessor{logger: c.logger, kind: "delete", parent: c} | |
66 | 69 | } |
67 | 70 | |
68 | 71 | // Query could be used to register callbacks for querying objects with query methods like `Find`, `First`, `Related`, `Association`... |
69 | 72 | // Refer `Create` for usage |
70 | 73 | func (c *Callback) Query() *CallbackProcessor { |
71 | return &CallbackProcessor{kind: "query", parent: c} | |
74 | return &CallbackProcessor{logger: c.logger, kind: "query", parent: c} | |
72 | 75 | } |
73 | 76 | |
74 | 77 | // RowQuery could be used to register callbacks for querying objects with `Row`, `Rows`, refer `Create` for usage |
75 | 78 | func (c *Callback) RowQuery() *CallbackProcessor { |
76 | return &CallbackProcessor{kind: "row_query", parent: c} | |
79 | return &CallbackProcessor{logger: c.logger, kind: "row_query", parent: c} | |
77 | 80 | } |
78 | 81 | |
79 | 82 | // After insert a new callback after callback `callbackName`, refer `Callbacks.Create` |
92 | 95 | func (cp *CallbackProcessor) Register(callbackName string, callback func(scope *Scope)) { |
93 | 96 | if cp.kind == "row_query" { |
94 | 97 | if cp.before == "" && cp.after == "" && callbackName != "gorm:row_query" { |
95 | log.Printf("Registing RowQuery callback %v without specify order with Before(), After(), applying Before('gorm:row_query') by default for compatibility...\n", callbackName) | |
98 | cp.logger.Print(fmt.Sprintf("Registering RowQuery callback %v without specify order with Before(), After(), applying Before('gorm:row_query') by default for compatibility...\n", callbackName)) | |
96 | 99 | cp.before = "gorm:row_query" |
97 | 100 | } |
98 | 101 | } |
106 | 109 | // Remove a registered callback |
107 | 110 | // db.Callback().Create().Remove("gorm:update_time_stamp_when_create") |
108 | 111 | func (cp *CallbackProcessor) Remove(callbackName string) { |
109 | log.Printf("[info] removing callback `%v` from %v\n", callbackName, fileWithLineNum()) | |
112 | cp.logger.Print(fmt.Sprintf("[info] removing callback `%v` from %v\n", callbackName, fileWithLineNum())) | |
110 | 113 | cp.name = callbackName |
111 | 114 | cp.remove = true |
112 | 115 | cp.parent.processors = append(cp.parent.processors, cp) |
119 | 122 | // scope.SetColumn("Updated", now) |
120 | 123 | // }) |
121 | 124 | func (cp *CallbackProcessor) Replace(callbackName string, callback func(scope *Scope)) { |
122 | log.Printf("[info] replacing callback `%v` from %v\n", callbackName, fileWithLineNum()) | |
125 | cp.logger.Print(fmt.Sprintf("[info] replacing callback `%v` from %v\n", callbackName, fileWithLineNum())) | |
123 | 126 | cp.name = callbackName |
124 | 127 | cp.processor = &callback |
125 | 128 | cp.replace = true |
158 | 161 | for _, cp := range cps { |
159 | 162 | // show warning message the callback name already exists |
160 | 163 | if index := getRIndex(allNames, cp.name); index > -1 && !cp.replace && !cp.remove { |
161 | log.Printf("[warning] duplicated callback `%v` from %v\n", cp.name, fileWithLineNum()) | |
164 | cp.logger.Print(fmt.Sprintf("[warning] duplicated callback `%v` from %v\n", cp.name, fileWithLineNum())) | |
162 | 165 | } |
163 | 166 | allNames = append(allNames, cp.name) |
164 | 167 | } |
58 | 58 | |
59 | 59 | for _, field := range scope.Fields() { |
60 | 60 | if scope.changeableField(field) { |
61 | if field.IsNormal { | |
61 | if field.IsNormal && !field.IsIgnored { | |
62 | 62 | if field.IsBlank && field.HasDefaultValue { |
63 | 63 | blankColumnsWithDefaultValue = append(blankColumnsWithDefaultValue, scope.Quote(field.DBName)) |
64 | 64 | scope.InstanceSet("gorm:blank_columns_with_default_value", blankColumnsWithDefaultValue) |
82 | 82 | quotedTableName = scope.QuotedTableName() |
83 | 83 | primaryField = scope.PrimaryField() |
84 | 84 | extraOption string |
85 | insertModifier string | |
85 | 86 | ) |
86 | 87 | |
87 | 88 | if str, ok := scope.Get("gorm:insert_option"); ok { |
88 | 89 | extraOption = fmt.Sprint(str) |
90 | } | |
91 | if str, ok := scope.Get("gorm:insert_modifier"); ok { | |
92 | insertModifier = strings.ToUpper(fmt.Sprint(str)) | |
93 | if insertModifier == "INTO" { | |
94 | insertModifier = "" | |
95 | } | |
89 | 96 | } |
90 | 97 | |
91 | 98 | if primaryField != nil { |
96 | 103 | |
97 | 104 | if len(columns) == 0 { |
98 | 105 | scope.Raw(fmt.Sprintf( |
99 | "INSERT INTO %v %v%v%v", | |
106 | "INSERT %v INTO %v %v%v%v", | |
107 | addExtraSpaceIfExist(insertModifier), | |
100 | 108 | quotedTableName, |
101 | 109 | scope.Dialect().DefaultValueStr(), |
102 | 110 | addExtraSpaceIfExist(extraOption), |
104 | 112 | )) |
105 | 113 | } else { |
106 | 114 | scope.Raw(fmt.Sprintf( |
107 | "INSERT INTO %v (%v) VALUES (%v)%v%v", | |
115 | "INSERT %v INTO %v (%v) VALUES (%v)%v%v", | |
116 | addExtraSpaceIfExist(insertModifier), | |
108 | 117 | scope.QuotedTableName(), |
109 | 118 | strings.Join(columns, ","), |
110 | 119 | strings.Join(placeholders, ","), |
15 | 15 | // queryCallback used to query data from database |
16 | 16 | func queryCallback(scope *Scope) { |
17 | 17 | if _, skip := scope.InstanceGet("gorm:skip_query_callback"); skip { |
18 | return | |
19 | } | |
20 | ||
21 | //we are only preloading relations, dont touch base model | |
22 | if _, skip := scope.InstanceGet("gorm:only_preload"); skip { | |
18 | 23 | return |
19 | 24 | } |
20 | 25 |
13 | 13 | return |
14 | 14 | } |
15 | 15 | |
16 | if _, ok := scope.Get("gorm:auto_preload"); ok { | |
17 | autoPreload(scope) | |
16 | if ap, ok := scope.Get("gorm:auto_preload"); ok { | |
17 | // If gorm:auto_preload IS NOT a bool then auto preload. | |
18 | // Else if it IS a bool, use the value | |
19 | if apb, ok := ap.(bool); !ok { | |
20 | autoPreload(scope) | |
21 | } else if apb { | |
22 | autoPreload(scope) | |
23 | } | |
18 | 24 | } |
19 | 25 | |
20 | 26 | if scope.Search.preload == nil || scope.HasError() { |
93 | 99 | continue |
94 | 100 | } |
95 | 101 | |
96 | if val, ok := field.TagSettings["PRELOAD"]; ok { | |
102 | if val, ok := field.TagSettingsGet("PRELOAD"); ok { | |
97 | 103 | if preload, err := strconv.ParseBool(val); err != nil { |
98 | 104 | scope.Err(errors.New("invalid preload option")) |
99 | 105 | return |
154 | 160 | ) |
155 | 161 | |
156 | 162 | if indirectScopeValue.Kind() == reflect.Slice { |
163 | foreignValuesToResults := make(map[string]reflect.Value) | |
164 | for i := 0; i < resultsValue.Len(); i++ { | |
165 | result := resultsValue.Index(i) | |
166 | foreignValues := toString(getValueFromFields(result, relation.ForeignFieldNames)) | |
167 | foreignValuesToResults[foreignValues] = result | |
168 | } | |
157 | 169 | for j := 0; j < indirectScopeValue.Len(); j++ { |
158 | for i := 0; i < resultsValue.Len(); i++ { | |
159 | result := resultsValue.Index(i) | |
160 | foreignValues := getValueFromFields(result, relation.ForeignFieldNames) | |
161 | if indirectValue := indirect(indirectScopeValue.Index(j)); equalAsString(getValueFromFields(indirectValue, relation.AssociationForeignFieldNames), foreignValues) { | |
162 | indirectValue.FieldByName(field.Name).Set(result) | |
163 | break | |
164 | } | |
170 | indirectValue := indirect(indirectScopeValue.Index(j)) | |
171 | valueString := toString(getValueFromFields(indirectValue, relation.AssociationForeignFieldNames)) | |
172 | if result, found := foreignValuesToResults[valueString]; found { | |
173 | indirectValue.FieldByName(field.Name).Set(result) | |
165 | 174 | } |
166 | 175 | } |
167 | 176 | } else { |
248 | 257 | indirectScopeValue = scope.IndirectValue() |
249 | 258 | ) |
250 | 259 | |
260 | foreignFieldToObjects := make(map[string][]*reflect.Value) | |
261 | if indirectScopeValue.Kind() == reflect.Slice { | |
262 | for j := 0; j < indirectScopeValue.Len(); j++ { | |
263 | object := indirect(indirectScopeValue.Index(j)) | |
264 | valueString := toString(getValueFromFields(object, relation.ForeignFieldNames)) | |
265 | foreignFieldToObjects[valueString] = append(foreignFieldToObjects[valueString], &object) | |
266 | } | |
267 | } | |
268 | ||
251 | 269 | for i := 0; i < resultsValue.Len(); i++ { |
252 | 270 | result := resultsValue.Index(i) |
253 | 271 | if indirectScopeValue.Kind() == reflect.Slice { |
254 | value := getValueFromFields(result, relation.AssociationForeignFieldNames) | |
255 | for j := 0; j < indirectScopeValue.Len(); j++ { | |
256 | object := indirect(indirectScopeValue.Index(j)) | |
257 | if equalAsString(getValueFromFields(object, relation.ForeignFieldNames), value) { | |
272 | valueString := toString(getValueFromFields(result, relation.AssociationForeignFieldNames)) | |
273 | if objects, found := foreignFieldToObjects[valueString]; found { | |
274 | for _, object := range objects { | |
258 | 275 | object.FieldByName(field.Name).Set(result) |
259 | 276 | } |
260 | 277 | } |
373 | 390 | key := toString(getValueFromFields(indirectScopeValue, foreignFieldNames)) |
374 | 391 | fieldsSourceMap[key] = append(fieldsSourceMap[key], indirectScopeValue.FieldByName(field.Name)) |
375 | 392 | } |
376 | for source, link := range linkHash { | |
377 | for i, field := range fieldsSourceMap[source] { | |
393 | ||
394 | for source, fields := range fieldsSourceMap { | |
395 | for _, f := range fields { | |
378 | 396 | //If not 0 this means Value is a pointer and we already added preloaded models to it |
379 | if fieldsSourceMap[source][i].Len() != 0 { | |
397 | if f.Len() != 0 { | |
380 | 398 | continue |
381 | 399 | } |
382 | field.Set(reflect.Append(fieldsSourceMap[source][i], link...)) | |
383 | } | |
384 | ||
385 | } | |
386 | } | |
400 | ||
401 | v := reflect.MakeSlice(f.Type(), 0, 0) | |
402 | if len(linkHash[source]) > 0 { | |
403 | v = reflect.Append(f, linkHash[source]...) | |
404 | } | |
405 | ||
406 | f.Set(v) | |
407 | } | |
408 | } | |
409 | } |
0 | 0 | package gorm |
1 | 1 | |
2 | import "database/sql" | |
2 | import ( | |
3 | "database/sql" | |
4 | "fmt" | |
5 | ) | |
3 | 6 | |
4 | 7 | // Define callbacks for row query |
5 | 8 | func init() { |
19 | 22 | func rowQueryCallback(scope *Scope) { |
20 | 23 | if result, ok := scope.InstanceGet("row_query_result"); ok { |
21 | 24 | scope.prepareQuerySQL() |
25 | if str, ok := scope.Get("gorm:query_option"); ok { | |
26 | scope.SQL += addExtraSpaceIfExist(fmt.Sprint(str)) | |
27 | } | |
22 | 28 | |
23 | 29 | if rowResult, ok := result.(*RowQueryResult); ok { |
24 | 30 | rowResult.Row = scope.SQLDB().QueryRow(scope.SQL, scope.SQLVars...) |
20 | 20 | |
21 | 21 | if v, ok := value.(string); ok { |
22 | 22 | v = strings.ToLower(v) |
23 | if v == "false" || v != "skip" { | |
24 | return false | |
25 | } | |
23 | return v == "true" | |
26 | 24 | } |
27 | 25 | |
28 | 26 | return true |
35 | 33 | if value, ok := scope.Get("gorm:save_associations"); ok { |
36 | 34 | autoUpdate = checkTruth(value) |
37 | 35 | autoCreate = autoUpdate |
38 | } else if value, ok := field.TagSettings["SAVE_ASSOCIATIONS"]; ok { | |
36 | saveReference = autoUpdate | |
37 | } else if value, ok := field.TagSettingsGet("SAVE_ASSOCIATIONS"); ok { | |
39 | 38 | autoUpdate = checkTruth(value) |
40 | 39 | autoCreate = autoUpdate |
40 | saveReference = autoUpdate | |
41 | 41 | } |
42 | 42 | |
43 | 43 | if value, ok := scope.Get("gorm:association_autoupdate"); ok { |
44 | 44 | autoUpdate = checkTruth(value) |
45 | } else if value, ok := field.TagSettings["ASSOCIATION_AUTOUPDATE"]; ok { | |
45 | } else if value, ok := field.TagSettingsGet("ASSOCIATION_AUTOUPDATE"); ok { | |
46 | 46 | autoUpdate = checkTruth(value) |
47 | 47 | } |
48 | 48 | |
49 | 49 | if value, ok := scope.Get("gorm:association_autocreate"); ok { |
50 | 50 | autoCreate = checkTruth(value) |
51 | } else if value, ok := field.TagSettings["ASSOCIATION_AUTOCREATE"]; ok { | |
51 | } else if value, ok := field.TagSettingsGet("ASSOCIATION_AUTOCREATE"); ok { | |
52 | 52 | autoCreate = checkTruth(value) |
53 | 53 | } |
54 | 54 | |
55 | 55 | if value, ok := scope.Get("gorm:association_save_reference"); ok { |
56 | 56 | saveReference = checkTruth(value) |
57 | } else if value, ok := field.TagSettings["ASSOCIATION_SAVE_REFERENCE"]; ok { | |
57 | } else if value, ok := field.TagSettingsGet("ASSOCIATION_SAVE_REFERENCE"); ok { | |
58 | 58 | saveReference = checkTruth(value) |
59 | 59 | } |
60 | 60 | } |
22 | 22 | func afterCreate2(s *Scope) {} |
23 | 23 | |
24 | 24 | func TestRegisterCallback(t *testing.T) { |
25 | var callback = &Callback{} | |
25 | var callback = &Callback{logger: defaultLogger} | |
26 | 26 | |
27 | 27 | callback.Create().Register("before_create1", beforeCreate1) |
28 | 28 | callback.Create().Register("before_create2", beforeCreate2) |
36 | 36 | } |
37 | 37 | |
38 | 38 | func TestRegisterCallbackWithOrder(t *testing.T) { |
39 | var callback1 = &Callback{} | |
39 | var callback1 = &Callback{logger: defaultLogger} | |
40 | 40 | callback1.Create().Register("before_create1", beforeCreate1) |
41 | 41 | callback1.Create().Register("create", create) |
42 | 42 | callback1.Create().Register("after_create1", afterCreate1) |
45 | 45 | t.Errorf("register callback with order") |
46 | 46 | } |
47 | 47 | |
48 | var callback2 = &Callback{} | |
48 | var callback2 = &Callback{logger: defaultLogger} | |
49 | 49 | |
50 | 50 | callback2.Update().Register("create", create) |
51 | 51 | callback2.Update().Before("create").Register("before_create1", beforeCreate1) |
59 | 59 | } |
60 | 60 | |
61 | 61 | func TestRegisterCallbackWithComplexOrder(t *testing.T) { |
62 | var callback1 = &Callback{} | |
62 | var callback1 = &Callback{logger: defaultLogger} | |
63 | 63 | |
64 | 64 | callback1.Query().Before("after_create1").After("before_create1").Register("create", create) |
65 | 65 | callback1.Query().Register("before_create1", beforeCreate1) |
69 | 69 | t.Errorf("register callback with order") |
70 | 70 | } |
71 | 71 | |
72 | var callback2 = &Callback{} | |
72 | var callback2 = &Callback{logger: defaultLogger} | |
73 | 73 | |
74 | 74 | callback2.Delete().Before("after_create1").After("before_create1").Register("create", create) |
75 | 75 | callback2.Delete().Before("create").Register("before_create1", beforeCreate1) |
85 | 85 | func replaceCreate(s *Scope) {} |
86 | 86 | |
87 | 87 | func TestReplaceCallback(t *testing.T) { |
88 | var callback = &Callback{} | |
88 | var callback = &Callback{logger: defaultLogger} | |
89 | 89 | |
90 | 90 | callback.Create().Before("after_create1").After("before_create1").Register("create", create) |
91 | 91 | callback.Create().Register("before_create1", beforeCreate1) |
98 | 98 | } |
99 | 99 | |
100 | 100 | func TestRemoveCallback(t *testing.T) { |
101 | var callback = &Callback{} | |
101 | var callback = &Callback{logger: defaultLogger} | |
102 | 102 | |
103 | 103 | callback.Create().Before("after_create1").After("before_create1").Register("create", create) |
104 | 104 | callback.Create().Register("before_create1", beforeCreate1) |
74 | 74 | } else { |
75 | 75 | for _, field := range scope.Fields() { |
76 | 76 | if scope.changeableField(field) { |
77 | if !field.IsPrimaryKey && field.IsNormal { | |
78 | sqls = append(sqls, fmt.Sprintf("%v = %v", scope.Quote(field.DBName), scope.AddToVars(field.Field.Interface()))) | |
77 | if !field.IsPrimaryKey && field.IsNormal && (field.Name != "CreatedAt" || !field.IsBlank) { | |
78 | if !field.IsForeignKey || !field.IsBlank || !field.HasDefaultValue { | |
79 | sqls = append(sqls, fmt.Sprintf("%v = %v", scope.Quote(field.DBName), scope.AddToVars(field.Field.Interface()))) | |
80 | } | |
79 | 81 | } else if relationship := field.Relationship; relationship != nil && relationship.Kind == "belongs_to" { |
80 | 82 | for _, foreignKey := range relationship.ForeignDBNames { |
81 | 83 | if foreignField, ok := scope.FieldByName(foreignKey); ok && !scope.changeableField(foreignField) { |
228 | 228 | t.Errorf("Should not create omitted relationships") |
229 | 229 | } |
230 | 230 | } |
231 | ||
232 | func TestCreateIgnore(t *testing.T) { | |
233 | float := 35.03554004971999 | |
234 | now := time.Now() | |
235 | user := User{Name: "CreateUser", Age: 18, Birthday: &now, UserNum: Num(111), PasswordHash: []byte{'f', 'a', 'k', '4'}, Latitude: float} | |
236 | ||
237 | if !DB.NewRecord(user) || !DB.NewRecord(&user) { | |
238 | t.Error("User should be new record before create") | |
239 | } | |
240 | ||
241 | if count := DB.Create(&user).RowsAffected; count != 1 { | |
242 | t.Error("There should be one record be affected when create record") | |
243 | } | |
244 | if DB.Dialect().GetName() == "mysql" && DB.Set("gorm:insert_modifier", "IGNORE").Create(&user).Error != nil { | |
245 | t.Error("Should ignore duplicate user insert by insert modifier:IGNORE ") | |
246 | } | |
247 | } |
288 | 288 | func TestSelfReferencingMany2ManyColumn(t *testing.T) { |
289 | 289 | DB.DropTable(&SelfReferencingUser{}, "UserFriends") |
290 | 290 | DB.AutoMigrate(&SelfReferencingUser{}) |
291 | if !DB.HasTable("UserFriends") { | |
292 | t.Errorf("auto migrate error, table UserFriends should be created") | |
293 | } | |
291 | 294 | |
292 | 295 | friend1 := SelfReferencingUser{Name: "friend1_m2m"} |
293 | 296 | if err := DB.Create(&friend1).Error; err != nil { |
310 | 313 | |
311 | 314 | if DB.Model(&user).Association("Friends").Count() != 2 { |
312 | 315 | t.Errorf("Should find created friends correctly") |
316 | } | |
317 | ||
318 | var count int | |
319 | if err := DB.Table("UserFriends").Count(&count).Error; err != nil { | |
320 | t.Errorf("no error should happen, but got %v", err) | |
321 | } | |
322 | if count == 0 { | |
323 | t.Errorf("table UserFriends should have records") | |
313 | 324 | } |
314 | 325 | |
315 | 326 | var newUser = SelfReferencingUser{} |
47 | 47 | // BuildKeyName returns a valid key name (foreign key, index key) for the given table, field and reference |
48 | 48 | BuildKeyName(kind, tableName string, fields ...string) string |
49 | 49 | |
50 | // NormalizeIndexAndColumn returns valid index name and column name depending on each dialect | |
51 | NormalizeIndexAndColumn(indexName, columnName string) (string, string) | |
52 | ||
50 | 53 | // CurrentDatabase return current database name |
51 | 54 | CurrentDatabase() string |
52 | 55 | } |
71 | 74 | dialectsMap[name] = dialect |
72 | 75 | } |
73 | 76 | |
77 | // GetDialect gets the dialect for the specified dialect name | |
78 | func GetDialect(name string) (dialect Dialect, ok bool) { | |
79 | dialect, ok = dialectsMap[name] | |
80 | return | |
81 | } | |
82 | ||
74 | 83 | // ParseFieldStructForDialect get field's sql data type |
75 | 84 | var ParseFieldStructForDialect = func(field *StructField, dialect Dialect) (fieldValue reflect.Value, sqlType string, size int, additionalType string) { |
76 | 85 | // Get redirected field type |
77 | 86 | var ( |
78 | 87 | reflectType = field.Struct.Type |
79 | dataType = field.TagSettings["TYPE"] | |
88 | dataType, _ = field.TagSettingsGet("TYPE") | |
80 | 89 | ) |
81 | 90 | |
82 | 91 | for reflectType.Kind() == reflect.Ptr { |
105 | 114 | } |
106 | 115 | |
107 | 116 | // Default Size |
108 | if num, ok := field.TagSettings["SIZE"]; ok { | |
117 | if num, ok := field.TagSettingsGet("SIZE"); ok { | |
109 | 118 | size, _ = strconv.Atoi(num) |
110 | 119 | } else { |
111 | 120 | size = 255 |
112 | 121 | } |
113 | 122 | |
114 | 123 | // Default type from tag setting |
115 | additionalType = field.TagSettings["NOT NULL"] + " " + field.TagSettings["UNIQUE"] | |
116 | if value, ok := field.TagSettings["DEFAULT"]; ok { | |
124 | notNull, _ := field.TagSettingsGet("NOT NULL") | |
125 | unique, _ := field.TagSettingsGet("UNIQUE") | |
126 | additionalType = notNull + " " + unique | |
127 | if value, ok := field.TagSettingsGet("DEFAULT"); ok { | |
117 | 128 | additionalType = additionalType + " DEFAULT " + value |
129 | } | |
130 | ||
131 | if value, ok := field.TagSettingsGet("COMMENT"); ok { | |
132 | additionalType = additionalType + " COMMENT " + value | |
118 | 133 | } |
119 | 134 | |
120 | 135 | return fieldValue, dataType, size, strings.TrimSpace(additionalType) |
7 | 7 | "strings" |
8 | 8 | "time" |
9 | 9 | ) |
10 | ||
11 | var keyNameRegex = regexp.MustCompile("[^a-zA-Z0-9]+") | |
10 | 12 | |
11 | 13 | // DefaultForeignKeyNamer contains the default foreign key name generator method |
12 | 14 | type DefaultForeignKeyNamer struct { |
38 | 40 | } |
39 | 41 | |
40 | 42 | func (s *commonDialect) fieldCanAutoIncrement(field *StructField) bool { |
41 | if value, ok := field.TagSettings["AUTO_INCREMENT"]; ok { | |
43 | if value, ok := field.TagSettingsGet("AUTO_INCREMENT"); ok { | |
42 | 44 | return strings.ToLower(value) != "false" |
43 | 45 | } |
44 | 46 | return field.IsPrimaryKey |
165 | 167 | // BuildKeyName returns a valid key name (foreign key, index key) for the given table, field and reference |
166 | 168 | func (DefaultForeignKeyNamer) BuildKeyName(kind, tableName string, fields ...string) string { |
167 | 169 | keyName := fmt.Sprintf("%s_%s_%s", kind, tableName, strings.Join(fields, "_")) |
168 | keyName = regexp.MustCompile("[^a-zA-Z0-9]+").ReplaceAllString(keyName, "_") | |
170 | keyName = keyNameRegex.ReplaceAllString(keyName, "_") | |
169 | 171 | return keyName |
172 | } | |
173 | ||
174 | // NormalizeIndexAndColumn returns argument's index name and column name without doing anything | |
175 | func (commonDialect) NormalizeIndexAndColumn(indexName, columnName string) (string, string) { | |
176 | return indexName, columnName | |
170 | 177 | } |
171 | 178 | |
172 | 179 | // IsByteArrayOrSlice returns true of the reflected value is an array or slice |
10 | 10 | "unicode/utf8" |
11 | 11 | ) |
12 | 12 | |
13 | var mysqlIndexRegex = regexp.MustCompile(`^(.+)\((\d+)\)$`) | |
14 | ||
13 | 15 | type mysql struct { |
14 | 16 | commonDialect |
15 | 17 | } |
32 | 34 | |
33 | 35 | // MySQL allows only one auto increment column per table, and it must |
34 | 36 | // be a KEY column. |
35 | if _, ok := field.TagSettings["AUTO_INCREMENT"]; ok { | |
36 | if _, ok = field.TagSettings["INDEX"]; !ok && !field.IsPrimaryKey { | |
37 | delete(field.TagSettings, "AUTO_INCREMENT") | |
37 | if _, ok := field.TagSettingsGet("AUTO_INCREMENT"); ok { | |
38 | if _, ok = field.TagSettingsGet("INDEX"); !ok && !field.IsPrimaryKey { | |
39 | field.TagSettingsDelete("AUTO_INCREMENT") | |
38 | 40 | } |
39 | 41 | } |
40 | 42 | |
44 | 46 | sqlType = "boolean" |
45 | 47 | case reflect.Int8: |
46 | 48 | if s.fieldCanAutoIncrement(field) { |
47 | field.TagSettings["AUTO_INCREMENT"] = "AUTO_INCREMENT" | |
49 | field.TagSettingsSet("AUTO_INCREMENT", "AUTO_INCREMENT") | |
48 | 50 | sqlType = "tinyint AUTO_INCREMENT" |
49 | 51 | } else { |
50 | 52 | sqlType = "tinyint" |
51 | 53 | } |
52 | 54 | case reflect.Int, reflect.Int16, reflect.Int32: |
53 | 55 | if s.fieldCanAutoIncrement(field) { |
54 | field.TagSettings["AUTO_INCREMENT"] = "AUTO_INCREMENT" | |
56 | field.TagSettingsSet("AUTO_INCREMENT", "AUTO_INCREMENT") | |
55 | 57 | sqlType = "int AUTO_INCREMENT" |
56 | 58 | } else { |
57 | 59 | sqlType = "int" |
58 | 60 | } |
59 | 61 | case reflect.Uint8: |
60 | 62 | if s.fieldCanAutoIncrement(field) { |
61 | field.TagSettings["AUTO_INCREMENT"] = "AUTO_INCREMENT" | |
63 | field.TagSettingsSet("AUTO_INCREMENT", "AUTO_INCREMENT") | |
62 | 64 | sqlType = "tinyint unsigned AUTO_INCREMENT" |
63 | 65 | } else { |
64 | 66 | sqlType = "tinyint unsigned" |
65 | 67 | } |
66 | 68 | case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uintptr: |
67 | 69 | if s.fieldCanAutoIncrement(field) { |
68 | field.TagSettings["AUTO_INCREMENT"] = "AUTO_INCREMENT" | |
70 | field.TagSettingsSet("AUTO_INCREMENT", "AUTO_INCREMENT") | |
69 | 71 | sqlType = "int unsigned AUTO_INCREMENT" |
70 | 72 | } else { |
71 | 73 | sqlType = "int unsigned" |
72 | 74 | } |
73 | 75 | case reflect.Int64: |
74 | 76 | if s.fieldCanAutoIncrement(field) { |
75 | field.TagSettings["AUTO_INCREMENT"] = "AUTO_INCREMENT" | |
77 | field.TagSettingsSet("AUTO_INCREMENT", "AUTO_INCREMENT") | |
76 | 78 | sqlType = "bigint AUTO_INCREMENT" |
77 | 79 | } else { |
78 | 80 | sqlType = "bigint" |
79 | 81 | } |
80 | 82 | case reflect.Uint64: |
81 | 83 | if s.fieldCanAutoIncrement(field) { |
82 | field.TagSettings["AUTO_INCREMENT"] = "AUTO_INCREMENT" | |
84 | field.TagSettingsSet("AUTO_INCREMENT", "AUTO_INCREMENT") | |
83 | 85 | sqlType = "bigint unsigned AUTO_INCREMENT" |
84 | 86 | } else { |
85 | 87 | sqlType = "bigint unsigned" |
95 | 97 | case reflect.Struct: |
96 | 98 | if _, ok := dataValue.Interface().(time.Time); ok { |
97 | 99 | precision := "" |
98 | if p, ok := field.TagSettings["PRECISION"]; ok { | |
100 | if p, ok := field.TagSettingsGet("PRECISION"); ok { | |
99 | 101 | precision = fmt.Sprintf("(%s)", p) |
100 | 102 | } |
101 | 103 | |
102 | if _, ok := field.TagSettings["NOT NULL"]; ok { | |
104 | if _, ok := field.TagSettingsGet("NOT NULL"); ok || field.IsPrimaryKey { | |
103 | 105 | sqlType = fmt.Sprintf("timestamp%v", precision) |
104 | 106 | } else { |
105 | 107 | sqlType = fmt.Sprintf("timestamp%v NULL", precision) |
177 | 179 | bs := h.Sum(nil) |
178 | 180 | |
179 | 181 | // sha1 is 40 characters, keep first 24 characters of destination |
180 | destRunes := []rune(regexp.MustCompile("[^a-zA-Z0-9]+").ReplaceAllString(fields[0], "_")) | |
182 | destRunes := []rune(keyNameRegex.ReplaceAllString(fields[0], "_")) | |
181 | 183 | if len(destRunes) > 24 { |
182 | 184 | destRunes = destRunes[:24] |
183 | 185 | } |
185 | 187 | return fmt.Sprintf("%s%x", string(destRunes), bs) |
186 | 188 | } |
187 | 189 | |
190 | // NormalizeIndexAndColumn returns index name and column name for specify an index prefix length if needed | |
191 | func (mysql) NormalizeIndexAndColumn(indexName, columnName string) (string, string) { | |
192 | submatch := mysqlIndexRegex.FindStringSubmatch(indexName) | |
193 | if len(submatch) != 3 { | |
194 | return indexName, columnName | |
195 | } | |
196 | indexName = submatch[1] | |
197 | columnName = fmt.Sprintf("%s(%s)", columnName, submatch[2]) | |
198 | return indexName, columnName | |
199 | } | |
200 | ||
188 | 201 | func (mysql) DefaultValueStr() string { |
189 | 202 | return "VALUES()" |
190 | 203 | } |
33 | 33 | sqlType = "boolean" |
34 | 34 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uintptr: |
35 | 35 | if s.fieldCanAutoIncrement(field) { |
36 | field.TagSettings["AUTO_INCREMENT"] = "AUTO_INCREMENT" | |
36 | field.TagSettingsSet("AUTO_INCREMENT", "AUTO_INCREMENT") | |
37 | 37 | sqlType = "serial" |
38 | 38 | } else { |
39 | 39 | sqlType = "integer" |
40 | 40 | } |
41 | 41 | case reflect.Int64, reflect.Uint32, reflect.Uint64: |
42 | 42 | if s.fieldCanAutoIncrement(field) { |
43 | field.TagSettings["AUTO_INCREMENT"] = "AUTO_INCREMENT" | |
43 | field.TagSettingsSet("AUTO_INCREMENT", "AUTO_INCREMENT") | |
44 | 44 | sqlType = "bigserial" |
45 | 45 | } else { |
46 | 46 | sqlType = "bigint" |
48 | 48 | case reflect.Float32, reflect.Float64: |
49 | 49 | sqlType = "numeric" |
50 | 50 | case reflect.String: |
51 | if _, ok := field.TagSettings["SIZE"]; !ok { | |
51 | if _, ok := field.TagSettingsGet("SIZE"); !ok { | |
52 | 52 | size = 0 // if SIZE haven't been set, use `text` as the default type, as there are no performance different |
53 | 53 | } |
54 | 54 |
28 | 28 | sqlType = "bool" |
29 | 29 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uintptr: |
30 | 30 | if s.fieldCanAutoIncrement(field) { |
31 | field.TagSettings["AUTO_INCREMENT"] = "AUTO_INCREMENT" | |
31 | field.TagSettingsSet("AUTO_INCREMENT", "AUTO_INCREMENT") | |
32 | 32 | sqlType = "integer primary key autoincrement" |
33 | 33 | } else { |
34 | 34 | sqlType = "integer" |
35 | 35 | } |
36 | 36 | case reflect.Int64, reflect.Uint64: |
37 | 37 | if s.fieldCanAutoIncrement(field) { |
38 | field.TagSettings["AUTO_INCREMENT"] = "AUTO_INCREMENT" | |
38 | field.TagSettingsSet("AUTO_INCREMENT", "AUTO_INCREMENT") | |
39 | 39 | sqlType = "integer primary key autoincrement" |
40 | 40 | } else { |
41 | 41 | sqlType = "bigint" |
0 | 0 | package mssql |
1 | 1 | |
2 | 2 | import ( |
3 | "database/sql/driver" | |
4 | "encoding/json" | |
5 | "errors" | |
3 | 6 | "fmt" |
4 | 7 | "reflect" |
5 | 8 | "strconv" |
6 | 9 | "strings" |
7 | 10 | "time" |
8 | 11 | |
12 | // Importing mssql driver package only in dialect file, otherwide not needed | |
9 | 13 | _ "github.com/denisenkom/go-mssqldb" |
10 | 14 | "github.com/jinzhu/gorm" |
11 | 15 | ) |
13 | 17 | func setIdentityInsert(scope *gorm.Scope) { |
14 | 18 | if scope.Dialect().GetName() == "mssql" { |
15 | 19 | for _, field := range scope.PrimaryFields() { |
16 | if _, ok := field.TagSettings["AUTO_INCREMENT"]; ok && !field.IsBlank { | |
20 | if _, ok := field.TagSettingsGet("AUTO_INCREMENT"); ok && !field.IsBlank { | |
17 | 21 | scope.NewDB().Exec(fmt.Sprintf("SET IDENTITY_INSERT %v ON", scope.TableName())) |
18 | 22 | scope.InstanceSet("mssql:identity_insert_on", true) |
19 | 23 | } |
65 | 69 | sqlType = "bit" |
66 | 70 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uintptr: |
67 | 71 | if s.fieldCanAutoIncrement(field) { |
68 | field.TagSettings["AUTO_INCREMENT"] = "AUTO_INCREMENT" | |
72 | field.TagSettingsSet("AUTO_INCREMENT", "AUTO_INCREMENT") | |
69 | 73 | sqlType = "int IDENTITY(1,1)" |
70 | 74 | } else { |
71 | 75 | sqlType = "int" |
72 | 76 | } |
73 | 77 | case reflect.Int64, reflect.Uint64: |
74 | 78 | if s.fieldCanAutoIncrement(field) { |
75 | field.TagSettings["AUTO_INCREMENT"] = "AUTO_INCREMENT" | |
79 | field.TagSettingsSet("AUTO_INCREMENT", "AUTO_INCREMENT") | |
76 | 80 | sqlType = "bigint IDENTITY(1,1)" |
77 | 81 | } else { |
78 | 82 | sqlType = "bigint" |
111 | 115 | } |
112 | 116 | |
113 | 117 | func (s mssql) fieldCanAutoIncrement(field *gorm.StructField) bool { |
114 | if value, ok := field.TagSettings["AUTO_INCREMENT"]; ok { | |
118 | if value, ok := field.TagSettingsGet("AUTO_INCREMENT"); ok { | |
115 | 119 | return value != "FALSE" |
116 | 120 | } |
117 | 121 | return field.IsPrimaryKey |
129 | 133 | } |
130 | 134 | |
131 | 135 | func (s mssql) HasForeignKey(tableName string, foreignKeyName string) bool { |
132 | return false | |
136 | var count int | |
137 | currentDatabase, tableName := currentDatabaseAndTable(&s, tableName) | |
138 | s.db.QueryRow(`SELECT count(*) | |
139 | FROM sys.foreign_keys as F inner join sys.tables as T on F.parent_object_id=T.object_id | |
140 | inner join information_schema.tables as I on I.TABLE_NAME = T.name | |
141 | WHERE F.name = ? | |
142 | AND T.Name = ? AND I.TABLE_CATALOG = ?;`, foreignKeyName, tableName, currentDatabase).Scan(&count) | |
143 | return count > 0 | |
133 | 144 | } |
134 | 145 | |
135 | 146 | func (s mssql) HasTable(tableName string) bool { |
186 | 197 | return "DEFAULT VALUES" |
187 | 198 | } |
188 | 199 | |
200 | // NormalizeIndexAndColumn returns argument's index name and column name without doing anything | |
201 | func (mssql) NormalizeIndexAndColumn(indexName, columnName string) (string, string) { | |
202 | return indexName, columnName | |
203 | } | |
204 | ||
189 | 205 | func currentDatabaseAndTable(dialect gorm.Dialect, tableName string) (string, string) { |
190 | 206 | if strings.Contains(tableName, ".") { |
191 | 207 | splitStrings := strings.SplitN(tableName, ".", 2) |
193 | 209 | } |
194 | 210 | return dialect.CurrentDatabase(), tableName |
195 | 211 | } |
212 | ||
213 | // JSON type to support easy handling of JSON data in character table fields | |
214 | // using golang json.RawMessage for deferred decoding/encoding | |
215 | type JSON struct { | |
216 | json.RawMessage | |
217 | } | |
218 | ||
219 | // Value get value of JSON | |
220 | func (j JSON) Value() (driver.Value, error) { | |
221 | if len(j.RawMessage) == 0 { | |
222 | return nil, nil | |
223 | } | |
224 | return j.MarshalJSON() | |
225 | } | |
226 | ||
227 | // Scan scan value into JSON | |
228 | func (j *JSON) Scan(value interface{}) error { | |
229 | str, ok := value.(string) | |
230 | if !ok { | |
231 | return errors.New(fmt.Sprint("Failed to unmarshal JSONB value (strcast):", value)) | |
232 | } | |
233 | bytes := []byte(str) | |
234 | return json.Unmarshal(bytes, j) | |
235 | } |
3 | 3 | "database/sql" |
4 | 4 | "database/sql/driver" |
5 | 5 | |
6 | _ "github.com/lib/pq" | |
7 | "github.com/lib/pq/hstore" | |
8 | 6 | "encoding/json" |
9 | 7 | "errors" |
10 | 8 | "fmt" |
9 | _ "github.com/lib/pq" | |
10 | "github.com/lib/pq/hstore" | |
11 | 11 | ) |
12 | 12 | |
13 | 13 | type Hstore map[string]*string |
5 | 5 | ) |
6 | 6 | |
7 | 7 | var ( |
8 | // ErrRecordNotFound record not found error, happens when haven't find any matched data when looking up with a struct | |
8 | // ErrRecordNotFound returns a "record not found error". Occurs only when attempting to query the database with a struct; querying with a slice won't return this error | |
9 | 9 | ErrRecordNotFound = errors.New("record not found") |
10 | // ErrInvalidSQL invalid SQL error, happens when you passed invalid SQL | |
10 | // ErrInvalidSQL occurs when you attempt a query with invalid SQL | |
11 | 11 | ErrInvalidSQL = errors.New("invalid SQL") |
12 | // ErrInvalidTransaction invalid transaction when you are trying to `Commit` or `Rollback` | |
12 | // ErrInvalidTransaction occurs when you are trying to `Commit` or `Rollback` | |
13 | 13 | ErrInvalidTransaction = errors.New("no valid transaction") |
14 | 14 | // ErrCantStartTransaction can't start transaction when you are trying to start one with `Begin` |
15 | 15 | ErrCantStartTransaction = errors.New("can't start transaction") |
20 | 20 | // Errors contains all happened errors |
21 | 21 | type Errors []error |
22 | 22 | |
23 | // IsRecordNotFoundError returns current error has record not found error or not | |
23 | // IsRecordNotFoundError returns true if error contains a RecordNotFound error | |
24 | 24 | func IsRecordNotFoundError(err error) bool { |
25 | 25 | if errs, ok := err.(Errors); ok { |
26 | 26 | for _, err := range errs { |
32 | 32 | return err == ErrRecordNotFound |
33 | 33 | } |
34 | 34 | |
35 | // GetErrors gets all happened errors | |
35 | // GetErrors gets all errors that have occurred and returns a slice of errors (Error type) | |
36 | 36 | func (errs Errors) GetErrors() []error { |
37 | 37 | return errs |
38 | 38 | } |
39 | 39 | |
40 | // Add adds an error | |
40 | // Add adds an error to a given slice of errors | |
41 | 41 | func (errs Errors) Add(newErrors ...error) Errors { |
42 | 42 | for _, err := range newErrors { |
43 | 43 | if err == nil { |
61 | 61 | return errs |
62 | 62 | } |
63 | 63 | |
64 | // Error format happened errors | |
64 | // Error takes a slice of all errors that have occurred and returns it as a formatted string | |
65 | 65 | func (errs Errors) Error() string { |
66 | 66 | var errors = []string{} |
67 | 67 | for _, e := range errs { |
1 | 1 | |
2 | 2 | import ( |
3 | 3 | "database/sql" |
4 | "database/sql/driver" | |
4 | 5 | "errors" |
5 | 6 | "fmt" |
6 | 7 | "reflect" |
43 | 44 | if reflectValue.Type().ConvertibleTo(fieldValue.Type()) { |
44 | 45 | fieldValue.Set(reflectValue.Convert(fieldValue.Type())) |
45 | 46 | } else if scanner, ok := fieldValue.Addr().Interface().(sql.Scanner); ok { |
46 | err = scanner.Scan(reflectValue.Interface()) | |
47 | v := reflectValue.Interface() | |
48 | if valuer, ok := v.(driver.Valuer); ok { | |
49 | if v, err = valuer.Value(); err == nil { | |
50 | err = scanner.Scan(v) | |
51 | } | |
52 | } else { | |
53 | err = scanner.Scan(v) | |
54 | } | |
47 | 55 | } else { |
48 | 56 | err = fmt.Errorf("could not convert argument of field %s from %s to %s", field.Name, reflectValue.Type(), fieldValue.Type()) |
49 | 57 | } |
0 | 0 | package gorm_test |
1 | 1 | |
2 | 2 | import ( |
3 | "database/sql/driver" | |
4 | "encoding/hex" | |
5 | "fmt" | |
3 | 6 | "testing" |
4 | 7 | |
5 | 8 | "github.com/jinzhu/gorm" |
42 | 45 | |
43 | 46 | if field, ok := scope.FieldByName("embedded_name"); !ok { |
44 | 47 | t.Errorf("should find embedded field") |
45 | } else if _, ok := field.TagSettings["NOT NULL"]; !ok { | |
48 | } else if _, ok := field.TagSettingsGet("NOT NULL"); !ok { | |
46 | 49 | t.Errorf("should find embedded field's tag settings") |
47 | 50 | } |
48 | 51 | } |
52 | ||
53 | type UUID [16]byte | |
54 | ||
55 | type NullUUID struct { | |
56 | UUID | |
57 | Valid bool | |
58 | } | |
59 | ||
60 | func FromString(input string) (u UUID) { | |
61 | src := []byte(input) | |
62 | return FromBytes(src) | |
63 | } | |
64 | ||
65 | func FromBytes(src []byte) (u UUID) { | |
66 | dst := u[:] | |
67 | hex.Decode(dst[0:4], src[0:8]) | |
68 | hex.Decode(dst[4:6], src[9:13]) | |
69 | hex.Decode(dst[6:8], src[14:18]) | |
70 | hex.Decode(dst[8:10], src[19:23]) | |
71 | hex.Decode(dst[10:], src[24:]) | |
72 | return | |
73 | } | |
74 | ||
75 | func (u UUID) String() string { | |
76 | buf := make([]byte, 36) | |
77 | src := u[:] | |
78 | hex.Encode(buf[0:8], src[0:4]) | |
79 | buf[8] = '-' | |
80 | hex.Encode(buf[9:13], src[4:6]) | |
81 | buf[13] = '-' | |
82 | hex.Encode(buf[14:18], src[6:8]) | |
83 | buf[18] = '-' | |
84 | hex.Encode(buf[19:23], src[8:10]) | |
85 | buf[23] = '-' | |
86 | hex.Encode(buf[24:], src[10:]) | |
87 | return string(buf) | |
88 | } | |
89 | ||
90 | func (u UUID) Value() (driver.Value, error) { | |
91 | return u.String(), nil | |
92 | } | |
93 | ||
94 | func (u *UUID) Scan(src interface{}) error { | |
95 | switch src := src.(type) { | |
96 | case UUID: // support gorm convert from UUID to NullUUID | |
97 | *u = src | |
98 | return nil | |
99 | case []byte: | |
100 | *u = FromBytes(src) | |
101 | return nil | |
102 | case string: | |
103 | *u = FromString(src) | |
104 | return nil | |
105 | } | |
106 | return fmt.Errorf("uuid: cannot convert %T to UUID", src) | |
107 | } | |
108 | ||
109 | func (u *NullUUID) Scan(src interface{}) error { | |
110 | u.Valid = true | |
111 | return u.UUID.Scan(src) | |
112 | } | |
113 | ||
114 | func TestFieldSet(t *testing.T) { | |
115 | type TestFieldSetNullUUID struct { | |
116 | NullUUID NullUUID | |
117 | } | |
118 | scope := DB.NewScope(&TestFieldSetNullUUID{}) | |
119 | field := scope.Fields()[0] | |
120 | err := field.Set(FromString("3034d44a-da03-11e8-b366-4a00070b9f00")) | |
121 | if err != nil { | |
122 | t.Fatal(err) | |
123 | } | |
124 | if id, ok := field.Field.Addr().Interface().(*NullUUID); !ok { | |
125 | t.Fatal() | |
126 | } else if !id.Valid || id.UUID.String() != "3034d44a-da03-11e8-b366-4a00070b9f00" { | |
127 | t.Fatal(id) | |
128 | } | |
129 | } |
0 | module github.com/jinzhu/gorm | |
1 | ||
2 | require ( | |
3 | github.com/denisenkom/go-mssqldb v0.0.0-20190423183735-731ef375ac02 | |
4 | github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5 | |
5 | github.com/go-sql-driver/mysql v1.4.1 | |
6 | github.com/jinzhu/inflection v0.0.0-20180308033659-04140366298a | |
7 | github.com/jinzhu/now v1.0.0 | |
8 | github.com/lib/pq v1.1.0 | |
9 | github.com/mattn/go-sqlite3 v1.10.0 | |
10 | ) |
0 | cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= | |
1 | cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= | |
2 | cloud.google.com/go v0.37.4 h1:glPeL3BQJsbF6aIIYfZizMwc5LTYz250bDMjttbBGAU= | |
3 | cloud.google.com/go v0.37.4/go.mod h1:NHPJ89PdicEuT9hdPXMROBD91xc5uRDxsMtSB16k7hw= | |
4 | github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= | |
5 | github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo= | |
6 | github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= | |
7 | github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= | |
8 | github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= | |
9 | github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= | |
10 | github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= | |
11 | github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= | |
12 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= | |
13 | github.com/denisenkom/go-mssqldb v0.0.0-20190423183735-731ef375ac02 h1:PS3xfVPa8N84AzoWZHFCbA0+ikz4f4skktfjQoNMsgk= | |
14 | github.com/denisenkom/go-mssqldb v0.0.0-20190423183735-731ef375ac02/go.mod h1:zAg7JM8CkOJ43xKXIj7eRO9kmWm/TW578qo+oDO6tuM= | |
15 | github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs= | |
16 | github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU= | |
17 | github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= | |
18 | github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5 h1:Yzb9+7DPaBjB8zlTR87/ElzFsnQfuHnVUVqpZZIcV5Y= | |
19 | github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5/go.mod h1:a2zkGnVExMxdzMo3M0Hi/3sEU+cWnZpSni0O6/Yb/P0= | |
20 | github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= | |
21 | github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= | |
22 | github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= | |
23 | github.com/go-sql-driver/mysql v1.4.1 h1:g24URVg0OFbNUTx9qqY1IRZ9D9z3iPyi5zKhQZpNwpA= | |
24 | github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= | |
25 | github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= | |
26 | github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= | |
27 | github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= | |
28 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= | |
29 | github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= | |
30 | github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= | |
31 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= | |
32 | github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= | |
33 | github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= | |
34 | github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= | |
35 | github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= | |
36 | github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= | |
37 | github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= | |
38 | github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= | |
39 | github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= | |
40 | github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= | |
41 | github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= | |
42 | github.com/jinzhu/inflection v0.0.0-20180308033659-04140366298a h1:eeaG9XMUvRBYXJi4pg1ZKM7nxc5AfXfojeLLW7O5J3k= | |
43 | github.com/jinzhu/inflection v0.0.0-20180308033659-04140366298a/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= | |
44 | github.com/jinzhu/now v1.0.0 h1:6WV8LvwPpDhKjo5U9O6b4+xdG/jTXNPwlDme/MTo8Ns= | |
45 | github.com/jinzhu/now v1.0.0/go.mod h1:oHTiXerJ20+SfYcrdlBO7rzZRJWGwSTQ0iUY2jI6Gfc= | |
46 | github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= | |
47 | github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= | |
48 | github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= | |
49 | github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= | |
50 | github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= | |
51 | github.com/lib/pq v1.1.0 h1:/5u4a+KGJptBRqGzPvYQL9p0d/tPR4S31+Tnzj9lEO4= | |
52 | github.com/lib/pq v1.1.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= | |
53 | github.com/mattn/go-sqlite3 v1.10.0 h1:jbhqpg7tQe4SupckyijYiy0mJJ/pRyHvXf7JdWK860o= | |
54 | github.com/mattn/go-sqlite3 v1.10.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= | |
55 | github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= | |
56 | github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= | |
57 | github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= | |
58 | github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= | |
59 | github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= | |
60 | github.com/openzipkin/zipkin-go v0.1.6 h1:yXiysv1CSK7Q5yjGy1710zZGnsbMUIjluWBxtLXHPBo= | |
61 | github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw= | |
62 | github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= | |
63 | github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= | |
64 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= | |
65 | github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= | |
66 | github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829/go.mod h1:p2iRAGwDERtqlqzRXnrOVns+ignqQo//hLXqYxZYVNs= | |
67 | github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= | |
68 | github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= | |
69 | github.com/prometheus/common v0.2.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= | |
70 | github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= | |
71 | github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= | |
72 | github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= | |
73 | github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= | |
74 | github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= | |
75 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= | |
76 | go.opencensus.io v0.20.1/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= | |
77 | golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= | |
78 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= | |
79 | golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c h1:Vj5n4GlwjmQteupaxJ9+0FNOmBrHfq7vN4btdGoDZgI= | |
80 | golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= | |
81 | golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= | |
82 | golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= | |
83 | golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= | |
84 | golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= | |
85 | golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= | |
86 | golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= | |
87 | golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= | |
88 | golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= | |
89 | golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= | |
90 | golang.org/x/net v0.0.0-20190125091013-d26f9f9a57f3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= | |
91 | golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= | |
92 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= | |
93 | golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= | |
94 | golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= | |
95 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= | |
96 | golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= | |
97 | golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= | |
98 | golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= | |
99 | golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= | |
100 | golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= | |
101 | golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= | |
102 | golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= | |
103 | golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= | |
104 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= | |
105 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= | |
106 | golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= | |
107 | golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= | |
108 | golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= | |
109 | golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= | |
110 | golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= | |
111 | golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= | |
112 | google.golang.org/api v0.3.1/go.mod h1:6wY9I6uQWHQ8EM57III9mq/AjF+i8G65rmVagqKMtkk= | |
113 | google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= | |
114 | google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= | |
115 | google.golang.org/appengine v1.5.0 h1:KxkO13IPW4Lslp2bz+KHP2E3gtFlrIGNThxkZQ3g+4c= | |
116 | google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= | |
117 | google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= | |
118 | google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= | |
119 | google.golang.org/genproto v0.0.0-20190404172233-64821d5d2107/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= | |
120 | google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= | |
121 | google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= | |
122 | google.golang.org/grpc v1.20.1 h1:Hz2g2wirWK7H0qIIhGIqRGTuMwTE8HEKFnDZZ7lm9NU= | |
123 | google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= | |
124 | gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= | |
125 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= | |
126 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= | |
127 | gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= | |
128 | gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= | |
129 | gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= | |
130 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= | |
131 | honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= | |
132 | honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= | |
133 | honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= |
62 | 62 | formattedValues = append(formattedValues, "NULL") |
63 | 63 | } |
64 | 64 | } else { |
65 | formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value)) | |
65 | switch value.(type) { | |
66 | case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, bool: | |
67 | formattedValues = append(formattedValues, fmt.Sprintf("%v", value)) | |
68 | default: | |
69 | formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value)) | |
70 | } | |
66 | 71 | } |
67 | 72 | } else { |
68 | 73 | formattedValues = append(formattedValues, "NULL") |
5 | 5 | "fmt" |
6 | 6 | "reflect" |
7 | 7 | "strings" |
8 | "sync" | |
8 | 9 | "time" |
9 | 10 | ) |
10 | 11 | |
11 | 12 | // DB contains information for current db connection |
12 | 13 | type DB struct { |
14 | sync.RWMutex | |
13 | 15 | Value interface{} |
14 | 16 | Error error |
15 | 17 | RowsAffected int64 |
17 | 19 | // single db |
18 | 20 | db SQLCommon |
19 | 21 | blockGlobalUpdate bool |
20 | logMode int | |
22 | logMode logModeValue | |
21 | 23 | logger logger |
22 | 24 | search *search |
23 | values map[string]interface{} | |
25 | values sync.Map | |
24 | 26 | |
25 | 27 | // global db |
26 | 28 | parent *DB |
28 | 30 | dialect Dialect |
29 | 31 | singularTable bool |
30 | 32 | } |
33 | ||
34 | type logModeValue int | |
35 | ||
36 | const ( | |
37 | defaultLogMode logModeValue = iota | |
38 | noLogMode | |
39 | detailedLogMode | |
40 | ) | |
31 | 41 | |
32 | 42 | // Open initialize a new db connection, need to import driver first, e.g: |
33 | 43 | // |
47 | 57 | } |
48 | 58 | var source string |
49 | 59 | var dbSQL SQLCommon |
60 | var ownDbSQL bool | |
50 | 61 | |
51 | 62 | switch value := args[0].(type) { |
52 | 63 | case string: |
58 | 69 | source = args[1].(string) |
59 | 70 | } |
60 | 71 | dbSQL, err = sql.Open(driver, source) |
72 | ownDbSQL = true | |
61 | 73 | case SQLCommon: |
62 | 74 | dbSQL = value |
75 | ownDbSQL = false | |
76 | default: | |
77 | return nil, fmt.Errorf("invalid database source: %v is not a valid type", value) | |
63 | 78 | } |
64 | 79 | |
65 | 80 | db = &DB{ |
66 | 81 | db: dbSQL, |
67 | 82 | logger: defaultLogger, |
68 | values: map[string]interface{}{}, | |
69 | 83 | callbacks: DefaultCallback, |
70 | 84 | dialect: newDialect(dialect, dbSQL), |
71 | 85 | } |
75 | 89 | } |
76 | 90 | // Send a ping to make sure the database connection is alive. |
77 | 91 | if d, ok := dbSQL.(*sql.DB); ok { |
78 | if err = d.Ping(); err != nil { | |
92 | if err = d.Ping(); err != nil && ownDbSQL { | |
79 | 93 | d.Close() |
80 | 94 | } |
81 | 95 | } |
116 | 130 | |
117 | 131 | // Dialect get dialect |
118 | 132 | func (s *DB) Dialect() Dialect { |
119 | return s.parent.dialect | |
133 | return s.dialect | |
120 | 134 | } |
121 | 135 | |
122 | 136 | // Callback return `Callbacks` container, you could add/change/delete callbacks with it |
123 | 137 | // db.Callback().Create().Register("update_created_at", updateCreated) |
124 | 138 | // Refer https://jinzhu.github.io/gorm/development.html#callbacks |
125 | 139 | func (s *DB) Callback() *Callback { |
126 | s.parent.callbacks = s.parent.callbacks.clone() | |
140 | s.parent.callbacks = s.parent.callbacks.clone(s.logger) | |
127 | 141 | return s.parent.callbacks |
128 | 142 | } |
129 | 143 | |
135 | 149 | // LogMode set log mode, `true` for detailed logs, `false` for no log, default, will only print error logs |
136 | 150 | func (s *DB) LogMode(enable bool) *DB { |
137 | 151 | if enable { |
138 | s.logMode = 2 | |
152 | s.logMode = detailedLogMode | |
139 | 153 | } else { |
140 | s.logMode = 1 | |
154 | s.logMode = noLogMode | |
141 | 155 | } |
142 | 156 | return s |
143 | 157 | } |
156 | 170 | |
157 | 171 | // SingularTable use singular table by default |
158 | 172 | func (s *DB) SingularTable(enable bool) { |
159 | modelStructsMap = newModelStructsMap() | |
173 | s.parent.Lock() | |
174 | defer s.parent.Unlock() | |
160 | 175 | s.parent.singularTable = enable |
161 | 176 | } |
162 | 177 | |
164 | 179 | func (s *DB) NewScope(value interface{}) *Scope { |
165 | 180 | dbClone := s.clone() |
166 | 181 | dbClone.Value = value |
167 | return &Scope{db: dbClone, Search: dbClone.search.clone(), Value: value} | |
182 | scope := &Scope{db: dbClone, Value: value} | |
183 | if s.search != nil { | |
184 | scope.Search = s.search.clone() | |
185 | } else { | |
186 | scope.Search = &search{} | |
187 | } | |
188 | return scope | |
168 | 189 | } |
169 | 190 | |
170 | 191 | // QueryExpr returns the query as expr object |
284 | 305 | func (s *DB) First(out interface{}, where ...interface{}) *DB { |
285 | 306 | newScope := s.NewScope(out) |
286 | 307 | newScope.Search.Limit(1) |
308 | ||
287 | 309 | return newScope.Set("gorm:order_by_primary_key", "ASC"). |
288 | 310 | inlineCondition(where...).callCallbacks(s.parent.callbacks.queries).db |
289 | 311 | } |
306 | 328 | // Find find records that match given conditions |
307 | 329 | func (s *DB) Find(out interface{}, where ...interface{}) *DB { |
308 | 330 | return s.NewScope(out).inlineCondition(where...).callCallbacks(s.parent.callbacks.queries).db |
331 | } | |
332 | ||
333 | //Preloads preloads relations, don`t touch out | |
334 | func (s *DB) Preloads(out interface{}) *DB { | |
335 | return s.NewScope(out).InstanceSet("gorm:only_preload", 1).callCallbacks(s.parent.callbacks.queries).db | |
309 | 336 | } |
310 | 337 | |
311 | 338 | // Scan scan value to a struct |
481 | 508 | if db, ok := c.db.(sqlDb); ok && db != nil { |
482 | 509 | tx, err := db.Begin() |
483 | 510 | c.db = interface{}(tx).(SQLCommon) |
511 | ||
512 | c.dialect.SetDB(c.db) | |
484 | 513 | c.AddError(err) |
485 | 514 | } else { |
486 | 515 | c.AddError(ErrCantStartTransaction) |
490 | 519 | |
491 | 520 | // Commit commit a transaction |
492 | 521 | func (s *DB) Commit() *DB { |
493 | if db, ok := s.db.(sqlTx); ok && db != nil { | |
522 | var emptySQLTx *sql.Tx | |
523 | if db, ok := s.db.(sqlTx); ok && db != nil && db != emptySQLTx { | |
494 | 524 | s.AddError(db.Commit()) |
495 | 525 | } else { |
496 | 526 | s.AddError(ErrInvalidTransaction) |
500 | 530 | |
501 | 531 | // Rollback rollback a transaction |
502 | 532 | func (s *DB) Rollback() *DB { |
503 | if db, ok := s.db.(sqlTx); ok && db != nil { | |
533 | var emptySQLTx *sql.Tx | |
534 | if db, ok := s.db.(sqlTx); ok && db != nil && db != emptySQLTx { | |
504 | 535 | s.AddError(db.Rollback()) |
505 | 536 | } else { |
506 | 537 | s.AddError(ErrInvalidTransaction) |
669 | 700 | |
670 | 701 | // InstantSet instant set setting, will affect current db |
671 | 702 | func (s *DB) InstantSet(name string, value interface{}) *DB { |
672 | s.values[name] = value | |
703 | s.values.Store(name, value) | |
673 | 704 | return s |
674 | 705 | } |
675 | 706 | |
676 | 707 | // Get get setting by name |
677 | 708 | func (s *DB) Get(name string) (value interface{}, ok bool) { |
678 | value, ok = s.values[name] | |
709 | value, ok = s.values.Load(name) | |
679 | 710 | return |
680 | 711 | } |
681 | 712 | |
684 | 715 | scope := s.NewScope(source) |
685 | 716 | for _, field := range scope.GetModelStruct().StructFields { |
686 | 717 | if field.Name == column || field.DBName == column { |
687 | if many2many := field.TagSettings["MANY2MANY"]; many2many != "" { | |
718 | if many2many, _ := field.TagSettingsGet("MANY2MANY"); many2many != "" { | |
688 | 719 | source := (&Scope{Value: source}).GetModelStruct().ModelType |
689 | 720 | destination := (&Scope{Value: reflect.New(field.Struct.Type).Interface()}).GetModelStruct().ModelType |
690 | 721 | handler.Setup(field.Relationship, many2many, source, destination) |
701 | 732 | func (s *DB) AddError(err error) error { |
702 | 733 | if err != nil { |
703 | 734 | if err != ErrRecordNotFound { |
704 | if s.logMode == 0 { | |
705 | go s.print(fileWithLineNum(), err) | |
735 | if s.logMode == defaultLogMode { | |
736 | go s.print("error", fileWithLineNum(), err) | |
706 | 737 | } else { |
707 | 738 | s.log(err) |
708 | 739 | } |
739 | 770 | parent: s.parent, |
740 | 771 | logger: s.logger, |
741 | 772 | logMode: s.logMode, |
742 | values: map[string]interface{}{}, | |
743 | 773 | Value: s.Value, |
744 | 774 | Error: s.Error, |
745 | 775 | blockGlobalUpdate: s.blockGlobalUpdate, |
746 | } | |
747 | ||
748 | for key, value := range s.values { | |
749 | db.values[key] = value | |
750 | } | |
776 | dialect: newDialect(s.dialect.GetName(), s.db), | |
777 | } | |
778 | ||
779 | s.values.Range(func(k, v interface{}) bool { | |
780 | db.values.Store(k, v) | |
781 | return true | |
782 | }) | |
751 | 783 | |
752 | 784 | if s.search == nil { |
753 | 785 | db.search = &search{limit: -1, offset: -1} |
764 | 796 | } |
765 | 797 | |
766 | 798 | func (s *DB) log(v ...interface{}) { |
767 | if s != nil && s.logMode == 2 { | |
799 | if s != nil && s.logMode == detailedLogMode { | |
768 | 800 | s.print(append([]interface{}{"log", fileWithLineNum()}, v...)...) |
769 | 801 | } |
770 | 802 | } |
771 | 803 | |
772 | 804 | func (s *DB) slog(sql string, t time.Time, vars ...interface{}) { |
773 | if s.logMode == 2 { | |
805 | if s.logMode == detailedLogMode { | |
774 | 806 | s.print("sql", fileWithLineNum(), NowFunc().Sub(t), sql, vars, s.RowsAffected) |
775 | 807 | } |
776 | 808 | } |
7 | 7 | "path/filepath" |
8 | 8 | "reflect" |
9 | 9 | "strconv" |
10 | "strings" | |
11 | "sync" | |
10 | 12 | "testing" |
11 | 13 | "time" |
12 | 14 | |
78 | 80 | return |
79 | 81 | } |
80 | 82 | |
83 | func TestOpen_ReturnsError_WithBadArgs(t *testing.T) { | |
84 | stringRef := "foo" | |
85 | testCases := []interface{}{42, time.Now(), &stringRef} | |
86 | for _, tc := range testCases { | |
87 | t.Run(fmt.Sprintf("%v", tc), func(t *testing.T) { | |
88 | _, err := gorm.Open("postgresql", tc) | |
89 | if err == nil { | |
90 | t.Error("Should got error with invalid database source") | |
91 | } | |
92 | if !strings.HasPrefix(err.Error(), "invalid database source:") { | |
93 | t.Errorf("Should got error starting with \"invalid database source:\", but got %q", err.Error()) | |
94 | } | |
95 | }) | |
96 | } | |
97 | } | |
98 | ||
81 | 99 | func TestStringPrimaryKey(t *testing.T) { |
82 | 100 | type UUIDStruct struct { |
83 | 101 | ID string `gorm:"primary_key"` |
256 | 274 | if DB.NewScope([]Cart{}).TableName() != "shopping_cart" { |
257 | 275 | t.Errorf("[]Cart's singular table name should be shopping_cart") |
258 | 276 | } |
277 | DB.SingularTable(false) | |
278 | } | |
279 | ||
280 | func TestTableNameConcurrently(t *testing.T) { | |
281 | DB := DB.Model("") | |
282 | if DB.NewScope(Order{}).TableName() != "orders" { | |
283 | t.Errorf("Order's table name should be orders") | |
284 | } | |
285 | ||
286 | var wg sync.WaitGroup | |
287 | wg.Add(10) | |
288 | ||
289 | for i := 1; i <= 10; i++ { | |
290 | go func(db *gorm.DB) { | |
291 | DB.SingularTable(true) | |
292 | wg.Done() | |
293 | }(DB) | |
294 | } | |
295 | wg.Wait() | |
296 | ||
297 | if DB.NewScope(Order{}).TableName() != "order" { | |
298 | t.Errorf("Order's singular table name should be order") | |
299 | } | |
300 | ||
259 | 301 | DB.SingularTable(false) |
260 | 302 | } |
261 | 303 | |
560 | 602 | db5 := DB.Joins("join emails on emails.user_id = users.id AND emails.email = ?", "join1@example.com").Joins("join credit_cards on credit_cards.user_id = users.id AND credit_cards.number = ?", "411111111111").Where(User{Id: 1}).Where(Email{Id: 1}).Not(Email{Id: 10}).First(&users5) |
561 | 603 | if db5.Error != nil { |
562 | 604 | t.Errorf("Should not raise error for join where identical fields in different tables. Error: %s", db5.Error.Error()) |
605 | } | |
606 | } | |
607 | ||
608 | type JoinedIds struct { | |
609 | UserID int64 `gorm:"column:id"` | |
610 | BillingAddressID int64 `gorm:"column:id"` | |
611 | EmailID int64 `gorm:"column:id"` | |
612 | } | |
613 | ||
614 | func TestScanIdenticalColumnNames(t *testing.T) { | |
615 | var user = User{ | |
616 | Name: "joinsIds", | |
617 | Email: "joinIds@example.com", | |
618 | BillingAddress: Address{ | |
619 | Address1: "One Park Place", | |
620 | }, | |
621 | Emails: []Email{{Email: "join1@example.com"}, {Email: "join2@example.com"}}, | |
622 | } | |
623 | DB.Save(&user) | |
624 | ||
625 | var users []JoinedIds | |
626 | DB.Select("users.id, addresses.id, emails.id").Table("users"). | |
627 | Joins("left join addresses on users.billing_address_id = addresses.id"). | |
628 | Joins("left join emails on emails.user_id = users.id"). | |
629 | Where("name = ?", "joinsIds").Scan(&users) | |
630 | ||
631 | if len(users) != 2 { | |
632 | t.Fatal("should find two rows using left join") | |
633 | } | |
634 | ||
635 | if user.Id != users[0].UserID { | |
636 | t.Errorf("Expected result row to contain UserID %d, but got %d", user.Id, users[0].UserID) | |
637 | } | |
638 | if user.Id != users[1].UserID { | |
639 | t.Errorf("Expected result row to contain UserID %d, but got %d", user.Id, users[1].UserID) | |
640 | } | |
641 | ||
642 | if user.BillingAddressID.Int64 != users[0].BillingAddressID { | |
643 | t.Errorf("Expected result row to contain BillingAddressID %d, but got %d", user.BillingAddressID.Int64, users[0].BillingAddressID) | |
644 | } | |
645 | if user.BillingAddressID.Int64 != users[1].BillingAddressID { | |
646 | t.Errorf("Expected result row to contain BillingAddressID %d, but got %d", user.BillingAddressID.Int64, users[0].BillingAddressID) | |
647 | } | |
648 | ||
649 | if users[0].EmailID == users[1].EmailID { | |
650 | t.Errorf("Email ids should be unique. Got %d and %d", users[0].EmailID, users[1].EmailID) | |
651 | } | |
652 | ||
653 | if int64(user.Emails[0].Id) != users[0].EmailID && int64(user.Emails[1].Id) != users[0].EmailID { | |
654 | t.Errorf("Expected result row ID to be either %d or %d, but was %d", user.Emails[0].Id, user.Emails[1].Id, users[0].EmailID) | |
655 | } | |
656 | ||
657 | if int64(user.Emails[0].Id) != users[1].EmailID && int64(user.Emails[1].Id) != users[1].EmailID { | |
658 | t.Errorf("Expected result row ID to be either %d or %d, but was %d", user.Emails[0].Id, user.Emails[1].Id, users[1].EmailID) | |
563 | 659 | } |
564 | 660 | } |
565 | 661 | |
861 | 957 | } |
862 | 958 | } |
863 | 959 | |
960 | func TestSaveAssociations(t *testing.T) { | |
961 | db := DB.New() | |
962 | deltaAddressCount := 0 | |
963 | if err := db.Model(&Address{}).Count(&deltaAddressCount).Error; err != nil { | |
964 | t.Errorf("failed to fetch address count") | |
965 | t.FailNow() | |
966 | } | |
967 | ||
968 | placeAddress := &Address{ | |
969 | Address1: "somewhere on earth", | |
970 | } | |
971 | ownerAddress1 := &Address{ | |
972 | Address1: "near place address", | |
973 | } | |
974 | ownerAddress2 := &Address{ | |
975 | Address1: "address2", | |
976 | } | |
977 | db.Create(placeAddress) | |
978 | ||
979 | addressCountShouldBe := func(t *testing.T, expectedCount int) { | |
980 | countFromDB := 0 | |
981 | t.Helper() | |
982 | err := db.Model(&Address{}).Count(&countFromDB).Error | |
983 | if err != nil { | |
984 | t.Error("failed to fetch address count") | |
985 | } | |
986 | if countFromDB != expectedCount { | |
987 | t.Errorf("address count mismatch: %d", countFromDB) | |
988 | } | |
989 | } | |
990 | addressCountShouldBe(t, deltaAddressCount+1) | |
991 | ||
992 | // owner address should be created, place address should be reused | |
993 | place1 := &Place{ | |
994 | PlaceAddressID: placeAddress.ID, | |
995 | PlaceAddress: placeAddress, | |
996 | OwnerAddress: ownerAddress1, | |
997 | } | |
998 | err := db.Create(place1).Error | |
999 | if err != nil { | |
1000 | t.Errorf("failed to store place: %s", err.Error()) | |
1001 | } | |
1002 | addressCountShouldBe(t, deltaAddressCount+2) | |
1003 | ||
1004 | // owner address should be created again, place address should be reused | |
1005 | place2 := &Place{ | |
1006 | PlaceAddressID: placeAddress.ID, | |
1007 | PlaceAddress: &Address{ | |
1008 | ID: 777, | |
1009 | Address1: "address1", | |
1010 | }, | |
1011 | OwnerAddress: ownerAddress2, | |
1012 | OwnerAddressID: 778, | |
1013 | } | |
1014 | err = db.Create(place2).Error | |
1015 | if err != nil { | |
1016 | t.Errorf("failed to store place: %s", err.Error()) | |
1017 | } | |
1018 | addressCountShouldBe(t, deltaAddressCount+3) | |
1019 | ||
1020 | count := 0 | |
1021 | db.Model(&Place{}).Where(&Place{ | |
1022 | PlaceAddressID: placeAddress.ID, | |
1023 | OwnerAddressID: ownerAddress1.ID, | |
1024 | }).Count(&count) | |
1025 | if count != 1 { | |
1026 | t.Errorf("only one instance of (%d, %d) should be available, found: %d", | |
1027 | placeAddress.ID, ownerAddress1.ID, count) | |
1028 | } | |
1029 | ||
1030 | db.Model(&Place{}).Where(&Place{ | |
1031 | PlaceAddressID: placeAddress.ID, | |
1032 | OwnerAddressID: ownerAddress2.ID, | |
1033 | }).Count(&count) | |
1034 | if count != 1 { | |
1035 | t.Errorf("only one instance of (%d, %d) should be available, found: %d", | |
1036 | placeAddress.ID, ownerAddress2.ID, count) | |
1037 | } | |
1038 | ||
1039 | db.Model(&Place{}).Where(&Place{ | |
1040 | PlaceAddressID: placeAddress.ID, | |
1041 | }).Count(&count) | |
1042 | if count != 2 { | |
1043 | t.Errorf("two instances of (%d) should be available, found: %d", | |
1044 | placeAddress.ID, count) | |
1045 | } | |
1046 | } | |
1047 | ||
864 | 1048 | func TestBlockGlobalUpdate(t *testing.T) { |
865 | 1049 | db := DB.New() |
866 | 1050 | db.Create(&Toy{Name: "Stuffed Animal", OwnerType: "Nobody"}) |
897 | 1081 | if err != nil { |
898 | 1082 | t.Error("Unexpected error on conditional delete") |
899 | 1083 | } |
1084 | } | |
1085 | ||
1086 | func TestCountWithHaving(t *testing.T) { | |
1087 | db := DB.New() | |
1088 | db.Delete(User{}) | |
1089 | defer db.Delete(User{}) | |
1090 | ||
1091 | DB.Create(getPreparedUser("user1", "pluck_user")) | |
1092 | DB.Create(getPreparedUser("user2", "pluck_user")) | |
1093 | user3 := getPreparedUser("user3", "pluck_user") | |
1094 | user3.Languages = []Language{} | |
1095 | DB.Create(user3) | |
1096 | ||
1097 | var count int | |
1098 | err := db.Model(User{}).Select("users.id"). | |
1099 | Joins("LEFT JOIN user_languages ON user_languages.user_id = users.id"). | |
1100 | Joins("LEFT JOIN languages ON user_languages.language_id = languages.id"). | |
1101 | Group("users.id").Having("COUNT(languages.id) > 1").Count(&count).Error | |
1102 | ||
1103 | if err != nil { | |
1104 | t.Error("Unexpected error on query count with having") | |
1105 | } | |
1106 | ||
1107 | if count != 2 { | |
1108 | t.Error("Unexpected result on query count with having") | |
1109 | } | |
1110 | } | |
1111 | ||
1112 | func TestPluck(t *testing.T) { | |
1113 | db := DB.New() | |
1114 | db.Delete(User{}) | |
1115 | defer db.Delete(User{}) | |
1116 | ||
1117 | DB.Create(&User{Id: 1, Name: "user1"}) | |
1118 | DB.Create(&User{Id: 2, Name: "user2"}) | |
1119 | DB.Create(&User{Id: 3, Name: "user3"}) | |
1120 | ||
1121 | var ids []int64 | |
1122 | err := db.Model(User{}).Order("id").Pluck("id", &ids).Error | |
1123 | ||
1124 | if err != nil { | |
1125 | t.Error("Unexpected error on pluck") | |
1126 | } | |
1127 | ||
1128 | if len(ids) != 3 || ids[0] != 1 || ids[1] != 2 || ids[2] != 3 { | |
1129 | t.Error("Unexpected result on pluck") | |
1130 | } | |
1131 | ||
1132 | err = db.Model(User{}).Order("id").Pluck("id", &ids).Error | |
1133 | ||
1134 | if err != nil { | |
1135 | t.Error("Unexpected error on pluck again") | |
1136 | } | |
1137 | ||
1138 | if len(ids) != 3 || ids[0] != 1 || ids[1] != 2 || ids[2] != 3 { | |
1139 | t.Error("Unexpected result on pluck again") | |
1140 | } | |
1141 | } | |
1142 | ||
1143 | func TestCountWithQueryOption(t *testing.T) { | |
1144 | db := DB.New() | |
1145 | db.Delete(User{}) | |
1146 | defer db.Delete(User{}) | |
1147 | ||
1148 | DB.Create(&User{Name: "user1"}) | |
1149 | DB.Create(&User{Name: "user2"}) | |
1150 | DB.Create(&User{Name: "user3"}) | |
1151 | ||
1152 | var count int | |
1153 | err := db.Model(User{}).Select("users.id"). | |
1154 | Set("gorm:query_option", "WHERE users.name='user2'"). | |
1155 | Count(&count).Error | |
1156 | ||
1157 | if err != nil { | |
1158 | t.Error("Unexpected error on query count with query_option") | |
1159 | } | |
1160 | ||
1161 | if count != 1 { | |
1162 | t.Error("Unexpected result on query count with query_option") | |
1163 | } | |
1164 | } | |
1165 | ||
1166 | func TestFloatColumnPrecision(t *testing.T) { | |
1167 | if dialect := os.Getenv("GORM_DIALECT"); dialect != "mysql" && dialect != "sqlite" { | |
1168 | t.Skip() | |
1169 | } | |
1170 | ||
1171 | type FloatTest struct { | |
1172 | ID string `gorm:"primary_key"` | |
1173 | FloatValue float64 `gorm:"column:float_value" sql:"type:float(255,5);"` | |
1174 | } | |
1175 | DB.DropTable(&FloatTest{}) | |
1176 | DB.AutoMigrate(&FloatTest{}) | |
1177 | ||
1178 | data := FloatTest{ID: "uuid", FloatValue: 112.57315} | |
1179 | if err := DB.Save(&data).Error; err != nil || data.ID != "uuid" || data.FloatValue != 112.57315 { | |
1180 | t.Errorf("Float value should not lose precision") | |
1181 | } | |
1182 | } | |
1183 | ||
1184 | func TestWhereUpdates(t *testing.T) { | |
1185 | type OwnerEntity struct { | |
1186 | gorm.Model | |
1187 | OwnerID uint | |
1188 | OwnerType string | |
1189 | } | |
1190 | ||
1191 | type SomeEntity struct { | |
1192 | gorm.Model | |
1193 | Name string | |
1194 | OwnerEntity OwnerEntity `gorm:"polymorphic:Owner"` | |
1195 | } | |
1196 | ||
1197 | db := DB.Debug() | |
1198 | db.DropTable(&SomeEntity{}) | |
1199 | db.AutoMigrate(&SomeEntity{}) | |
1200 | ||
1201 | a := SomeEntity{Name: "test"} | |
1202 | db.Model(&a).Where(a).Updates(SomeEntity{Name: "test2"}) | |
900 | 1203 | } |
901 | 1204 | |
902 | 1205 | func BenchmarkGorm(b *testing.B) { |
117 | 117 | Owner *User `sql:"-"` |
118 | 118 | } |
119 | 119 | |
120 | type Place struct { | |
121 | Id int64 | |
122 | PlaceAddressID int | |
123 | PlaceAddress *Address `gorm:"save_associations:false"` | |
124 | OwnerAddressID int | |
125 | OwnerAddress *Address `gorm:"save_associations:true"` | |
126 | } | |
127 | ||
120 | 128 | type EncryptedData []byte |
121 | 129 | |
122 | 130 | func (data *EncryptedData) Scan(value interface{}) error { |
283 | 291 | DB.Exec(fmt.Sprintf("drop table %v;", table)) |
284 | 292 | } |
285 | 293 | |
286 | values := []interface{}{&Short{}, &ReallyLongThingThatReferencesShort{}, &ReallyLongTableNameToTestMySQLNameLengthLimit{}, &NotSoLongTableName{}, &Product{}, &Email{}, &Address{}, &CreditCard{}, &Company{}, &Role{}, &Language{}, &HNPost{}, &EngadgetPost{}, &Animal{}, &User{}, &JoinTable{}, &Post{}, &Category{}, &Comment{}, &Cat{}, &Dog{}, &Hamster{}, &Toy{}, &ElementWithIgnoredField{}} | |
294 | values := []interface{}{&Short{}, &ReallyLongThingThatReferencesShort{}, &ReallyLongTableNameToTestMySQLNameLengthLimit{}, &NotSoLongTableName{}, &Product{}, &Email{}, &Address{}, &CreditCard{}, &Company{}, &Role{}, &Language{}, &HNPost{}, &EngadgetPost{}, &Animal{}, &User{}, &JoinTable{}, &Post{}, &Category{}, &Comment{}, &Cat{}, &Dog{}, &Hamster{}, &Toy{}, &ElementWithIgnoredField{}, &Place{}} | |
287 | 295 | for _, value := range values { |
288 | 296 | DB.DropTable(value) |
289 | 297 | } |
397 | 405 | } |
398 | 406 | } |
399 | 407 | |
408 | func TestCreateAndAutomigrateTransaction(t *testing.T) { | |
409 | tx := DB.Begin() | |
410 | ||
411 | func() { | |
412 | type Bar struct { | |
413 | ID uint | |
414 | } | |
415 | DB.DropTableIfExists(&Bar{}) | |
416 | ||
417 | if ok := DB.HasTable("bars"); ok { | |
418 | t.Errorf("Table should not exist, but does") | |
419 | } | |
420 | ||
421 | if ok := tx.HasTable("bars"); ok { | |
422 | t.Errorf("Table should not exist, but does") | |
423 | } | |
424 | }() | |
425 | ||
426 | func() { | |
427 | type Bar struct { | |
428 | Name string | |
429 | } | |
430 | err := tx.CreateTable(&Bar{}).Error | |
431 | ||
432 | if err != nil { | |
433 | t.Errorf("Should have been able to create the table, but couldn't: %s", err) | |
434 | } | |
435 | ||
436 | if ok := tx.HasTable(&Bar{}); !ok { | |
437 | t.Errorf("The transaction should be able to see the table") | |
438 | } | |
439 | }() | |
440 | ||
441 | func() { | |
442 | type Bar struct { | |
443 | Stuff string | |
444 | } | |
445 | ||
446 | err := tx.AutoMigrate(&Bar{}).Error | |
447 | if err != nil { | |
448 | t.Errorf("Should have been able to alter the table, but couldn't") | |
449 | } | |
450 | }() | |
451 | ||
452 | tx.Rollback() | |
453 | } | |
454 | ||
400 | 455 | type MultipleIndexes struct { |
401 | 456 | ID int64 |
402 | 457 | UserID int64 `sql:"unique_index:uix_multipleindexes_user_name,uix_multipleindexes_user_email;index:idx_multipleindexes_user_other"` |
482 | 537 | t.Errorf("No error should happen when ModifyColumn, but got %v", err) |
483 | 538 | } |
484 | 539 | } |
540 | ||
541 | func TestIndexWithPrefixLength(t *testing.T) { | |
542 | if dialect := os.Getenv("GORM_DIALECT"); dialect != "mysql" { | |
543 | t.Skip("Skipping this because only mysql support setting an index prefix length") | |
544 | } | |
545 | ||
546 | type IndexWithPrefix struct { | |
547 | gorm.Model | |
548 | Name string | |
549 | Description string `gorm:"type:text;index:idx_index_with_prefixes_length(100)"` | |
550 | } | |
551 | type IndexesWithPrefix struct { | |
552 | gorm.Model | |
553 | Name string | |
554 | Description1 string `gorm:"type:text;index:idx_index_with_prefixes_length(100)"` | |
555 | Description2 string `gorm:"type:text;index:idx_index_with_prefixes_length(100)"` | |
556 | } | |
557 | type IndexesWithPrefixAndWithoutPrefix struct { | |
558 | gorm.Model | |
559 | Name string `gorm:"index:idx_index_with_prefixes_length"` | |
560 | Description string `gorm:"type:text;index:idx_index_with_prefixes_length(100)"` | |
561 | } | |
562 | tables := []interface{}{&IndexWithPrefix{}, &IndexesWithPrefix{}, &IndexesWithPrefixAndWithoutPrefix{}} | |
563 | for _, table := range tables { | |
564 | scope := DB.NewScope(table) | |
565 | tableName := scope.TableName() | |
566 | t.Run(fmt.Sprintf("Create index with prefix length: %s", tableName), func(t *testing.T) { | |
567 | if err := DB.DropTableIfExists(table).Error; err != nil { | |
568 | t.Errorf("Failed to drop %s table: %v", tableName, err) | |
569 | } | |
570 | if err := DB.CreateTable(table).Error; err != nil { | |
571 | t.Errorf("Failed to create %s table: %v", tableName, err) | |
572 | } | |
573 | if !scope.Dialect().HasIndex(tableName, "idx_index_with_prefixes_length") { | |
574 | t.Errorf("Failed to create %s table index:", tableName) | |
575 | } | |
576 | }) | |
577 | } | |
578 | } |
16 | 16 | return defaultTableName |
17 | 17 | } |
18 | 18 | |
19 | type safeModelStructsMap struct { | |
20 | m map[reflect.Type]*ModelStruct | |
21 | l *sync.RWMutex | |
22 | } | |
23 | ||
24 | func (s *safeModelStructsMap) Set(key reflect.Type, value *ModelStruct) { | |
19 | var modelStructsMap sync.Map | |
20 | ||
21 | // ModelStruct model definition | |
22 | type ModelStruct struct { | |
23 | PrimaryFields []*StructField | |
24 | StructFields []*StructField | |
25 | ModelType reflect.Type | |
26 | ||
27 | defaultTableName string | |
28 | l sync.Mutex | |
29 | } | |
30 | ||
31 | // TableName returns model's table name | |
32 | func (s *ModelStruct) TableName(db *DB) string { | |
25 | 33 | s.l.Lock() |
26 | 34 | defer s.l.Unlock() |
27 | s.m[key] = value | |
28 | } | |
29 | ||
30 | func (s *safeModelStructsMap) Get(key reflect.Type) *ModelStruct { | |
31 | s.l.RLock() | |
32 | defer s.l.RUnlock() | |
33 | return s.m[key] | |
34 | } | |
35 | ||
36 | func newModelStructsMap() *safeModelStructsMap { | |
37 | return &safeModelStructsMap{l: new(sync.RWMutex), m: make(map[reflect.Type]*ModelStruct)} | |
38 | } | |
39 | ||
40 | var modelStructsMap = newModelStructsMap() | |
41 | ||
42 | // ModelStruct model definition | |
43 | type ModelStruct struct { | |
44 | PrimaryFields []*StructField | |
45 | StructFields []*StructField | |
46 | ModelType reflect.Type | |
47 | defaultTableName string | |
48 | } | |
49 | ||
50 | // TableName get model's table name | |
51 | func (s *ModelStruct) TableName(db *DB) string { | |
35 | ||
52 | 36 | if s.defaultTableName == "" && db != nil && s.ModelType != nil { |
53 | 37 | // Set default table name |
54 | 38 | if tabler, ok := reflect.New(s.ModelType).Interface().(tabler); ok { |
55 | 39 | s.defaultTableName = tabler.TableName() |
56 | 40 | } else { |
57 | tableName := ToDBName(s.ModelType.Name()) | |
58 | if db == nil || !db.parent.singularTable { | |
41 | tableName := ToTableName(s.ModelType.Name()) | |
42 | db.parent.RLock() | |
43 | if db == nil || (db.parent != nil && !db.parent.singularTable) { | |
59 | 44 | tableName = inflection.Plural(tableName) |
60 | 45 | } |
46 | db.parent.RUnlock() | |
61 | 47 | s.defaultTableName = tableName |
62 | 48 | } |
63 | 49 | } |
80 | 66 | Struct reflect.StructField |
81 | 67 | IsForeignKey bool |
82 | 68 | Relationship *Relationship |
83 | } | |
84 | ||
85 | func (structField *StructField) clone() *StructField { | |
69 | ||
70 | tagSettingsLock sync.RWMutex | |
71 | } | |
72 | ||
73 | // TagSettingsSet Sets a tag in the tag settings map | |
74 | func (sf *StructField) TagSettingsSet(key, val string) { | |
75 | sf.tagSettingsLock.Lock() | |
76 | defer sf.tagSettingsLock.Unlock() | |
77 | sf.TagSettings[key] = val | |
78 | } | |
79 | ||
80 | // TagSettingsGet returns a tag from the tag settings | |
81 | func (sf *StructField) TagSettingsGet(key string) (string, bool) { | |
82 | sf.tagSettingsLock.RLock() | |
83 | defer sf.tagSettingsLock.RUnlock() | |
84 | val, ok := sf.TagSettings[key] | |
85 | return val, ok | |
86 | } | |
87 | ||
88 | // TagSettingsDelete deletes a tag | |
89 | func (sf *StructField) TagSettingsDelete(key string) { | |
90 | sf.tagSettingsLock.Lock() | |
91 | defer sf.tagSettingsLock.Unlock() | |
92 | delete(sf.TagSettings, key) | |
93 | } | |
94 | ||
95 | func (sf *StructField) clone() *StructField { | |
86 | 96 | clone := &StructField{ |
87 | DBName: structField.DBName, | |
88 | Name: structField.Name, | |
89 | Names: structField.Names, | |
90 | IsPrimaryKey: structField.IsPrimaryKey, | |
91 | IsNormal: structField.IsNormal, | |
92 | IsIgnored: structField.IsIgnored, | |
93 | IsScanner: structField.IsScanner, | |
94 | HasDefaultValue: structField.HasDefaultValue, | |
95 | Tag: structField.Tag, | |
97 | DBName: sf.DBName, | |
98 | Name: sf.Name, | |
99 | Names: sf.Names, | |
100 | IsPrimaryKey: sf.IsPrimaryKey, | |
101 | IsNormal: sf.IsNormal, | |
102 | IsIgnored: sf.IsIgnored, | |
103 | IsScanner: sf.IsScanner, | |
104 | HasDefaultValue: sf.HasDefaultValue, | |
105 | Tag: sf.Tag, | |
96 | 106 | TagSettings: map[string]string{}, |
97 | Struct: structField.Struct, | |
98 | IsForeignKey: structField.IsForeignKey, | |
99 | } | |
100 | ||
101 | if structField.Relationship != nil { | |
102 | relationship := *structField.Relationship | |
107 | Struct: sf.Struct, | |
108 | IsForeignKey: sf.IsForeignKey, | |
109 | } | |
110 | ||
111 | if sf.Relationship != nil { | |
112 | relationship := *sf.Relationship | |
103 | 113 | clone.Relationship = &relationship |
104 | 114 | } |
105 | 115 | |
106 | for key, value := range structField.TagSettings { | |
116 | // copy the struct field tagSettings, they should be read-locked while they are copied | |
117 | sf.tagSettingsLock.Lock() | |
118 | defer sf.tagSettingsLock.Unlock() | |
119 | for key, value := range sf.TagSettings { | |
107 | 120 | clone.TagSettings[key] = value |
108 | 121 | } |
109 | 122 | |
125 | 138 | |
126 | 139 | func getForeignField(column string, fields []*StructField) *StructField { |
127 | 140 | for _, field := range fields { |
128 | if field.Name == column || field.DBName == column || field.DBName == ToDBName(column) { | |
141 | if field.Name == column || field.DBName == column || field.DBName == ToColumnName(column) { | |
129 | 142 | return field |
130 | 143 | } |
131 | 144 | } |
151 | 164 | } |
152 | 165 | |
153 | 166 | // Get Cached model struct |
154 | if value := modelStructsMap.Get(reflectType); value != nil { | |
155 | return value | |
167 | isSingularTable := false | |
168 | if scope.db != nil && scope.db.parent != nil { | |
169 | scope.db.parent.RLock() | |
170 | isSingularTable = scope.db.parent.singularTable | |
171 | scope.db.parent.RUnlock() | |
172 | } | |
173 | ||
174 | hashKey := struct { | |
175 | singularTable bool | |
176 | reflectType reflect.Type | |
177 | }{isSingularTable, reflectType} | |
178 | if value, ok := modelStructsMap.Load(hashKey); ok && value != nil { | |
179 | return value.(*ModelStruct) | |
156 | 180 | } |
157 | 181 | |
158 | 182 | modelStruct.ModelType = reflectType |
169 | 193 | } |
170 | 194 | |
171 | 195 | // is ignored field |
172 | if _, ok := field.TagSettings["-"]; ok { | |
196 | if _, ok := field.TagSettingsGet("-"); ok { | |
173 | 197 | field.IsIgnored = true |
174 | 198 | } else { |
175 | if _, ok := field.TagSettings["PRIMARY_KEY"]; ok { | |
199 | if _, ok := field.TagSettingsGet("PRIMARY_KEY"); ok { | |
176 | 200 | field.IsPrimaryKey = true |
177 | 201 | modelStruct.PrimaryFields = append(modelStruct.PrimaryFields, field) |
178 | 202 | } |
179 | 203 | |
180 | if _, ok := field.TagSettings["DEFAULT"]; ok { | |
204 | if _, ok := field.TagSettingsGet("DEFAULT"); ok { | |
181 | 205 | field.HasDefaultValue = true |
182 | 206 | } |
183 | 207 | |
184 | if _, ok := field.TagSettings["AUTO_INCREMENT"]; ok && !field.IsPrimaryKey { | |
208 | if _, ok := field.TagSettingsGet("AUTO_INCREMENT"); ok && !field.IsPrimaryKey { | |
185 | 209 | field.HasDefaultValue = true |
186 | 210 | } |
187 | 211 | |
197 | 221 | if indirectType.Kind() == reflect.Struct { |
198 | 222 | for i := 0; i < indirectType.NumField(); i++ { |
199 | 223 | for key, value := range parseTagSetting(indirectType.Field(i).Tag) { |
200 | if _, ok := field.TagSettings[key]; !ok { | |
201 | field.TagSettings[key] = value | |
224 | if _, ok := field.TagSettingsGet(key); !ok { | |
225 | field.TagSettingsSet(key, value) | |
202 | 226 | } |
203 | 227 | } |
204 | 228 | } |
206 | 230 | } else if _, isTime := fieldValue.(*time.Time); isTime { |
207 | 231 | // is time |
208 | 232 | field.IsNormal = true |
209 | } else if _, ok := field.TagSettings["EMBEDDED"]; ok || fieldStruct.Anonymous { | |
233 | } else if _, ok := field.TagSettingsGet("EMBEDDED"); ok || fieldStruct.Anonymous { | |
210 | 234 | // is embedded struct |
211 | 235 | for _, subField := range scope.New(fieldValue).GetModelStruct().StructFields { |
212 | 236 | subField = subField.clone() |
213 | 237 | subField.Names = append([]string{fieldStruct.Name}, subField.Names...) |
214 | if prefix, ok := field.TagSettings["EMBEDDED_PREFIX"]; ok { | |
238 | if prefix, ok := field.TagSettingsGet("EMBEDDED_PREFIX"); ok { | |
215 | 239 | subField.DBName = prefix + subField.DBName |
216 | 240 | } |
217 | 241 | |
218 | 242 | if subField.IsPrimaryKey { |
219 | if _, ok := subField.TagSettings["PRIMARY_KEY"]; ok { | |
243 | if _, ok := subField.TagSettingsGet("PRIMARY_KEY"); ok { | |
220 | 244 | modelStruct.PrimaryFields = append(modelStruct.PrimaryFields, subField) |
221 | 245 | } else { |
222 | 246 | subField.IsPrimaryKey = false |
247 | 271 | elemType = field.Struct.Type |
248 | 272 | ) |
249 | 273 | |
250 | if foreignKey := field.TagSettings["FOREIGNKEY"]; foreignKey != "" { | |
274 | if foreignKey, _ := field.TagSettingsGet("FOREIGNKEY"); foreignKey != "" { | |
251 | 275 | foreignKeys = strings.Split(foreignKey, ",") |
252 | 276 | } |
253 | 277 | |
254 | if foreignKey := field.TagSettings["ASSOCIATION_FOREIGNKEY"]; foreignKey != "" { | |
278 | if foreignKey, _ := field.TagSettingsGet("ASSOCIATION_FOREIGNKEY"); foreignKey != "" { | |
255 | 279 | associationForeignKeys = strings.Split(foreignKey, ",") |
256 | } else if foreignKey := field.TagSettings["ASSOCIATIONFOREIGNKEY"]; foreignKey != "" { | |
280 | } else if foreignKey, _ := field.TagSettingsGet("ASSOCIATIONFOREIGNKEY"); foreignKey != "" { | |
257 | 281 | associationForeignKeys = strings.Split(foreignKey, ",") |
258 | 282 | } |
259 | 283 | |
262 | 286 | } |
263 | 287 | |
264 | 288 | if elemType.Kind() == reflect.Struct { |
265 | if many2many := field.TagSettings["MANY2MANY"]; many2many != "" { | |
289 | if many2many, _ := field.TagSettingsGet("MANY2MANY"); many2many != "" { | |
266 | 290 | relationship.Kind = "many_to_many" |
267 | 291 | |
268 | 292 | { // Foreign Keys for Source |
269 | 293 | joinTableDBNames := []string{} |
270 | 294 | |
271 | if foreignKey := field.TagSettings["JOINTABLE_FOREIGNKEY"]; foreignKey != "" { | |
295 | if foreignKey, _ := field.TagSettingsGet("JOINTABLE_FOREIGNKEY"); foreignKey != "" { | |
272 | 296 | joinTableDBNames = strings.Split(foreignKey, ",") |
273 | 297 | } |
274 | 298 | |
289 | 313 | // if defined join table's foreign key |
290 | 314 | relationship.ForeignDBNames = append(relationship.ForeignDBNames, joinTableDBNames[idx]) |
291 | 315 | } else { |
292 | defaultJointableForeignKey := ToDBName(reflectType.Name()) + "_" + foreignField.DBName | |
316 | defaultJointableForeignKey := ToColumnName(reflectType.Name()) + "_" + foreignField.DBName | |
293 | 317 | relationship.ForeignDBNames = append(relationship.ForeignDBNames, defaultJointableForeignKey) |
294 | 318 | } |
295 | 319 | } |
299 | 323 | { // Foreign Keys for Association (Destination) |
300 | 324 | associationJoinTableDBNames := []string{} |
301 | 325 | |
302 | if foreignKey := field.TagSettings["ASSOCIATION_JOINTABLE_FOREIGNKEY"]; foreignKey != "" { | |
326 | if foreignKey, _ := field.TagSettingsGet("ASSOCIATION_JOINTABLE_FOREIGNKEY"); foreignKey != "" { | |
303 | 327 | associationJoinTableDBNames = strings.Split(foreignKey, ",") |
304 | 328 | } |
305 | 329 | |
320 | 344 | relationship.AssociationForeignDBNames = append(relationship.AssociationForeignDBNames, associationJoinTableDBNames[idx]) |
321 | 345 | } else { |
322 | 346 | // join table foreign keys for association |
323 | joinTableDBName := ToDBName(elemType.Name()) + "_" + field.DBName | |
347 | joinTableDBName := ToColumnName(elemType.Name()) + "_" + field.DBName | |
324 | 348 | relationship.AssociationForeignDBNames = append(relationship.AssociationForeignDBNames, joinTableDBName) |
325 | 349 | } |
326 | 350 | } |
337 | 361 | var toFields = toScope.GetStructFields() |
338 | 362 | relationship.Kind = "has_many" |
339 | 363 | |
340 | if polymorphic := field.TagSettings["POLYMORPHIC"]; polymorphic != "" { | |
364 | if polymorphic, _ := field.TagSettingsGet("POLYMORPHIC"); polymorphic != "" { | |
341 | 365 | // Dog has many toys, tag polymorphic is Owner, then associationType is Owner |
342 | 366 | // Toy use OwnerID, OwnerType ('dogs') as foreign key |
343 | 367 | if polymorphicType := getForeignField(polymorphic+"Type", toFields); polymorphicType != nil { |
345 | 369 | relationship.PolymorphicType = polymorphicType.Name |
346 | 370 | relationship.PolymorphicDBName = polymorphicType.DBName |
347 | 371 | // if Dog has multiple set of toys set name of the set (instead of default 'dogs') |
348 | if value, ok := field.TagSettings["POLYMORPHIC_VALUE"]; ok { | |
372 | if value, ok := field.TagSettingsGet("POLYMORPHIC_VALUE"); ok { | |
349 | 373 | relationship.PolymorphicValue = value |
350 | 374 | } else { |
351 | 375 | relationship.PolymorphicValue = scope.TableName() |
427 | 451 | tagAssociationForeignKeys []string |
428 | 452 | ) |
429 | 453 | |
430 | if foreignKey := field.TagSettings["FOREIGNKEY"]; foreignKey != "" { | |
454 | if foreignKey, _ := field.TagSettingsGet("FOREIGNKEY"); foreignKey != "" { | |
431 | 455 | tagForeignKeys = strings.Split(foreignKey, ",") |
432 | 456 | } |
433 | 457 | |
434 | if foreignKey := field.TagSettings["ASSOCIATION_FOREIGNKEY"]; foreignKey != "" { | |
458 | if foreignKey, _ := field.TagSettingsGet("ASSOCIATION_FOREIGNKEY"); foreignKey != "" { | |
435 | 459 | tagAssociationForeignKeys = strings.Split(foreignKey, ",") |
436 | } else if foreignKey := field.TagSettings["ASSOCIATIONFOREIGNKEY"]; foreignKey != "" { | |
460 | } else if foreignKey, _ := field.TagSettingsGet("ASSOCIATIONFOREIGNKEY"); foreignKey != "" { | |
437 | 461 | tagAssociationForeignKeys = strings.Split(foreignKey, ",") |
438 | 462 | } |
439 | 463 | |
440 | if polymorphic := field.TagSettings["POLYMORPHIC"]; polymorphic != "" { | |
464 | if polymorphic, _ := field.TagSettingsGet("POLYMORPHIC"); polymorphic != "" { | |
441 | 465 | // Cat has one toy, tag polymorphic is Owner, then associationType is Owner |
442 | 466 | // Toy use OwnerID, OwnerType ('cats') as foreign key |
443 | 467 | if polymorphicType := getForeignField(polymorphic+"Type", toFields); polymorphicType != nil { |
445 | 469 | relationship.PolymorphicType = polymorphicType.Name |
446 | 470 | relationship.PolymorphicDBName = polymorphicType.DBName |
447 | 471 | // if Cat has several different types of toys set name for each (instead of default 'cats') |
448 | if value, ok := field.TagSettings["POLYMORPHIC_VALUE"]; ok { | |
472 | if value, ok := field.TagSettingsGet("POLYMORPHIC_VALUE"); ok { | |
449 | 473 | relationship.PolymorphicValue = value |
450 | 474 | } else { |
451 | 475 | relationship.PolymorphicValue = scope.TableName() |
583 | 607 | } |
584 | 608 | |
585 | 609 | // Even it is ignored, also possible to decode db value into the field |
586 | if value, ok := field.TagSettings["COLUMN"]; ok { | |
610 | if value, ok := field.TagSettingsGet("COLUMN"); ok { | |
587 | 611 | field.DBName = value |
588 | 612 | } else { |
589 | field.DBName = ToDBName(fieldStruct.Name) | |
613 | field.DBName = ToColumnName(fieldStruct.Name) | |
590 | 614 | } |
591 | 615 | |
592 | 616 | modelStruct.StructFields = append(modelStruct.StructFields, field) |
600 | 624 | } |
601 | 625 | } |
602 | 626 | |
603 | modelStructsMap.Set(reflectType, &modelStruct) | |
627 | modelStructsMap.Store(hashKey, &modelStruct) | |
604 | 628 | |
605 | 629 | return &modelStruct |
606 | 630 | } |
613 | 637 | func parseTagSetting(tags reflect.StructTag) map[string]string { |
614 | 638 | setting := map[string]string{} |
615 | 639 | for _, str := range []string{tags.Get("sql"), tags.Get("gorm")} { |
640 | if str == "" { | |
641 | continue | |
642 | } | |
616 | 643 | tags := strings.Split(str, ";") |
617 | 644 | for _, value := range tags { |
618 | 645 | v := strings.Split(value, ":") |
0 | package gorm | |
1 | ||
2 | import ( | |
3 | "bytes" | |
4 | "strings" | |
5 | ) | |
6 | ||
7 | // Namer is a function type which is given a string and return a string | |
8 | type Namer func(string) string | |
9 | ||
10 | // NamingStrategy represents naming strategies | |
11 | type NamingStrategy struct { | |
12 | DB Namer | |
13 | Table Namer | |
14 | Column Namer | |
15 | } | |
16 | ||
17 | // TheNamingStrategy is being initialized with defaultNamingStrategy | |
18 | var TheNamingStrategy = &NamingStrategy{ | |
19 | DB: defaultNamer, | |
20 | Table: defaultNamer, | |
21 | Column: defaultNamer, | |
22 | } | |
23 | ||
24 | // AddNamingStrategy sets the naming strategy | |
25 | func AddNamingStrategy(ns *NamingStrategy) { | |
26 | if ns.DB == nil { | |
27 | ns.DB = defaultNamer | |
28 | } | |
29 | if ns.Table == nil { | |
30 | ns.Table = defaultNamer | |
31 | } | |
32 | if ns.Column == nil { | |
33 | ns.Column = defaultNamer | |
34 | } | |
35 | TheNamingStrategy = ns | |
36 | } | |
37 | ||
38 | // DBName alters the given name by DB | |
39 | func (ns *NamingStrategy) DBName(name string) string { | |
40 | return ns.DB(name) | |
41 | } | |
42 | ||
43 | // TableName alters the given name by Table | |
44 | func (ns *NamingStrategy) TableName(name string) string { | |
45 | return ns.Table(name) | |
46 | } | |
47 | ||
48 | // ColumnName alters the given name by Column | |
49 | func (ns *NamingStrategy) ColumnName(name string) string { | |
50 | return ns.Column(name) | |
51 | } | |
52 | ||
53 | // ToDBName convert string to db name | |
54 | func ToDBName(name string) string { | |
55 | return TheNamingStrategy.DBName(name) | |
56 | } | |
57 | ||
58 | // ToTableName convert string to table name | |
59 | func ToTableName(name string) string { | |
60 | return TheNamingStrategy.TableName(name) | |
61 | } | |
62 | ||
63 | // ToColumnName convert string to db name | |
64 | func ToColumnName(name string) string { | |
65 | return TheNamingStrategy.ColumnName(name) | |
66 | } | |
67 | ||
68 | var smap = newSafeMap() | |
69 | ||
70 | func defaultNamer(name string) string { | |
71 | const ( | |
72 | lower = false | |
73 | upper = true | |
74 | ) | |
75 | ||
76 | if v := smap.Get(name); v != "" { | |
77 | return v | |
78 | } | |
79 | ||
80 | if name == "" { | |
81 | return "" | |
82 | } | |
83 | ||
84 | var ( | |
85 | value = commonInitialismsReplacer.Replace(name) | |
86 | buf = bytes.NewBufferString("") | |
87 | lastCase, currCase, nextCase, nextNumber bool | |
88 | ) | |
89 | ||
90 | for i, v := range value[:len(value)-1] { | |
91 | nextCase = bool(value[i+1] >= 'A' && value[i+1] <= 'Z') | |
92 | nextNumber = bool(value[i+1] >= '0' && value[i+1] <= '9') | |
93 | ||
94 | if i > 0 { | |
95 | if currCase == upper { | |
96 | if lastCase == upper && (nextCase == upper || nextNumber == upper) { | |
97 | buf.WriteRune(v) | |
98 | } else { | |
99 | if value[i-1] != '_' && value[i+1] != '_' { | |
100 | buf.WriteRune('_') | |
101 | } | |
102 | buf.WriteRune(v) | |
103 | } | |
104 | } else { | |
105 | buf.WriteRune(v) | |
106 | if i == len(value)-2 && (nextCase == upper && nextNumber == lower) { | |
107 | buf.WriteRune('_') | |
108 | } | |
109 | } | |
110 | } else { | |
111 | currCase = upper | |
112 | buf.WriteRune(v) | |
113 | } | |
114 | lastCase = currCase | |
115 | currCase = nextCase | |
116 | } | |
117 | ||
118 | buf.WriteByte(value[len(value)-1]) | |
119 | ||
120 | s := strings.ToLower(buf.String()) | |
121 | smap.Set(name, s) | |
122 | return s | |
123 | } |
0 | package gorm_test | |
1 | ||
2 | import ( | |
3 | "testing" | |
4 | ||
5 | "github.com/jinzhu/gorm" | |
6 | ) | |
7 | ||
8 | func TestTheNamingStrategy(t *testing.T) { | |
9 | ||
10 | cases := []struct { | |
11 | name string | |
12 | namer gorm.Namer | |
13 | expected string | |
14 | }{ | |
15 | {name: "auth", expected: "auth", namer: gorm.TheNamingStrategy.DB}, | |
16 | {name: "userRestrictions", expected: "user_restrictions", namer: gorm.TheNamingStrategy.Table}, | |
17 | {name: "clientID", expected: "client_id", namer: gorm.TheNamingStrategy.Column}, | |
18 | } | |
19 | ||
20 | for _, c := range cases { | |
21 | t.Run(c.name, func(t *testing.T) { | |
22 | result := c.namer(c.name) | |
23 | if result != c.expected { | |
24 | t.Errorf("error in naming strategy. expected: %v got :%v\n", c.expected, result) | |
25 | } | |
26 | }) | |
27 | } | |
28 | ||
29 | } | |
30 | ||
31 | func TestNamingStrategy(t *testing.T) { | |
32 | ||
33 | dbNameNS := func(name string) string { | |
34 | return "db_" + name | |
35 | } | |
36 | tableNameNS := func(name string) string { | |
37 | return "tbl_" + name | |
38 | } | |
39 | columnNameNS := func(name string) string { | |
40 | return "col_" + name | |
41 | } | |
42 | ||
43 | ns := &gorm.NamingStrategy{ | |
44 | DB: dbNameNS, | |
45 | Table: tableNameNS, | |
46 | Column: columnNameNS, | |
47 | } | |
48 | ||
49 | cases := []struct { | |
50 | name string | |
51 | namer gorm.Namer | |
52 | expected string | |
53 | }{ | |
54 | {name: "auth", expected: "db_auth", namer: ns.DB}, | |
55 | {name: "user", expected: "tbl_user", namer: ns.Table}, | |
56 | {name: "password", expected: "col_password", namer: ns.Column}, | |
57 | } | |
58 | ||
59 | for _, c := range cases { | |
60 | t.Run(c.name, func(t *testing.T) { | |
61 | result := c.namer(c.name) | |
62 | if result != c.expected { | |
63 | t.Errorf("error in naming strategy. expected: %v got :%v\n", c.expected, result) | |
64 | } | |
65 | }) | |
66 | } | |
67 | ||
68 | } |
122 | 122 | } |
123 | 123 | } |
124 | 124 | |
125 | func TestAutoPreloadFalseDoesntPreload(t *testing.T) { | |
126 | user1 := getPreloadUser("auto_user1") | |
127 | DB.Save(user1) | |
128 | ||
129 | preloadDB := DB.Set("gorm:auto_preload", false).Where("role = ?", "Preload") | |
130 | var user User | |
131 | preloadDB.Find(&user) | |
132 | ||
133 | if user.BillingAddress.Address1 != "" { | |
134 | t.Error("AutoPreload was set to fasle, but still fetched data") | |
135 | } | |
136 | ||
137 | user2 := getPreloadUser("auto_user2") | |
138 | DB.Save(user2) | |
139 | ||
140 | var users []User | |
141 | preloadDB.Find(&users) | |
142 | ||
143 | for _, user := range users { | |
144 | if user.BillingAddress.Address1 != "" { | |
145 | t.Error("AutoPreload was set to fasle, but still fetched data") | |
146 | } | |
147 | } | |
148 | } | |
149 | ||
125 | 150 | func TestNestedPreload1(t *testing.T) { |
126 | 151 | type ( |
127 | 152 | Level1 struct { |
745 | 770 | levelB3 := &LevelB3{ |
746 | 771 | Value: "bar", |
747 | 772 | LevelB1ID: sql.NullInt64{Valid: true, Int64: int64(levelB1.ID)}, |
773 | LevelB2s: []*LevelB2{}, | |
748 | 774 | } |
749 | 775 | if err := DB.Create(levelB3).Error; err != nil { |
750 | 776 | t.Error(err) |
1650 | 1676 | lvl := Level1{ |
1651 | 1677 | Name: "l1", |
1652 | 1678 | Level2s: []Level2{ |
1653 | Level2{Name: "l2-1"}, Level2{Name: "l2-2"}, | |
1679 | {Name: "l2-1"}, {Name: "l2-2"}, | |
1654 | 1680 | }, |
1655 | 1681 | } |
1656 | 1682 | DB.Save(&lvl) |
180 | 180 | |
181 | 181 | scopedb.Where("birthday > ?", parseTime("2000-1-1")).Find(&users) |
182 | 182 | if len(users) != 2 { |
183 | t.Errorf("Should found 2 users's birthday > 2000-1-1, but got %v", len(users)) | |
183 | t.Errorf("Should found 2 users' birthday > 2000-1-1, but got %v", len(users)) | |
184 | 184 | } |
185 | 185 | |
186 | 186 | scopedb.Where("birthday > ?", "2002-10-10").Find(&users) |
187 | 187 | if len(users) != 2 { |
188 | t.Errorf("Should found 2 users's birthday >= 2002-10-10, but got %v", len(users)) | |
188 | t.Errorf("Should found 2 users' birthday >= 2002-10-10, but got %v", len(users)) | |
189 | 189 | } |
190 | 190 | |
191 | 191 | scopedb.Where("birthday >= ?", "2010-1-1").Where("birthday < ?", "2020-1-1").Find(&users) |
192 | 192 | if len(users) != 1 { |
193 | t.Errorf("Should found 1 users's birthday < 2020-1-1 and >= 2010-1-1, but got %v", len(users)) | |
193 | t.Errorf("Should found 1 users' birthday < 2020-1-1 and >= 2010-1-1, but got %v", len(users)) | |
194 | 194 | } |
195 | 195 | |
196 | 196 | DB.Where("name in (?)", []string{user1.Name, user2.Name}).Find(&users) |
531 | 531 | DB.Table("users").Where("name = ?", "user3").Count(&name3Count) |
532 | 532 | DB.Not("name", "user3").Find(&users4) |
533 | 533 | if len(users1)-len(users4) != int(name3Count) { |
534 | t.Errorf("Should find all users's name not equal 3") | |
534 | t.Errorf("Should find all users' name not equal 3") | |
535 | 535 | } |
536 | 536 | |
537 | 537 | DB.Not("name = ?", "user3").Find(&users4) |
538 | 538 | if len(users1)-len(users4) != int(name3Count) { |
539 | t.Errorf("Should find all users's name not equal 3") | |
539 | t.Errorf("Should find all users' name not equal 3") | |
540 | 540 | } |
541 | 541 | |
542 | 542 | DB.Not("name <> ?", "user3").Find(&users4) |
543 | 543 | if len(users4) != int(name3Count) { |
544 | t.Errorf("Should find all users's name not equal 3") | |
544 | t.Errorf("Should find all users' name not equal 3") | |
545 | 545 | } |
546 | 546 | |
547 | 547 | DB.Not(User{Name: "user3"}).Find(&users5) |
548 | 548 | |
549 | 549 | if len(users1)-len(users5) != int(name3Count) { |
550 | t.Errorf("Should find all users's name not equal 3") | |
550 | t.Errorf("Should find all users' name not equal 3") | |
551 | 551 | } |
552 | 552 | |
553 | 553 | DB.Not(map[string]interface{}{"name": "user3"}).Find(&users6) |
554 | 554 | if len(users1)-len(users6) != int(name3Count) { |
555 | t.Errorf("Should find all users's name not equal 3") | |
555 | t.Errorf("Should find all users' name not equal 3") | |
556 | 556 | } |
557 | 557 | |
558 | 558 | DB.Not(map[string]interface{}{"name": "user3", "company_id": nil}).Find(&users7) |
562 | 562 | |
563 | 563 | DB.Not("name", []string{"user3"}).Find(&users8) |
564 | 564 | if len(users1)-len(users8) != int(name3Count) { |
565 | t.Errorf("Should find all users's name not equal 3") | |
565 | t.Errorf("Should find all users' name not equal 3") | |
566 | 566 | } |
567 | 567 | |
568 | 568 | var name2Count int64 |
569 | 569 | DB.Table("users").Where("name = ?", "user2").Count(&name2Count) |
570 | 570 | DB.Not("name", []string{"user3", "user2"}).Find(&users9) |
571 | 571 | if len(users1)-len(users9) != (int(name3Count) + int(name2Count)) { |
572 | t.Errorf("Should find all users's name not equal 3") | |
572 | t.Errorf("Should find all users' name not equal 3") | |
573 | 573 | } |
574 | 574 | } |
575 | 575 |
62 | 62 | |
63 | 63 | // Dialect get dialect |
64 | 64 | func (scope *Scope) Dialect() Dialect { |
65 | return scope.db.parent.dialect | |
65 | return scope.db.dialect | |
66 | 66 | } |
67 | 67 | |
68 | 68 | // Quote used to quote string to escape them for database |
69 | 69 | func (scope *Scope) Quote(str string) string { |
70 | if strings.Index(str, ".") != -1 { | |
70 | if strings.Contains(str, ".") { | |
71 | 71 | newStrs := []string{} |
72 | 72 | for _, str := range strings.Split(str, ".") { |
73 | 73 | newStrs = append(newStrs, scope.Dialect().Quote(str)) |
133 | 133 | // FieldByName find `gorm.Field` with field name or db name |
134 | 134 | func (scope *Scope) FieldByName(name string) (field *Field, ok bool) { |
135 | 135 | var ( |
136 | dbName = ToDBName(name) | |
136 | dbName = ToColumnName(name) | |
137 | 137 | mostMatchedField *Field |
138 | 138 | ) |
139 | 139 | |
329 | 329 | // QuotedTableName return quoted table name |
330 | 330 | func (scope *Scope) QuotedTableName() (name string) { |
331 | 331 | if scope.Search != nil && len(scope.Search.tableName) > 0 { |
332 | if strings.Index(scope.Search.tableName, " ") != -1 { | |
332 | if strings.Contains(scope.Search.tableName, " ") { | |
333 | 333 | return scope.Search.tableName |
334 | 334 | } |
335 | 335 | return scope.Quote(scope.Search.tableName) |
485 | 485 | values[index] = &ignored |
486 | 486 | |
487 | 487 | selectFields = fields |
488 | offset := 0 | |
488 | 489 | if idx, ok := selectedColumnsMap[column]; ok { |
489 | selectFields = selectFields[idx+1:] | |
490 | offset = idx + 1 | |
491 | selectFields = selectFields[offset:] | |
490 | 492 | } |
491 | 493 | |
492 | 494 | for fieldIndex, field := range selectFields { |
500 | 502 | resetFields[index] = field |
501 | 503 | } |
502 | 504 | |
503 | selectedColumnsMap[column] = fieldIndex | |
505 | selectedColumnsMap[column] = offset + fieldIndex | |
504 | 506 | |
505 | 507 | if field.IsNormal { |
506 | 508 | break |
585 | 587 | scope.Err(fmt.Errorf("invalid query condition: %v", value)) |
586 | 588 | return |
587 | 589 | } |
588 | ||
590 | scopeQuotedTableName := newScope.QuotedTableName() | |
589 | 591 | for _, field := range newScope.Fields() { |
590 | 592 | if !field.IsIgnored && !field.IsBlank { |
591 | sqls = append(sqls, fmt.Sprintf("(%v.%v %s %v)", quotedTableName, scope.Quote(field.DBName), equalSQL, scope.AddToVars(field.Field.Interface()))) | |
593 | sqls = append(sqls, fmt.Sprintf("(%v.%v %s %v)", scopeQuotedTableName, scope.Quote(field.DBName), equalSQL, scope.AddToVars(field.Field.Interface()))) | |
592 | 594 | } |
593 | 595 | } |
594 | 596 | return strings.Join(sqls, " AND ") |
691 | 693 | |
692 | 694 | buff := bytes.NewBuffer([]byte{}) |
693 | 695 | i := 0 |
694 | for pos := range str { | |
696 | for pos, char := range str { | |
695 | 697 | if str[pos] == '?' { |
696 | 698 | buff.WriteString(replacements[i]) |
697 | 699 | i++ |
698 | 700 | } else { |
699 | buff.WriteByte(str[pos]) | |
701 | buff.WriteRune(char) | |
700 | 702 | } |
701 | 703 | } |
702 | 704 | |
852 | 854 | } |
853 | 855 | |
854 | 856 | func (scope *Scope) callCallbacks(funcs []*func(s *Scope)) *Scope { |
857 | defer func() { | |
858 | if err := recover(); err != nil { | |
859 | if db, ok := scope.db.db.(sqlTx); ok { | |
860 | db.Rollback() | |
861 | } | |
862 | panic(err) | |
863 | } | |
864 | }() | |
855 | 865 | for _, f := range funcs { |
856 | 866 | (*f)(scope) |
857 | 867 | if scope.skipLeft { |
861 | 871 | return scope |
862 | 872 | } |
863 | 873 | |
864 | func convertInterfaceToMap(values interface{}, withIgnoredField bool) map[string]interface{} { | |
874 | func convertInterfaceToMap(values interface{}, withIgnoredField bool, db *DB) map[string]interface{} { | |
865 | 875 | var attrs = map[string]interface{}{} |
866 | 876 | |
867 | 877 | switch value := values.(type) { |
869 | 879 | return value |
870 | 880 | case []interface{}: |
871 | 881 | for _, v := range value { |
872 | for key, value := range convertInterfaceToMap(v, withIgnoredField) { | |
882 | for key, value := range convertInterfaceToMap(v, withIgnoredField, db) { | |
873 | 883 | attrs[key] = value |
874 | 884 | } |
875 | 885 | } |
879 | 889 | switch reflectValue.Kind() { |
880 | 890 | case reflect.Map: |
881 | 891 | for _, key := range reflectValue.MapKeys() { |
882 | attrs[ToDBName(key.Interface().(string))] = reflectValue.MapIndex(key).Interface() | |
892 | attrs[ToColumnName(key.Interface().(string))] = reflectValue.MapIndex(key).Interface() | |
883 | 893 | } |
884 | 894 | default: |
885 | for _, field := range (&Scope{Value: values}).Fields() { | |
895 | for _, field := range (&Scope{Value: values, db: db}).Fields() { | |
886 | 896 | if !field.IsBlank && (withIgnoredField || !field.IsIgnored) { |
887 | 897 | attrs[field.DBName] = field.Field.Interface() |
888 | 898 | } |
894 | 904 | |
895 | 905 | func (scope *Scope) updatedAttrsWithValues(value interface{}) (results map[string]interface{}, hasUpdate bool) { |
896 | 906 | if scope.IndirectValue().Kind() != reflect.Struct { |
897 | return convertInterfaceToMap(value, false), true | |
907 | return convertInterfaceToMap(value, false, scope.db), true | |
898 | 908 | } |
899 | 909 | |
900 | 910 | results = map[string]interface{}{} |
901 | 911 | |
902 | for key, value := range convertInterfaceToMap(value, true) { | |
912 | for key, value := range convertInterfaceToMap(value, true, scope.db) { | |
903 | 913 | if field, ok := scope.FieldByName(key); ok && scope.changeableField(field) { |
904 | 914 | if _, ok := value.(*expr); ok { |
905 | 915 | hasUpdate = true |
906 | 916 | results[field.DBName] = value |
907 | 917 | } else { |
908 | 918 | err := field.Set(value) |
909 | if field.IsNormal { | |
919 | if field.IsNormal && !field.IsIgnored { | |
910 | 920 | hasUpdate = true |
911 | 921 | if err == ErrUnaddressable { |
912 | 922 | results[field.DBName] = value |
971 | 981 | if dest.Kind() != reflect.Slice { |
972 | 982 | scope.Err(fmt.Errorf("results should be a slice, not %s", dest.Kind())) |
973 | 983 | return scope |
984 | } | |
985 | ||
986 | if dest.Len() > 0 { | |
987 | dest.Set(reflect.Zero(dest.Type())) | |
974 | 988 | } |
975 | 989 | |
976 | 990 | if query, ok := scope.Search.selects["query"]; !ok || !scope.isQueryForColumn(query, column) { |
996 | 1010 | func (scope *Scope) count(value interface{}) *Scope { |
997 | 1011 | if query, ok := scope.Search.selects["query"]; !ok || !countingQueryRegexp.MatchString(fmt.Sprint(query)) { |
998 | 1012 | if len(scope.Search.group) != 0 { |
999 | scope.Search.Select("count(*) FROM ( SELECT count(*) as name ") | |
1000 | scope.Search.group += " ) AS count_table" | |
1013 | if len(scope.Search.havingConditions) != 0 { | |
1014 | scope.prepareQuerySQL() | |
1015 | scope.Search = &search{} | |
1016 | scope.Search.Select("count(*)") | |
1017 | scope.Search.Table(fmt.Sprintf("( %s ) AS count_table", scope.SQL)) | |
1018 | } else { | |
1019 | scope.Search.Select("count(*) FROM ( SELECT count(*) as name ") | |
1020 | scope.Search.group += " ) AS count_table" | |
1021 | } | |
1001 | 1022 | } else { |
1002 | 1023 | scope.Search.Select("count(*)") |
1003 | 1024 | } |
1112 | 1133 | if field, ok := scope.FieldByName(fieldName); ok { |
1113 | 1134 | foreignKeyStruct := field.clone() |
1114 | 1135 | foreignKeyStruct.IsPrimaryKey = false |
1115 | foreignKeyStruct.TagSettings["IS_JOINTABLE_FOREIGNKEY"] = "true" | |
1116 | delete(foreignKeyStruct.TagSettings, "AUTO_INCREMENT") | |
1136 | foreignKeyStruct.TagSettingsSet("IS_JOINTABLE_FOREIGNKEY", "true") | |
1137 | foreignKeyStruct.TagSettingsDelete("AUTO_INCREMENT") | |
1117 | 1138 | sqlTypes = append(sqlTypes, scope.Quote(relationship.ForeignDBNames[idx])+" "+scope.Dialect().DataTypeOf(foreignKeyStruct)) |
1118 | 1139 | primaryKeys = append(primaryKeys, scope.Quote(relationship.ForeignDBNames[idx])) |
1119 | 1140 | } |
1123 | 1144 | if field, ok := toScope.FieldByName(fieldName); ok { |
1124 | 1145 | foreignKeyStruct := field.clone() |
1125 | 1146 | foreignKeyStruct.IsPrimaryKey = false |
1126 | foreignKeyStruct.TagSettings["IS_JOINTABLE_FOREIGNKEY"] = "true" | |
1127 | delete(foreignKeyStruct.TagSettings, "AUTO_INCREMENT") | |
1147 | foreignKeyStruct.TagSettingsSet("IS_JOINTABLE_FOREIGNKEY", "true") | |
1148 | foreignKeyStruct.TagSettingsDelete("AUTO_INCREMENT") | |
1128 | 1149 | sqlTypes = append(sqlTypes, scope.Quote(relationship.AssociationForeignDBNames[idx])+" "+scope.Dialect().DataTypeOf(foreignKeyStruct)) |
1129 | 1150 | primaryKeys = append(primaryKeys, scope.Quote(relationship.AssociationForeignDBNames[idx])) |
1130 | 1151 | } |
1172 | 1193 | } |
1173 | 1194 | |
1174 | 1195 | func (scope *Scope) dropTable() *Scope { |
1175 | scope.Raw(fmt.Sprintf("DROP TABLE %v%s", scope.QuotedTableName(), scope.getTableOptions())).Exec() | |
1196 | scope.Raw(fmt.Sprintf("DROP TABLE %v", scope.QuotedTableName())).Exec() | |
1176 | 1197 | return scope |
1177 | 1198 | } |
1178 | 1199 | |
1214 | 1235 | } |
1215 | 1236 | |
1216 | 1237 | func (scope *Scope) removeForeignKey(field string, dest string) { |
1217 | keyName := scope.Dialect().BuildKeyName(scope.TableName(), field, dest) | |
1218 | ||
1238 | keyName := scope.Dialect().BuildKeyName(scope.TableName(), field, dest, "foreign") | |
1219 | 1239 | if !scope.Dialect().HasForeignKey(scope.TableName(), keyName) { |
1220 | 1240 | return |
1221 | 1241 | } |
1222 | var query = `ALTER TABLE %s DROP CONSTRAINT %s;` | |
1242 | var mysql mysql | |
1243 | var query string | |
1244 | if scope.Dialect().GetName() == mysql.GetName() { | |
1245 | query = `ALTER TABLE %s DROP FOREIGN KEY %s;` | |
1246 | } else { | |
1247 | query = `ALTER TABLE %s DROP CONSTRAINT %s;` | |
1248 | } | |
1249 | ||
1223 | 1250 | scope.Raw(fmt.Sprintf(query, scope.QuotedTableName(), scope.quoteIfPossible(keyName))).Exec() |
1224 | 1251 | } |
1225 | 1252 | |
1253 | 1280 | var uniqueIndexes = map[string][]string{} |
1254 | 1281 | |
1255 | 1282 | for _, field := range scope.GetStructFields() { |
1256 | if name, ok := field.TagSettings["INDEX"]; ok { | |
1283 | if name, ok := field.TagSettingsGet("INDEX"); ok { | |
1257 | 1284 | names := strings.Split(name, ",") |
1258 | 1285 | |
1259 | 1286 | for _, name := range names { |
1260 | 1287 | if name == "INDEX" || name == "" { |
1261 | 1288 | name = scope.Dialect().BuildKeyName("idx", scope.TableName(), field.DBName) |
1262 | 1289 | } |
1263 | indexes[name] = append(indexes[name], field.DBName) | |
1264 | } | |
1265 | } | |
1266 | ||
1267 | if name, ok := field.TagSettings["UNIQUE_INDEX"]; ok { | |
1290 | name, column := scope.Dialect().NormalizeIndexAndColumn(name, field.DBName) | |
1291 | indexes[name] = append(indexes[name], column) | |
1292 | } | |
1293 | } | |
1294 | ||
1295 | if name, ok := field.TagSettingsGet("UNIQUE_INDEX"); ok { | |
1268 | 1296 | names := strings.Split(name, ",") |
1269 | 1297 | |
1270 | 1298 | for _, name := range names { |
1271 | 1299 | if name == "UNIQUE_INDEX" || name == "" { |
1272 | 1300 | name = scope.Dialect().BuildKeyName("uix", scope.TableName(), field.DBName) |
1273 | 1301 | } |
1274 | uniqueIndexes[name] = append(uniqueIndexes[name], field.DBName) | |
1302 | name, column := scope.Dialect().NormalizeIndexAndColumn(name, field.DBName) | |
1303 | uniqueIndexes[name] = append(uniqueIndexes[name], column) | |
1275 | 1304 | } |
1276 | 1305 | } |
1277 | 1306 | } |
1292 | 1321 | } |
1293 | 1322 | |
1294 | 1323 | func (scope *Scope) getColumnAsArray(columns []string, values ...interface{}) (results [][]interface{}) { |
1324 | resultMap := make(map[string][]interface{}) | |
1295 | 1325 | for _, value := range values { |
1296 | 1326 | indirectValue := indirect(reflect.ValueOf(value)) |
1297 | 1327 | |
1310 | 1340 | } |
1311 | 1341 | |
1312 | 1342 | if hasValue { |
1313 | results = append(results, result) | |
1343 | h := fmt.Sprint(result...) | |
1344 | if _, exist := resultMap[h]; !exist { | |
1345 | resultMap[h] = result | |
1346 | } | |
1314 | 1347 | } |
1315 | 1348 | } |
1316 | 1349 | case reflect.Struct: |
1325 | 1358 | } |
1326 | 1359 | |
1327 | 1360 | if hasValue { |
1328 | results = append(results, result) | |
1329 | } | |
1330 | } | |
1331 | } | |
1332 | ||
1361 | h := fmt.Sprint(result...) | |
1362 | if _, exist := resultMap[h]; !exist { | |
1363 | resultMap[h] = result | |
1364 | } | |
1365 | } | |
1366 | } | |
1367 | } | |
1368 | for _, v := range resultMap { | |
1369 | results = append(results, v) | |
1370 | } | |
1333 | 1371 | return |
1334 | 1372 | } |
1335 | 1373 |
77 | 77 | t.Errorf("The error should be returned from Valuer, but get %v", err) |
78 | 78 | } |
79 | 79 | } |
80 | ||
81 | func TestDropTableWithTableOptions(t *testing.T) { | |
82 | type UserWithOptions struct { | |
83 | gorm.Model | |
84 | } | |
85 | DB.AutoMigrate(&UserWithOptions{}) | |
86 | ||
87 | DB = DB.Set("gorm:table_options", "CHARSET=utf8") | |
88 | err := DB.DropTable(&UserWithOptions{}).Error | |
89 | if err != nil { | |
90 | t.Errorf("Table must be dropped, got error %s", err) | |
91 | } | |
92 | } |
0 | 0 | package gorm |
1 | 1 | |
2 | 2 | import ( |
3 | "bytes" | |
4 | 3 | "database/sql/driver" |
5 | 4 | "fmt" |
6 | 5 | "reflect" |
25 | 24 | var commonInitialisms = []string{"API", "ASCII", "CPU", "CSS", "DNS", "EOF", "GUID", "HTML", "HTTP", "HTTPS", "ID", "IP", "JSON", "LHS", "QPS", "RAM", "RHS", "RPC", "SLA", "SMTP", "SSH", "TLS", "TTL", "UID", "UI", "UUID", "URI", "URL", "UTF8", "VM", "XML", "XSRF", "XSS"} |
26 | 25 | var commonInitialismsReplacer *strings.Replacer |
27 | 26 | |
28 | var goSrcRegexp = regexp.MustCompile(`jinzhu/gorm/.*.go`) | |
29 | var goTestRegexp = regexp.MustCompile(`jinzhu/gorm/.*test.go`) | |
27 | var goSrcRegexp = regexp.MustCompile(`jinzhu/gorm(@.*)?/.*.go`) | |
28 | var goTestRegexp = regexp.MustCompile(`jinzhu/gorm(@.*)?/.*test.go`) | |
30 | 29 | |
31 | 30 | func init() { |
32 | 31 | var commonInitialismsForReplacer []string |
55 | 54 | |
56 | 55 | func newSafeMap() *safeMap { |
57 | 56 | return &safeMap{l: new(sync.RWMutex), m: make(map[string]string)} |
58 | } | |
59 | ||
60 | var smap = newSafeMap() | |
61 | ||
62 | type strCase bool | |
63 | ||
64 | const ( | |
65 | lower strCase = false | |
66 | upper strCase = true | |
67 | ) | |
68 | ||
69 | // ToDBName convert string to db name | |
70 | func ToDBName(name string) string { | |
71 | if v := smap.Get(name); v != "" { | |
72 | return v | |
73 | } | |
74 | ||
75 | if name == "" { | |
76 | return "" | |
77 | } | |
78 | ||
79 | var ( | |
80 | value = commonInitialismsReplacer.Replace(name) | |
81 | buf = bytes.NewBufferString("") | |
82 | lastCase, currCase, nextCase strCase | |
83 | ) | |
84 | ||
85 | for i, v := range value[:len(value)-1] { | |
86 | nextCase = strCase(value[i+1] >= 'A' && value[i+1] <= 'Z') | |
87 | if i > 0 { | |
88 | if currCase == upper { | |
89 | if lastCase == upper && nextCase == upper { | |
90 | buf.WriteRune(v) | |
91 | } else { | |
92 | if value[i-1] != '_' && value[i+1] != '_' { | |
93 | buf.WriteRune('_') | |
94 | } | |
95 | buf.WriteRune(v) | |
96 | } | |
97 | } else { | |
98 | buf.WriteRune(v) | |
99 | if i == len(value)-2 && nextCase == upper { | |
100 | buf.WriteRune('_') | |
101 | } | |
102 | } | |
103 | } else { | |
104 | currCase = upper | |
105 | buf.WriteRune(v) | |
106 | } | |
107 | lastCase = currCase | |
108 | currCase = nextCase | |
109 | } | |
110 | ||
111 | buf.WriteByte(value[len(value)-1]) | |
112 | ||
113 | s := strings.ToLower(buf.String()) | |
114 | smap.Set(name, s) | |
115 | return s | |
116 | 57 | } |
117 | 58 | |
118 | 59 | // SQL expression |
264 | 205 | // as FieldByName could panic |
265 | 206 | if indirectValue := reflect.Indirect(value); indirectValue.IsValid() { |
266 | 207 | for _, fieldName := range fieldNames { |
267 | if fieldValue := indirectValue.FieldByName(fieldName); fieldValue.IsValid() { | |
208 | if fieldValue := reflect.Indirect(indirectValue.FieldByName(fieldName)); fieldValue.IsValid() { | |
268 | 209 | result := fieldValue.Interface() |
269 | 210 | if r, ok := result.(driver.Valuer); ok { |
270 | 211 | result, _ = r.Value() |
0 | package gorm_test | |
1 | ||
2 | import ( | |
3 | "testing" | |
4 | ||
5 | "github.com/jinzhu/gorm" | |
6 | ) | |
7 | ||
8 | func TestToDBNameGenerateFriendlyName(t *testing.T) { | |
9 | var maps = map[string]string{ | |
10 | "": "", | |
11 | "X": "x", | |
12 | "ThisIsATest": "this_is_a_test", | |
13 | "PFAndESI": "pf_and_esi", | |
14 | "AbcAndJkl": "abc_and_jkl", | |
15 | "EmployeeID": "employee_id", | |
16 | "SKU_ID": "sku_id", | |
17 | "FieldX": "field_x", | |
18 | "HTTPAndSMTP": "http_and_smtp", | |
19 | "HTTPServerHandlerForURLID": "http_server_handler_for_url_id", | |
20 | "UUID": "uuid", | |
21 | "HTTPURL": "http_url", | |
22 | "HTTP_URL": "http_url", | |
23 | "ThisIsActuallyATestSoWeMayBeAbleToUseThisCodeInGormPackageAlsoIdCanBeUsedAtTheEndAsID": "this_is_actually_a_test_so_we_may_be_able_to_use_this_code_in_gorm_package_also_id_can_be_used_at_the_end_as_id", | |
24 | } | |
25 | ||
26 | for key, value := range maps { | |
27 | if gorm.ToDBName(key) != value { | |
28 | t.Errorf("%v ToDBName should equal %v, but got %v", key, value, gorm.ToDBName(key)) | |
29 | } | |
30 | } | |
31 | } |
82 | 82 | code: | |
83 | 83 | cd $WERCKER_SOURCE_DIR |
84 | 84 | go version |
85 | go get -t ./... | |
85 | go get -t -v ./... | |
86 | 86 | |
87 | 87 | # Build the project |
88 | 88 | - script: |
94 | 94 | - script: |
95 | 95 | name: test sqlite |
96 | 96 | code: | |
97 | go test ./... | |
97 | go test -race -v ./... | |
98 | 98 | |
99 | 99 | - script: |
100 | 100 | name: test mariadb |
101 | 101 | code: | |
102 | GORM_DIALECT=mysql GORM_DSN="gorm:gorm@tcp(mariadb:3306)/gorm?charset=utf8&parseTime=True" go test ./... | |
102 | GORM_DIALECT=mysql GORM_DSN="gorm:gorm@tcp(mariadb:3306)/gorm?charset=utf8&parseTime=True" go test -race ./... | |
103 | 103 | |
104 | 104 | - script: |
105 | 105 | name: test mysql5.7 |
106 | 106 | code: | |
107 | GORM_DIALECT=mysql GORM_DSN="gorm:gorm@tcp(mysql57:3306)/gorm?charset=utf8&parseTime=True" go test ./... | |
107 | GORM_DIALECT=mysql GORM_DSN="gorm:gorm@tcp(mysql57:3306)/gorm?charset=utf8&parseTime=True" go test -race ./... | |
108 | 108 | |
109 | 109 | - script: |
110 | 110 | name: test mysql5.6 |
111 | 111 | code: | |
112 | GORM_DIALECT=mysql GORM_DSN="gorm:gorm@tcp(mysql56:3306)/gorm?charset=utf8&parseTime=True" go test ./... | |
112 | GORM_DIALECT=mysql GORM_DSN="gorm:gorm@tcp(mysql56:3306)/gorm?charset=utf8&parseTime=True" go test -race ./... | |
113 | 113 | |
114 | 114 | - script: |
115 | 115 | name: test mysql5.5 |
116 | 116 | code: | |
117 | GORM_DIALECT=mysql GORM_DSN="gorm:gorm@tcp(mysql55:3306)/gorm?charset=utf8&parseTime=True" go test ./... | |
117 | GORM_DIALECT=mysql GORM_DSN="gorm:gorm@tcp(mysql55:3306)/gorm?charset=utf8&parseTime=True" go test -race ./... | |
118 | 118 | |
119 | 119 | - script: |
120 | 120 | name: test postgres |
121 | 121 | code: | |
122 | GORM_DIALECT=postgres GORM_DSN="host=postgres user=gorm password=gorm DB.name=gorm port=5432 sslmode=disable" go test ./... | |
122 | GORM_DIALECT=postgres GORM_DSN="host=postgres user=gorm password=gorm DB.name=gorm port=5432 sslmode=disable" go test -race ./... | |
123 | 123 | |
124 | 124 | - script: |
125 | 125 | name: test postgres96 |
126 | 126 | code: | |
127 | GORM_DIALECT=postgres GORM_DSN="host=postgres96 user=gorm password=gorm DB.name=gorm port=5432 sslmode=disable" go test ./... | |
127 | GORM_DIALECT=postgres GORM_DSN="host=postgres96 user=gorm password=gorm DB.name=gorm port=5432 sslmode=disable" go test -race ./... | |
128 | 128 | |
129 | 129 | - script: |
130 | 130 | name: test postgres95 |
131 | 131 | code: | |
132 | GORM_DIALECT=postgres GORM_DSN="host=postgres95 user=gorm password=gorm DB.name=gorm port=5432 sslmode=disable" go test ./... | |
132 | GORM_DIALECT=postgres GORM_DSN="host=postgres95 user=gorm password=gorm DB.name=gorm port=5432 sslmode=disable" go test -race ./... | |
133 | 133 | |
134 | 134 | - script: |
135 | 135 | name: test postgres94 |
136 | 136 | code: | |
137 | GORM_DIALECT=postgres GORM_DSN="host=postgres94 user=gorm password=gorm DB.name=gorm port=5432 sslmode=disable" go test ./... | |
137 | GORM_DIALECT=postgres GORM_DSN="host=postgres94 user=gorm password=gorm DB.name=gorm port=5432 sslmode=disable" go test -race ./... | |
138 | 138 | |
139 | 139 | - script: |
140 | 140 | name: test postgres93 |
141 | 141 | code: | |
142 | GORM_DIALECT=postgres GORM_DSN="host=postgres93 user=gorm password=gorm DB.name=gorm port=5432 sslmode=disable" go test ./... | |
142 | GORM_DIALECT=postgres GORM_DSN="host=postgres93 user=gorm password=gorm DB.name=gorm port=5432 sslmode=disable" go test -race ./... | |
143 | 143 | |
144 | 144 | - script: |
145 | 145 | name: test mssql |
146 | 146 | code: | |
147 | GORM_DIALECT=mssql GORM_DSN="sqlserver://gorm:LoremIpsum86@mssql:1433?database=gorm" go test ./... | |
147 | GORM_DIALECT=mssql GORM_DSN="sqlserver://gorm:LoremIpsum86@mssql:1433?database=gorm" go test -race ./... | |
148 | ||
149 | - script: | |
150 | name: codecov | |
151 | code: | | |
152 | go test -race -coverprofile=coverage.txt -covermode=atomic ./... | |
153 | bash <(curl -s https://codecov.io/bash) |