Browse Source

更新gorm

lijian 2 years ago
parent
commit
0cd57469f2

+ 3 - 4
pkg/server/promethues.go

@@ -10,8 +10,7 @@ var rpcCallCnt = &Metric{
 	ID:          "rpcCallCnt",
 	Name:        "rpc_call_total",
 	Description: "HOW MANY RPC CALL",
-	Type:        "counter_vec",
-	Args:        []string{"server", "host"},
+	Type:        "counter",
 }
 
 var rpcCallDur = &Metric{
@@ -39,7 +38,7 @@ type Metric struct {
 type Prometheus struct {
 	MetricsList []*Metric
 	MetricsPath string
-	CallCnt     *prometheus.CounterVec
+	CallCnt     prometheus.Counter
 	CallDur     *prometheus.HistogramVec
 }
 
@@ -157,7 +156,7 @@ func (p *Prometheus) registerMetrics(sub string) {
 		}
 		switch metricDef {
 		case rpcCallCnt:
-			p.CallCnt = metric.(*prometheus.CounterVec)
+			p.CallCnt = metric.(prometheus.Gauge)
 		case rpcCallDur:
 			p.CallDur = metric.(*prometheus.HistogramVec)
 		}

+ 1 - 1
pkg/server/rpc_server.go

@@ -13,6 +13,6 @@ type RPCServer struct {
 type rpcHandler struct{}
 
 func (handler *rpcHandler) Handle(conn net.Conn) {
-	addCallCount(conn.RemoteAddr().String())
+	addCallCount()
 	rpc.ServeConn(conn)
 }

+ 2 - 2
pkg/server/server.go

@@ -303,8 +303,8 @@ func Run() error {
 	}
 }
 
-func addCallCount(host string) {
+func addCallCount() {
 	if serverInstance.prome != nil {
-		serverInstance.prome.CallCnt.WithLabelValues(serverInstance.name, host).Inc()
+		serverInstance.prome.CallCnt.Inc()
 	}
 }

+ 2 - 37
vendor/github.com/jinzhu/gorm/README.md

@@ -1,40 +1,5 @@
 # GORM
 
-The fantastic ORM library for Golang, aims to be developer friendly.
+GORM V2 moved to https://github.com/go-gorm/gorm
 
-[![go report card](https://goreportcard.com/badge/github.com/jinzhu/gorm "go report card")](https://goreportcard.com/report/github.com/jinzhu/gorm)
-[![wercker status](https://app.wercker.com/status/8596cace912c9947dd9c8542ecc8cb8b/s/master "wercker status")](https://app.wercker.com/project/byKey/8596cace912c9947dd9c8542ecc8cb8b)
-[![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)
-[![Open Collective Backer](https://opencollective.com/gorm/tiers/backer/badge.svg?label=backer&color=brightgreen "Open Collective Backer")](https://opencollective.com/gorm)
-[![Open Collective Sponsor](https://opencollective.com/gorm/tiers/sponsor/badge.svg?label=sponsor&color=brightgreen "Open Collective Sponsor")](https://opencollective.com/gorm)
-[![MIT license](http://img.shields.io/badge/license-MIT-brightgreen.svg)](http://opensource.org/licenses/MIT)
-[![GoDoc](https://godoc.org/github.com/jinzhu/gorm?status.svg)](https://godoc.org/github.com/jinzhu/gorm)
-
-## Overview
-
-* Full-Featured ORM (almost)
-* Associations (Has One, Has Many, Belongs To, Many To Many, Polymorphism)
-* Hooks (Before/After Create/Save/Update/Delete/Find)
-* Preloading (eager loading)
-* Transactions
-* Composite Primary Key
-* SQL Builder
-* Auto Migrations
-* Logger
-* Extendable, write Plugins based on GORM callbacks
-* Every feature comes with tests
-* Developer Friendly
-
-## Getting Started
-
-* GORM Guides [http://gorm.io](http://gorm.io)
-
-## Contributing
-
-[You can help to deliver a better GORM, check out things you can do](http://gorm.io/contribute.html)
-
-## License
-
-© Jinzhu, 2013~time.Now
-
-Released under the [MIT License](https://github.com/jinzhu/gorm/blob/master/License)
+GORM V1 Doc https://v1.gorm.io/

+ 5 - 3
vendor/github.com/jinzhu/gorm/association.go

@@ -267,15 +267,16 @@ func (association *Association) Count() int {
 		query        = scope.DB()
 	)
 
-	if relationship.Kind == "many_to_many" {
+	switch relationship.Kind {
+	case "many_to_many":
 		query = relationship.JoinTableHandler.JoinWith(relationship.JoinTableHandler, query, scope.Value)
-	} else if relationship.Kind == "has_many" || relationship.Kind == "has_one" {
+	case "has_many", "has_one":
 		primaryKeys := scope.getColumnAsArray(relationship.AssociationForeignFieldNames, scope.Value)
 		query = query.Where(
 			fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, relationship.ForeignDBNames), toQueryMarks(primaryKeys)),
 			toQueryValues(primaryKeys)...,
 		)
-	} else if relationship.Kind == "belongs_to" {
+	case "belongs_to":
 		primaryKeys := scope.getColumnAsArray(relationship.ForeignFieldNames, scope.Value)
 		query = query.Where(
 			fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, relationship.AssociationForeignDBNames), toQueryMarks(primaryKeys)),
@@ -367,6 +368,7 @@ func (association *Association) saveAssociations(values ...interface{}) *Associa
 	return association
 }
 
+// setErr set error when the error is not nil. And return Association.
 func (association *Association) setErr(err error) *Association {
 	if err != nil {
 		association.Error = err

+ 25 - 17
vendor/github.com/jinzhu/gorm/callback.go

@@ -1,9 +1,9 @@
 package gorm
 
-import "log"
+import "fmt"
 
 // DefaultCallback default callbacks defined by gorm
-var DefaultCallback = &Callback{}
+var DefaultCallback = &Callback{logger: nopLogger{}}
 
 // Callback is a struct that contains all CRUD callbacks
 //   Field `creates` contains callbacks will be call when creating object
@@ -13,6 +13,7 @@ var DefaultCallback = &Callback{}
 //   Field `rowQueries` contains callbacks will be call when querying object with Row, Rows...
 //   Field `processors` contains all callback processors, will be used to generate above callbacks in order
 type Callback struct {
+	logger     logger
 	creates    []*func(scope *Scope)
 	updates    []*func(scope *Scope)
 	deletes    []*func(scope *Scope)
@@ -23,6 +24,7 @@ type Callback struct {
 
 // CallbackProcessor contains callback informations
 type CallbackProcessor struct {
+	logger    logger
 	name      string              // current callback's name
 	before    string              // register current callback before a callback
 	after     string              // register current callback after a callback
@@ -33,8 +35,9 @@ type CallbackProcessor struct {
 	parent    *Callback
 }
 
-func (c *Callback) clone() *Callback {
+func (c *Callback) clone(logger logger) *Callback {
 	return &Callback{
+		logger:     logger,
 		creates:    c.creates,
 		updates:    c.updates,
 		deletes:    c.deletes,
@@ -53,28 +56,28 @@ func (c *Callback) clone() *Callback {
 //       scope.Err(errors.New("error"))
 //     })
 func (c *Callback) Create() *CallbackProcessor {
-	return &CallbackProcessor{kind: "create", parent: c}
+	return &CallbackProcessor{logger: c.logger, kind: "create", parent: c}
 }
 
 // Update could be used to register callbacks for updating object, refer `Create` for usage
 func (c *Callback) Update() *CallbackProcessor {
-	return &CallbackProcessor{kind: "update", parent: c}
+	return &CallbackProcessor{logger: c.logger, kind: "update", parent: c}
 }
 
 // Delete could be used to register callbacks for deleting object, refer `Create` for usage
 func (c *Callback) Delete() *CallbackProcessor {
-	return &CallbackProcessor{kind: "delete", parent: c}
+	return &CallbackProcessor{logger: c.logger, kind: "delete", parent: c}
 }
 
 // Query could be used to register callbacks for querying objects with query methods like `Find`, `First`, `Related`, `Association`...
 // Refer `Create` for usage
 func (c *Callback) Query() *CallbackProcessor {
-	return &CallbackProcessor{kind: "query", parent: c}
+	return &CallbackProcessor{logger: c.logger, kind: "query", parent: c}
 }
 
 // RowQuery could be used to register callbacks for querying objects with `Row`, `Rows`, refer `Create` for usage
 func (c *Callback) RowQuery() *CallbackProcessor {
-	return &CallbackProcessor{kind: "row_query", parent: c}
+	return &CallbackProcessor{logger: c.logger, kind: "row_query", parent: c}
 }
 
 // After insert a new callback after callback `callbackName`, refer `Callbacks.Create`
@@ -93,11 +96,12 @@ func (cp *CallbackProcessor) Before(callbackName string) *CallbackProcessor {
 func (cp *CallbackProcessor) Register(callbackName string, callback func(scope *Scope)) {
 	if cp.kind == "row_query" {
 		if cp.before == "" && cp.after == "" && callbackName != "gorm:row_query" {
-			log.Printf("Registing RowQuery callback %v without specify order with Before(), After(), applying Before('gorm:row_query') by default for compatibility...\n", callbackName)
+			cp.logger.Print("info", fmt.Sprintf("Registering RowQuery callback %v without specify order with Before(), After(), applying Before('gorm:row_query') by default for compatibility...", callbackName))
 			cp.before = "gorm:row_query"
 		}
 	}
 
+	cp.logger.Print("info", fmt.Sprintf("[info] registering callback `%v` from %v", callbackName, fileWithLineNum()))
 	cp.name = callbackName
 	cp.processor = &callback
 	cp.parent.processors = append(cp.parent.processors, cp)
@@ -107,7 +111,7 @@ func (cp *CallbackProcessor) Register(callbackName string, callback func(scope *
 // Remove a registered callback
 //     db.Callback().Create().Remove("gorm:update_time_stamp_when_create")
 func (cp *CallbackProcessor) Remove(callbackName string) {
-	log.Printf("[info] removing callback `%v` from %v\n", callbackName, fileWithLineNum())
+	cp.logger.Print("info", fmt.Sprintf("[info] removing callback `%v` from %v", callbackName, fileWithLineNum()))
 	cp.name = callbackName
 	cp.remove = true
 	cp.parent.processors = append(cp.parent.processors, cp)
@@ -116,11 +120,11 @@ func (cp *CallbackProcessor) Remove(callbackName string) {
 
 // Replace a registered callback with new callback
 //     db.Callback().Create().Replace("gorm:update_time_stamp_when_create", func(*Scope) {
-//		   scope.SetColumn("Created", now)
-//		   scope.SetColumn("Updated", now)
+//		   scope.SetColumn("CreatedAt", now)
+//		   scope.SetColumn("UpdatedAt", now)
 //     })
 func (cp *CallbackProcessor) Replace(callbackName string, callback func(scope *Scope)) {
-	log.Printf("[info] replacing callback `%v` from %v\n", callbackName, fileWithLineNum())
+	cp.logger.Print("info", fmt.Sprintf("[info] replacing callback `%v` from %v", callbackName, fileWithLineNum()))
 	cp.name = callbackName
 	cp.processor = &callback
 	cp.replace = true
@@ -132,11 +136,15 @@ func (cp *CallbackProcessor) Replace(callbackName string, callback func(scope *S
 //    db.Callback().Create().Get("gorm:create")
 func (cp *CallbackProcessor) Get(callbackName string) (callback func(scope *Scope)) {
 	for _, p := range cp.parent.processors {
-		if p.name == callbackName && p.kind == cp.kind && !cp.remove {
-			return *p.processor
+		if p.name == callbackName && p.kind == cp.kind {
+			if p.remove {
+				callback = nil
+			} else {
+				callback = *p.processor
+			}
 		}
 	}
-	return nil
+	return
 }
 
 // getRIndex get right index from string slice
@@ -159,7 +167,7 @@ func sortProcessors(cps []*CallbackProcessor) []*func(scope *Scope) {
 	for _, cp := range cps {
 		// show warning message the callback name already exists
 		if index := getRIndex(allNames, cp.name); index > -1 && !cp.replace && !cp.remove {
-			log.Printf("[warning] duplicated callback `%v` from %v\n", cp.name, fileWithLineNum())
+			cp.logger.Print("warning", fmt.Sprintf("[warning] duplicated callback `%v` from %v", cp.name, fileWithLineNum()))
 		}
 		allNames = append(allNames, cp.name)
 	}

+ 53 - 13
vendor/github.com/jinzhu/gorm/callback_create.go

@@ -31,7 +31,7 @@ func beforeCreateCallback(scope *Scope) {
 // updateTimeStampForCreateCallback will set `CreatedAt`, `UpdatedAt` when creating
 func updateTimeStampForCreateCallback(scope *Scope) {
 	if !scope.HasError() {
-		now := NowFunc()
+		now := scope.db.nowFunc()
 
 		if createdAtField, ok := scope.FieldByName("CreatedAt"); ok {
 			if createdAtField.IsBlank {
@@ -83,21 +83,33 @@ func createCallback(scope *Scope) {
 			quotedTableName = scope.QuotedTableName()
 			primaryField    = scope.PrimaryField()
 			extraOption     string
+			insertModifier  string
 		)
 
 		if str, ok := scope.Get("gorm:insert_option"); ok {
 			extraOption = fmt.Sprint(str)
 		}
+		if str, ok := scope.Get("gorm:insert_modifier"); ok {
+			insertModifier = strings.ToUpper(fmt.Sprint(str))
+			if insertModifier == "INTO" {
+				insertModifier = ""
+			}
+		}
 
 		if primaryField != nil {
 			returningColumn = scope.Quote(primaryField.DBName)
 		}
 
-		lastInsertIDReturningSuffix := scope.Dialect().LastInsertIDReturningSuffix(quotedTableName, returningColumn)
+		lastInsertIDOutputInterstitial := scope.Dialect().LastInsertIDOutputInterstitial(quotedTableName, returningColumn, columns)
+		var lastInsertIDReturningSuffix string
+		if lastInsertIDOutputInterstitial == "" {
+			lastInsertIDReturningSuffix = scope.Dialect().LastInsertIDReturningSuffix(quotedTableName, returningColumn)
+		}
 
 		if len(columns) == 0 {
 			scope.Raw(fmt.Sprintf(
-				"INSERT INTO %v %v%v%v",
+				"INSERT%v INTO %v %v%v%v",
+				addExtraSpaceIfExist(insertModifier),
 				quotedTableName,
 				scope.Dialect().DefaultValueStr(),
 				addExtraSpaceIfExist(extraOption),
@@ -105,17 +117,19 @@ func createCallback(scope *Scope) {
 			))
 		} else {
 			scope.Raw(fmt.Sprintf(
-				"INSERT INTO %v (%v) VALUES (%v)%v%v",
+				"INSERT%v INTO %v (%v)%v VALUES (%v)%v%v",
+				addExtraSpaceIfExist(insertModifier),
 				scope.QuotedTableName(),
 				strings.Join(columns, ","),
+				addExtraSpaceIfExist(lastInsertIDOutputInterstitial),
 				strings.Join(placeholders, ","),
 				addExtraSpaceIfExist(extraOption),
 				addExtraSpaceIfExist(lastInsertIDReturningSuffix),
 			))
 		}
 
-		// execute create sql
-		if lastInsertIDReturningSuffix == "" || primaryField == nil {
+		// execute create sql: no primaryField
+		if primaryField == nil {
 			if result, err := scope.SQLDB().Exec(scope.SQL, scope.SQLVars...); scope.Err(err) == nil {
 				// set rows affected count
 				scope.db.RowsAffected, _ = result.RowsAffected()
@@ -127,28 +141,54 @@ func createCallback(scope *Scope) {
 					}
 				}
 			}
-		} else {
-			if primaryField.Field.CanAddr() {
-				if err := scope.SQLDB().QueryRow(scope.SQL, scope.SQLVars...).Scan(primaryField.Field.Addr().Interface()); scope.Err(err) == nil {
-					primaryField.IsBlank = false
-					scope.db.RowsAffected = 1
+			return
+		}
+
+		// execute create sql: lastInsertID implemention for majority of dialects
+		if lastInsertIDReturningSuffix == "" && lastInsertIDOutputInterstitial == "" {
+			if result, err := scope.SQLDB().Exec(scope.SQL, scope.SQLVars...); scope.Err(err) == nil {
+				// set rows affected count
+				scope.db.RowsAffected, _ = result.RowsAffected()
+
+				// set primary value to primary field
+				if primaryField != nil && primaryField.IsBlank {
+					if primaryValue, err := result.LastInsertId(); scope.Err(err) == nil {
+						scope.Err(primaryField.Set(primaryValue))
+					}
 				}
-			} else {
-				scope.Err(ErrUnaddressable)
 			}
+			return
 		}
+
+		// execute create sql: dialects with additional lastInsertID requirements (currently postgres & mssql)
+		if primaryField.Field.CanAddr() {
+			if err := scope.SQLDB().QueryRow(scope.SQL, scope.SQLVars...).Scan(primaryField.Field.Addr().Interface()); scope.Err(err) == nil {
+				primaryField.IsBlank = false
+				scope.db.RowsAffected = 1
+			}
+		} else {
+			scope.Err(ErrUnaddressable)
+		}
+		return
 	}
 }
 
 // forceReloadAfterCreateCallback will reload columns that having default value, and set it back to current object
 func forceReloadAfterCreateCallback(scope *Scope) {
 	if blankColumnsWithDefaultValue, ok := scope.InstanceGet("gorm:blank_columns_with_default_value"); ok {
+		var shouldScan bool
 		db := scope.DB().New().Table(scope.TableName()).Select(blankColumnsWithDefaultValue.([]string))
 		for _, field := range scope.Fields() {
 			if field.IsPrimaryKey && !field.IsBlank {
 				db = db.Where(fmt.Sprintf("%v = ?", field.DBName), field.Field.Interface())
+				shouldScan = true
 			}
 		}
+
+		if !shouldScan {
+			return
+		}
+
 		db.Scan(scope.Value)
 	}
 }

+ 2 - 2
vendor/github.com/jinzhu/gorm/callback_delete.go

@@ -17,7 +17,7 @@ func init() {
 // beforeDeleteCallback will invoke `BeforeDelete` method before deleting
 func beforeDeleteCallback(scope *Scope) {
 	if scope.DB().HasBlockGlobalUpdate() && !scope.hasConditions() {
-		scope.Err(errors.New("Missing WHERE clause while deleting"))
+		scope.Err(errors.New("missing WHERE clause while deleting"))
 		return
 	}
 	if !scope.HasError() {
@@ -40,7 +40,7 @@ func deleteCallback(scope *Scope) {
 				"UPDATE %v SET %v=%v%v%v",
 				scope.QuotedTableName(),
 				scope.Quote(deletedAtField.DBName),
-				scope.AddToVars(NowFunc()),
+				scope.AddToVars(scope.db.nowFunc()),
 				addExtraSpaceIfExist(scope.CombinedConditionSql()),
 				addExtraSpaceIfExist(extraOption),
 			)).Exec()

+ 4 - 3
vendor/github.com/jinzhu/gorm/callback_query.go

@@ -18,7 +18,7 @@ func queryCallback(scope *Scope) {
 	if _, skip := scope.InstanceGet("gorm:skip_query_callback"); skip {
 		return
 	}
-	
+
 	//we are only preloading relations, dont touch base model
 	if _, skip := scope.InstanceGet("gorm:only_preload"); skip {
 		return
@@ -60,8 +60,9 @@ func queryCallback(scope *Scope) {
 
 	if !scope.HasError() {
 		scope.db.RowsAffected = 0
-		if str, ok := scope.Get("gorm:query_option"); ok {
-			scope.SQL += addExtraSpaceIfExist(fmt.Sprint(str))
+
+		if str, ok := scope.Get("gorm:query_hint"); ok {
+			scope.SQL = fmt.Sprint(str) + scope.SQL
 		}
 
 		if rows, err := scope.SQLDB().Query(scope.SQL, scope.SQLVars...); scope.Err(err) == nil {

+ 11 - 5
vendor/github.com/jinzhu/gorm/callback_query_preload.go

@@ -391,14 +391,20 @@ func (scope *Scope) handleManyToManyPreload(field *Field, conditions []interface
 		key := toString(getValueFromFields(indirectScopeValue, foreignFieldNames))
 		fieldsSourceMap[key] = append(fieldsSourceMap[key], indirectScopeValue.FieldByName(field.Name))
 	}
-	for source, link := range linkHash {
-		for i, field := range fieldsSourceMap[source] {
+
+	for source, fields := range fieldsSourceMap {
+		for _, f := range fields {
 			//If not 0 this means Value is a pointer and we already added preloaded models to it
-			if fieldsSourceMap[source][i].Len() != 0 {
+			if f.Len() != 0 {
 				continue
 			}
-			field.Set(reflect.Append(fieldsSourceMap[source][i], link...))
-		}
 
+			v := reflect.MakeSlice(f.Type(), 0, 0)
+			if len(linkHash[source]) > 0 {
+				v = reflect.Append(f, linkHash[source]...)
+			}
+
+			f.Set(v)
+		}
 	}
 }

+ 8 - 1
vendor/github.com/jinzhu/gorm/callback_row_query.go

@@ -1,6 +1,9 @@
 package gorm
 
-import "database/sql"
+import (
+	"database/sql"
+	"fmt"
+)
 
 // Define callbacks for row query
 func init() {
@@ -21,6 +24,10 @@ func rowQueryCallback(scope *Scope) {
 	if result, ok := scope.InstanceGet("row_query_result"); ok {
 		scope.prepareQuerySQL()
 
+		if str, ok := scope.Get("gorm:query_hint"); ok {
+			scope.SQL = fmt.Sprint(str) + scope.SQL
+		}
+
 		if rowResult, ok := result.(*RowQueryResult); ok {
 			rowResult.Row = scope.SQLDB().QueryRow(scope.SQL, scope.SQLVars...)
 		} else if rowsResult, ok := result.(*RowsQueryResult); ok {

+ 3 - 3
vendor/github.com/jinzhu/gorm/callback_update.go

@@ -34,7 +34,7 @@ func assignUpdatingAttributesCallback(scope *Scope) {
 // beforeUpdateCallback will invoke `BeforeSave`, `BeforeUpdate` method before updating
 func beforeUpdateCallback(scope *Scope) {
 	if scope.DB().HasBlockGlobalUpdate() && !scope.hasConditions() {
-		scope.Err(errors.New("Missing WHERE clause while updating"))
+		scope.Err(errors.New("missing WHERE clause while updating"))
 		return
 	}
 	if _, ok := scope.Get("gorm:update_column"); !ok {
@@ -50,7 +50,7 @@ func beforeUpdateCallback(scope *Scope) {
 // updateTimeStampForUpdateCallback will set `UpdatedAt` when updating
 func updateTimeStampForUpdateCallback(scope *Scope) {
 	if _, ok := scope.Get("gorm:update_column"); !ok {
-		scope.SetColumn("UpdatedAt", NowFunc())
+		scope.SetColumn("UpdatedAt", scope.db.nowFunc())
 	}
 }
 
@@ -75,7 +75,7 @@ func updateCallback(scope *Scope) {
 		} else {
 			for _, field := range scope.Fields() {
 				if scope.changeableField(field) {
-					if !field.IsPrimaryKey && field.IsNormal {
+					if !field.IsPrimaryKey && field.IsNormal && (field.Name != "CreatedAt" || !field.IsBlank) {
 						if !field.IsForeignKey || !field.IsBlank || !field.HasDefaultValue {
 							sqls = append(sqls, fmt.Sprintf("%v = %v", scope.Quote(field.DBName), scope.AddToVars(field.Field.Interface())))
 						}

+ 10 - 1
vendor/github.com/jinzhu/gorm/dialect.go

@@ -37,9 +37,11 @@ type Dialect interface {
 	ModifyColumn(tableName string, columnName string, typ string) error
 
 	// LimitAndOffsetSQL return generated SQL with Limit and Offset, as mssql has special case
-	LimitAndOffsetSQL(limit, offset interface{}) string
+	LimitAndOffsetSQL(limit, offset interface{}) (string, error)
 	// SelectFromDummyTable return select values, for most dbs, `SELECT values` just works, mysql needs `SELECT value FROM DUAL`
 	SelectFromDummyTable() string
+	// LastInsertIDOutputInterstitial most dbs support LastInsertId, but mssql needs to use `OUTPUT`
+	LastInsertIDOutputInterstitial(tableName, columnName string, columns []string) string
 	// LastInsertIdReturningSuffix most dbs support LastInsertId, but postgres needs to use `RETURNING`
 	LastInsertIDReturningSuffix(tableName, columnName string) string
 	// DefaultValueStr
@@ -48,6 +50,9 @@ type Dialect interface {
 	// BuildKeyName returns a valid key name (foreign key, index key) for the given table, field and reference
 	BuildKeyName(kind, tableName string, fields ...string) string
 
+	// NormalizeIndexAndColumn returns valid index name and column name depending on each dialect
+	NormalizeIndexAndColumn(indexName, columnName string) (string, string)
+
 	// CurrentDatabase return current database name
 	CurrentDatabase() string
 }
@@ -126,6 +131,10 @@ var ParseFieldStructForDialect = func(field *StructField, dialect Dialect) (fiel
 		additionalType = additionalType + " DEFAULT " + value
 	}
 
+	if value, ok := field.TagSettingsGet("COMMENT"); ok && dialect.GetName() != "sqlite3" {
+		additionalType = additionalType + " COMMENT " + value
+	}
+
 	return fieldValue, dataType, size, strings.TrimSpace(additionalType)
 }
 

+ 24 - 4
vendor/github.com/jinzhu/gorm/dialect_common.go

@@ -9,6 +9,8 @@ import (
 	"time"
 )
 
+var keyNameRegex = regexp.MustCompile("[^a-zA-Z0-9]+")
+
 // DefaultForeignKeyNamer contains the default foreign key name generator method
 type DefaultForeignKeyNamer struct {
 }
@@ -137,14 +139,19 @@ func (s commonDialect) CurrentDatabase() (name string) {
 	return
 }
 
-func (commonDialect) LimitAndOffsetSQL(limit, offset interface{}) (sql string) {
+// LimitAndOffsetSQL return generated SQL with Limit and Offset
+func (s commonDialect) LimitAndOffsetSQL(limit, offset interface{}) (sql string, err error) {
 	if limit != nil {
-		if parsedLimit, err := strconv.ParseInt(fmt.Sprint(limit), 0, 0); err == nil && parsedLimit >= 0 {
+		if parsedLimit, err := s.parseInt(limit); err != nil {
+			return "", err
+		} else if parsedLimit >= 0 {
 			sql += fmt.Sprintf(" LIMIT %d", parsedLimit)
 		}
 	}
 	if offset != nil {
-		if parsedOffset, err := strconv.ParseInt(fmt.Sprint(offset), 0, 0); err == nil && parsedOffset >= 0 {
+		if parsedOffset, err := s.parseInt(offset); err != nil {
+			return "", err
+		} else if parsedOffset >= 0 {
 			sql += fmt.Sprintf(" OFFSET %d", parsedOffset)
 		}
 	}
@@ -155,6 +162,10 @@ func (commonDialect) SelectFromDummyTable() string {
 	return ""
 }
 
+func (commonDialect) LastInsertIDOutputInterstitial(tableName, columnName string, columns []string) string {
+	return ""
+}
+
 func (commonDialect) LastInsertIDReturningSuffix(tableName, columnName string) string {
 	return ""
 }
@@ -166,10 +177,19 @@ func (commonDialect) DefaultValueStr() string {
 // BuildKeyName returns a valid key name (foreign key, index key) for the given table, field and reference
 func (DefaultForeignKeyNamer) BuildKeyName(kind, tableName string, fields ...string) string {
 	keyName := fmt.Sprintf("%s_%s_%s", kind, tableName, strings.Join(fields, "_"))
-	keyName = regexp.MustCompile("[^a-zA-Z0-9]+").ReplaceAllString(keyName, "_")
+	keyName = keyNameRegex.ReplaceAllString(keyName, "_")
 	return keyName
 }
 
+// NormalizeIndexAndColumn returns argument's index name and column name without doing anything
+func (commonDialect) NormalizeIndexAndColumn(indexName, columnName string) (string, string) {
+	return indexName, columnName
+}
+
+func (commonDialect) parseInt(value interface{}) (int64, error) {
+	return strconv.ParseInt(fmt.Sprint(value), 0, 0)
+}
+
 // IsByteArrayOrSlice returns true of the reflected value is an array or slice
 func IsByteArrayOrSlice(value reflect.Value) bool {
 	return (value.Kind() == reflect.Array || value.Kind() == reflect.Slice) && value.Type().Elem() == reflect.TypeOf(uint8(0))

+ 64 - 9
vendor/github.com/jinzhu/gorm/dialect_mysql.go

@@ -2,15 +2,17 @@ package gorm
 
 import (
 	"crypto/sha1"
+	"database/sql"
 	"fmt"
 	"reflect"
 	"regexp"
-	"strconv"
 	"strings"
 	"time"
 	"unicode/utf8"
 )
 
+var mysqlIndexRegex = regexp.MustCompile(`^(.+)\((\d+)\)$`)
+
 type mysql struct {
 	commonDialect
 }
@@ -100,10 +102,10 @@ func (s *mysql) DataTypeOf(field *StructField) string {
 					precision = fmt.Sprintf("(%s)", p)
 				}
 
-				if _, ok := field.TagSettingsGet("NOT NULL"); ok {
-					sqlType = fmt.Sprintf("timestamp%v", precision)
+				if _, ok := field.TagSettings["NOT NULL"]; ok || field.IsPrimaryKey {
+					sqlType = fmt.Sprintf("DATETIME%v", precision)
 				} else {
-					sqlType = fmt.Sprintf("timestamp%v NULL", precision)
+					sqlType = fmt.Sprintf("DATETIME%v NULL", precision)
 				}
 			}
 		default:
@@ -118,7 +120,7 @@ func (s *mysql) DataTypeOf(field *StructField) string {
 	}
 
 	if sqlType == "" {
-		panic(fmt.Sprintf("invalid sql type %s (%s) for mysql", dataValue.Type().Name(), dataValue.Kind().String()))
+		panic(fmt.Sprintf("invalid sql type %s (%s) in field %s for mysql", dataValue.Type().Name(), dataValue.Kind().String(), field.Name))
 	}
 
 	if strings.TrimSpace(additionalType) == "" {
@@ -137,13 +139,21 @@ func (s mysql) ModifyColumn(tableName string, columnName string, typ string) err
 	return err
 }
 
-func (s mysql) LimitAndOffsetSQL(limit, offset interface{}) (sql string) {
+func (s mysql) LimitAndOffsetSQL(limit, offset interface{}) (sql string, err error) {
 	if limit != nil {
-		if parsedLimit, err := strconv.ParseInt(fmt.Sprint(limit), 0, 0); err == nil && parsedLimit >= 0 {
+		parsedLimit, err := s.parseInt(limit)
+		if err != nil {
+			return "", err
+		}
+		if parsedLimit >= 0 {
 			sql += fmt.Sprintf(" LIMIT %d", parsedLimit)
 
 			if offset != nil {
-				if parsedOffset, err := strconv.ParseInt(fmt.Sprint(offset), 0, 0); err == nil && parsedOffset >= 0 {
+				parsedOffset, err := s.parseInt(offset)
+				if err != nil {
+					return "", err
+				}
+				if parsedOffset >= 0 {
 					sql += fmt.Sprintf(" OFFSET %d", parsedOffset)
 				}
 			}
@@ -159,6 +169,40 @@ func (s mysql) HasForeignKey(tableName string, foreignKeyName string) bool {
 	return count > 0
 }
 
+func (s mysql) HasTable(tableName string) bool {
+	currentDatabase, tableName := currentDatabaseAndTable(&s, tableName)
+	var name string
+	// allow mysql database name with '-' character
+	if err := s.db.QueryRow(fmt.Sprintf("SHOW TABLES FROM `%s` WHERE `Tables_in_%s` = ?", currentDatabase, currentDatabase), tableName).Scan(&name); err != nil {
+		if err == sql.ErrNoRows {
+			return false
+		}
+		panic(err)
+	} else {
+		return true
+	}
+}
+
+func (s mysql) HasIndex(tableName string, indexName string) bool {
+	currentDatabase, tableName := currentDatabaseAndTable(&s, tableName)
+	if rows, err := s.db.Query(fmt.Sprintf("SHOW INDEXES FROM `%s` FROM `%s` WHERE Key_name = ?", tableName, currentDatabase), indexName); err != nil {
+		panic(err)
+	} else {
+		defer rows.Close()
+		return rows.Next()
+	}
+}
+
+func (s mysql) HasColumn(tableName string, columnName string) bool {
+	currentDatabase, tableName := currentDatabaseAndTable(&s, tableName)
+	if rows, err := s.db.Query(fmt.Sprintf("SHOW COLUMNS FROM `%s` FROM `%s` WHERE Field = ?", tableName, currentDatabase), columnName); err != nil {
+		panic(err)
+	} else {
+		defer rows.Close()
+		return rows.Next()
+	}
+}
+
 func (s mysql) CurrentDatabase() (name string) {
 	s.db.QueryRow("SELECT DATABASE()").Scan(&name)
 	return
@@ -178,7 +222,7 @@ func (s mysql) BuildKeyName(kind, tableName string, fields ...string) string {
 	bs := h.Sum(nil)
 
 	// sha1 is 40 characters, keep first 24 characters of destination
-	destRunes := []rune(regexp.MustCompile("[^a-zA-Z0-9]+").ReplaceAllString(fields[0], "_"))
+	destRunes := []rune(keyNameRegex.ReplaceAllString(fields[0], "_"))
 	if len(destRunes) > 24 {
 		destRunes = destRunes[:24]
 	}
@@ -186,6 +230,17 @@ func (s mysql) BuildKeyName(kind, tableName string, fields ...string) string {
 	return fmt.Sprintf("%s%x", string(destRunes), bs)
 }
 
+// NormalizeIndexAndColumn returns index name and column name for specify an index prefix length if needed
+func (mysql) NormalizeIndexAndColumn(indexName, columnName string) (string, string) {
+	submatch := mysqlIndexRegex.FindStringSubmatch(indexName)
+	if len(submatch) != 3 {
+		return indexName, columnName
+	}
+	indexName = submatch[1]
+	columnName = fmt.Sprintf("%s(%s)", columnName, submatch[2])
+	return indexName, columnName
+}
+
 func (mysql) DefaultValueStr() string {
 	return "VALUES()"
 }

+ 4 - 0
vendor/github.com/jinzhu/gorm/dialect_postgres.go

@@ -120,6 +120,10 @@ func (s postgres) CurrentDatabase() (name string) {
 	return
 }
 
+func (s postgres) LastInsertIDOutputInterstitial(tableName, key string, columns []string) string {
+	return ""
+}
+
 func (s postgres) LastInsertIDReturningSuffix(tableName, key string) string {
 	return fmt.Sprintf("RETURNING %v.%v", tableName, key)
 }

+ 7 - 7
vendor/github.com/jinzhu/gorm/errors.go

@@ -6,11 +6,11 @@ import (
 )
 
 var (
-	// ErrRecordNotFound record not found error, happens when only haven't find any matched data when looking up with a struct, finding a slice won't return this error
+	// 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
 	ErrRecordNotFound = errors.New("record not found")
-	// ErrInvalidSQL invalid SQL error, happens when you passed invalid SQL
+	// ErrInvalidSQL occurs when you attempt a query with invalid SQL
 	ErrInvalidSQL = errors.New("invalid SQL")
-	// ErrInvalidTransaction invalid transaction when you are trying to `Commit` or `Rollback`
+	// ErrInvalidTransaction occurs when you are trying to `Commit` or `Rollback`
 	ErrInvalidTransaction = errors.New("no valid transaction")
 	// ErrCantStartTransaction can't start transaction when you are trying to start one with `Begin`
 	ErrCantStartTransaction = errors.New("can't start transaction")
@@ -21,7 +21,7 @@ var (
 // Errors contains all happened errors
 type Errors []error
 
-// IsRecordNotFoundError returns current error has record not found error or not
+// IsRecordNotFoundError returns true if error contains a RecordNotFound error
 func IsRecordNotFoundError(err error) bool {
 	if errs, ok := err.(Errors); ok {
 		for _, err := range errs {
@@ -33,12 +33,12 @@ func IsRecordNotFoundError(err error) bool {
 	return err == ErrRecordNotFound
 }
 
-// GetErrors gets all happened errors
+// GetErrors gets all errors that have occurred and returns a slice of errors (Error type)
 func (errs Errors) GetErrors() []error {
 	return errs
 }
 
-// Add adds an error
+// Add adds an error to a given slice of errors
 func (errs Errors) Add(newErrors ...error) Errors {
 	for _, err := range newErrors {
 		if err == nil {
@@ -62,7 +62,7 @@ func (errs Errors) Add(newErrors ...error) Errors {
 	return errs
 }
 
-// Error format happened errors
+// Error takes a slice of all errors that have occurred and returns it as a formatted string
 func (errs Errors) Error() string {
 	var errors = []string{}
 	for _, e := range errs {

+ 9 - 1
vendor/github.com/jinzhu/gorm/field.go

@@ -2,6 +2,7 @@ package gorm
 
 import (
 	"database/sql"
+	"database/sql/driver"
 	"errors"
 	"fmt"
 	"reflect"
@@ -44,7 +45,14 @@ func (field *Field) Set(value interface{}) (err error) {
 			if reflectValue.Type().ConvertibleTo(fieldValue.Type()) {
 				fieldValue.Set(reflectValue.Convert(fieldValue.Type()))
 			} else if scanner, ok := fieldValue.Addr().Interface().(sql.Scanner); ok {
-				err = scanner.Scan(reflectValue.Interface())
+				v := reflectValue.Interface()
+				if valuer, ok := v.(driver.Valuer); ok {
+					if v, err = valuer.Value(); err == nil {
+						err = scanner.Scan(v)
+					}
+				} else {
+					err = scanner.Scan(v)
+				}
 			} else {
 				err = fmt.Errorf("could not convert argument of field %s from %s to %s", field.Name, reflectValue.Type(), fieldValue.Type())
 			}

+ 5 - 1
vendor/github.com/jinzhu/gorm/interface.go

@@ -1,6 +1,9 @@
 package gorm
 
-import "database/sql"
+import (
+	"context"
+	"database/sql"
+)
 
 // SQLCommon is the minimal database connection functionality gorm requires.  Implemented by *sql.DB.
 type SQLCommon interface {
@@ -12,6 +15,7 @@ type SQLCommon interface {
 
 type sqlDb interface {
 	Begin() (*sql.Tx, error)
+	BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
 }
 
 type sqlTx interface {

+ 24 - 2
vendor/github.com/jinzhu/gorm/logger.go

@@ -39,6 +39,15 @@ var LogFormatter = func(values ...interface{}) (messages []interface{}) {
 
 		messages = []interface{}{source, currentTime}
 
+		if len(values) == 2 {
+			//remove the line break
+			currentTime = currentTime[1:]
+			//remove the brackets
+			source = fmt.Sprintf("\033[35m%v\033[0m", values[1])
+
+			messages = []interface{}{currentTime, source}
+		}
+
 		if level == "sql" {
 			// duration
 			messages = append(messages, fmt.Sprintf(" \033[36;1m[%.2fms]\033[0m ", float64(values[2].(time.Duration).Nanoseconds()/1e4)/100.0))
@@ -49,7 +58,11 @@ var LogFormatter = func(values ...interface{}) (messages []interface{}) {
 				if indirectValue.IsValid() {
 					value = indirectValue.Interface()
 					if t, ok := value.(time.Time); ok {
-						formattedValues = append(formattedValues, fmt.Sprintf("'%v'", t.Format("2006-01-02 15:04:05")))
+						if t.IsZero() {
+							formattedValues = append(formattedValues, fmt.Sprintf("'%v'", "0000-00-00 00:00:00"))
+						} else {
+							formattedValues = append(formattedValues, fmt.Sprintf("'%v'", t.Format("2006-01-02 15:04:05")))
+						}
 					} else if b, ok := value.([]byte); ok {
 						if str := string(b); isPrintable(str) {
 							formattedValues = append(formattedValues, fmt.Sprintf("'%v'", str))
@@ -63,7 +76,12 @@ var LogFormatter = func(values ...interface{}) (messages []interface{}) {
 							formattedValues = append(formattedValues, "NULL")
 						}
 					} else {
-						formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value))
+						switch value.(type) {
+						case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, bool:
+							formattedValues = append(formattedValues, fmt.Sprintf("%v", value))
+						default:
+							formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value))
+						}
 					}
 				} else {
 					formattedValues = append(formattedValues, "NULL")
@@ -117,3 +135,7 @@ type Logger struct {
 func (logger Logger) Print(values ...interface{}) {
 	logger.Println(LogFormatter(values...)...)
 }
+
+type nopLogger struct{}
+
+func (nopLogger) Print(values ...interface{}) {}

+ 116 - 19
vendor/github.com/jinzhu/gorm/main.go

@@ -1,6 +1,7 @@
 package gorm
 
 import (
+	"context"
 	"database/sql"
 	"errors"
 	"fmt"
@@ -12,6 +13,7 @@ import (
 
 // DB contains information for current db connection
 type DB struct {
+	sync.RWMutex
 	Value        interface{}
 	Error        error
 	RowsAffected int64
@@ -19,7 +21,7 @@ type DB struct {
 	// single db
 	db                SQLCommon
 	blockGlobalUpdate bool
-	logMode           int
+	logMode           logModeValue
 	logger            logger
 	search            *search
 	values            sync.Map
@@ -29,8 +31,19 @@ type DB struct {
 	callbacks     *Callback
 	dialect       Dialect
 	singularTable bool
+
+	// function to be used to override the creating of a new timestamp
+	nowFuncOverride func() time.Time
 }
 
+type logModeValue int
+
+const (
+	defaultLogMode logModeValue = iota
+	noLogMode
+	detailedLogMode
+)
+
 // Open initialize a new db connection, need to import driver first, e.g:
 //
 //     import _ "github.com/go-sql-driver/mysql"
@@ -72,7 +85,10 @@ func Open(dialect string, args ...interface{}) (db *DB, err error) {
 	db = &DB{
 		db:        dbSQL,
 		logger:    defaultLogger,
-		callbacks: DefaultCallback,
+		
+		// Create a clone of the default logger to avoid mutating a shared object when
+		// multiple gorm connections are created simultaneously.
+		callbacks: DefaultCallback.clone(defaultLogger),
 		dialect:   newDialect(dialect, dbSQL),
 	}
 	db.parent = db
@@ -111,7 +127,10 @@ func (s *DB) Close() error {
 // DB get `*sql.DB` from current connection
 // If the underlying database connection is not a *sql.DB, returns nil
 func (s *DB) DB() *sql.DB {
-	db, _ := s.db.(*sql.DB)
+	db, ok := s.db.(*sql.DB)
+	if !ok {
+		panic("can't support full GORM on currently status, maybe this is a TX instance.")
+	}
 	return db
 }
 
@@ -129,7 +148,7 @@ func (s *DB) Dialect() Dialect {
 //     db.Callback().Create().Register("update_created_at", updateCreated)
 // Refer https://jinzhu.github.io/gorm/development.html#callbacks
 func (s *DB) Callback() *Callback {
-	s.parent.callbacks = s.parent.callbacks.clone()
+	s.parent.callbacks = s.parent.callbacks.clone(s.logger)
 	return s.parent.callbacks
 }
 
@@ -141,13 +160,29 @@ func (s *DB) SetLogger(log logger) {
 // LogMode set log mode, `true` for detailed logs, `false` for no log, default, will only print error logs
 func (s *DB) LogMode(enable bool) *DB {
 	if enable {
-		s.logMode = 2
+		s.logMode = detailedLogMode
 	} else {
-		s.logMode = 1
+		s.logMode = noLogMode
 	}
 	return s
 }
 
+// SetNowFuncOverride set the function to be used when creating a new timestamp
+func (s *DB) SetNowFuncOverride(nowFuncOverride func() time.Time) *DB {
+	s.nowFuncOverride = nowFuncOverride
+	return s
+}
+
+// Get a new timestamp, using the provided nowFuncOverride on the DB instance if set,
+// otherwise defaults to the global NowFunc()
+func (s *DB) nowFunc() time.Time {
+	if s.nowFuncOverride != nil {
+		return s.nowFuncOverride()
+	}
+
+	return NowFunc()
+}
+
 // BlockGlobalUpdate if true, generates an error on update/delete without where clause.
 // This is to prevent eventual error with empty objects updates/deletions
 func (s *DB) BlockGlobalUpdate(enable bool) *DB {
@@ -162,7 +197,8 @@ func (s *DB) HasBlockGlobalUpdate() bool {
 
 // SingularTable use singular table by default
 func (s *DB) SingularTable(enable bool) {
-	modelStructsMap = sync.Map{}
+	s.parent.Lock()
+	defer s.parent.Unlock()
 	s.parent.singularTable = enable
 }
 
@@ -170,11 +206,17 @@ func (s *DB) SingularTable(enable bool) {
 func (s *DB) NewScope(value interface{}) *Scope {
 	dbClone := s.clone()
 	dbClone.Value = value
-	return &Scope{db: dbClone, Search: dbClone.search.clone(), Value: value}
+	scope := &Scope{db: dbClone, Value: value}
+	if s.search != nil {
+		scope.Search = s.search.clone()
+	} else {
+		scope.Search = &search{}
+	}
+	return scope
 }
 
-// QueryExpr returns the query as expr object
-func (s *DB) QueryExpr() *expr {
+// QueryExpr returns the query as SqlExpr object
+func (s *DB) QueryExpr() *SqlExpr {
 	scope := s.NewScope(s.Value)
 	scope.InstanceSet("skip_bindvar", true)
 	scope.prepareQuerySQL()
@@ -183,7 +225,7 @@ func (s *DB) QueryExpr() *expr {
 }
 
 // SubQuery returns the query as sub query
-func (s *DB) SubQuery() *expr {
+func (s *DB) SubQuery() *SqlExpr {
 	scope := s.NewScope(s.Value)
 	scope.InstanceSet("skip_bindvar", true)
 	scope.prepareQuerySQL()
@@ -290,6 +332,7 @@ func (s *DB) Assign(attrs ...interface{}) *DB {
 func (s *DB) First(out interface{}, where ...interface{}) *DB {
 	newScope := s.NewScope(out)
 	newScope.Search.Limit(1)
+
 	return newScope.Set("gorm:order_by_primary_key", "ASC").
 		inlineCondition(where...).callCallbacks(s.parent.callbacks.queries).db
 }
@@ -397,6 +440,7 @@ func (s *DB) FirstOrCreate(out interface{}, where ...interface{}) *DB {
 }
 
 // Update update attributes with callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update
+// WARNING when update with struct, GORM will not update fields that with zero value
 func (s *DB) Update(attrs ...interface{}) *DB {
 	return s.Updates(toSearchableMap(attrs...), true)
 }
@@ -429,7 +473,7 @@ func (s *DB) Save(value interface{}) *DB {
 	if !scope.PrimaryKeyZero() {
 		newDB := scope.callCallbacks(s.parent.callbacks.updates).db
 		if newDB.Error == nil && newDB.RowsAffected == 0 {
-			return s.New().FirstOrCreate(value)
+			return s.New().Table(scope.TableName()).FirstOrCreate(value)
 		}
 		return newDB
 	}
@@ -443,6 +487,7 @@ func (s *DB) Create(value interface{}) *DB {
 }
 
 // Delete delete value match given conditions, if the value has primary key, then will including the primary key as condition
+// WARNING If model has DeletedAt field, GORM will only set field DeletedAt's value to current time
 func (s *DB) Delete(value interface{}, where ...interface{}) *DB {
 	return s.NewScope(value).inlineCondition(where...).callCallbacks(s.parent.callbacks.deletes).db
 }
@@ -486,11 +531,43 @@ func (s *DB) Debug() *DB {
 	return s.clone().LogMode(true)
 }
 
-// Begin begin a transaction
+// Transaction start a transaction as a block,
+// return error will rollback, otherwise to commit.
+func (s *DB) Transaction(fc func(tx *DB) error) (err error) {
+
+	if _, ok := s.db.(*sql.Tx); ok {
+		return fc(s)
+	}
+
+	panicked := true
+	tx := s.Begin()
+	defer func() {
+		// Make sure to rollback when panic, Block error or Commit error
+		if panicked || err != nil {
+			tx.Rollback()
+		}
+	}()
+
+	err = fc(tx)
+
+	if err == nil {
+		err = tx.Commit().Error
+	}
+
+	panicked = false
+	return
+}
+
+// Begin begins a transaction
 func (s *DB) Begin() *DB {
+	return s.BeginTx(context.Background(), &sql.TxOptions{})
+}
+
+// BeginTx begins a transaction with options
+func (s *DB) BeginTx(ctx context.Context, opts *sql.TxOptions) *DB {
 	c := s.clone()
 	if db, ok := c.db.(sqlDb); ok && db != nil {
-		tx, err := db.Begin()
+		tx, err := db.BeginTx(ctx, opts)
 		c.db = interface{}(tx).(SQLCommon)
 
 		c.dialect.SetDB(c.db)
@@ -516,7 +593,26 @@ func (s *DB) Commit() *DB {
 func (s *DB) Rollback() *DB {
 	var emptySQLTx *sql.Tx
 	if db, ok := s.db.(sqlTx); ok && db != nil && db != emptySQLTx {
-		s.AddError(db.Rollback())
+		if err := db.Rollback(); err != nil && err != sql.ErrTxDone {
+			s.AddError(err)
+		}
+	} else {
+		s.AddError(ErrInvalidTransaction)
+	}
+	return s
+}
+
+// RollbackUnlessCommitted rollback a transaction if it has not yet been
+// committed.
+func (s *DB) RollbackUnlessCommitted() *DB {
+	var emptySQLTx *sql.Tx
+	if db, ok := s.db.(sqlTx); ok && db != nil && db != emptySQLTx {
+		err := db.Rollback()
+		// Ignore the error indicating that the transaction has already
+		// been committed.
+		if err != sql.ErrTxDone {
+			s.AddError(err)
+		}
 	} else {
 		s.AddError(ErrInvalidTransaction)
 	}
@@ -716,8 +812,8 @@ func (s *DB) SetJoinTableHandler(source interface{}, column string, handler Join
 func (s *DB) AddError(err error) error {
 	if err != nil {
 		if err != ErrRecordNotFound {
-			if s.logMode == 0 {
-				go s.print(fileWithLineNum(), err)
+			if s.logMode == defaultLogMode {
+				go s.print("error", fileWithLineNum(), err)
 			} else {
 				s.log(err)
 			}
@@ -758,6 +854,7 @@ func (s *DB) clone() *DB {
 		Error:             s.Error,
 		blockGlobalUpdate: s.blockGlobalUpdate,
 		dialect:           newDialect(s.dialect.GetName(), s.db),
+		nowFuncOverride:   s.nowFuncOverride,
 	}
 
 	s.values.Range(func(k, v interface{}) bool {
@@ -780,13 +877,13 @@ func (s *DB) print(v ...interface{}) {
 }
 
 func (s *DB) log(v ...interface{}) {
-	if s != nil && s.logMode == 2 {
+	if s != nil && s.logMode == detailedLogMode {
 		s.print(append([]interface{}{"log", fileWithLineNum()}, v...)...)
 	}
 }
 
 func (s *DB) slog(sql string, t time.Time, vars ...interface{}) {
-	if s.logMode == 2 {
+	if s.logMode == detailedLogMode {
 		s.print("sql", fileWithLineNum(), NowFunc().Sub(t), sql, vars, s.RowsAffected)
 	}
 }

+ 90 - 48
vendor/github.com/jinzhu/gorm/model_struct.go

@@ -17,27 +17,38 @@ var DefaultTableNameHandler = func(db *DB, defaultTableName string) string {
 	return defaultTableName
 }
 
+// lock for mutating global cached model metadata
+var structsLock sync.Mutex
+
+// global cache of model metadata
 var modelStructsMap sync.Map
 
 // ModelStruct model definition
 type ModelStruct struct {
-	PrimaryFields    []*StructField
-	StructFields     []*StructField
-	ModelType        reflect.Type
+	PrimaryFields []*StructField
+	StructFields  []*StructField
+	ModelType     reflect.Type
+
 	defaultTableName string
+	l                sync.Mutex
 }
 
 // TableName returns model's table name
 func (s *ModelStruct) TableName(db *DB) string {
+	s.l.Lock()
+	defer s.l.Unlock()
+
 	if s.defaultTableName == "" && db != nil && s.ModelType != nil {
 		// Set default table name
 		if tabler, ok := reflect.New(s.ModelType).Interface().(tabler); ok {
 			s.defaultTableName = tabler.TableName()
 		} else {
 			tableName := ToTableName(s.ModelType.Name())
-			if db == nil || !db.parent.singularTable {
+			db.parent.RLock()
+			if db == nil || (db.parent != nil && !db.parent.singularTable) {
 				tableName = inflection.Plural(tableName)
 			}
+			db.parent.RUnlock()
 			s.defaultTableName = tableName
 		}
 	}
@@ -65,52 +76,52 @@ type StructField struct {
 }
 
 // TagSettingsSet Sets a tag in the tag settings map
-func (s *StructField) TagSettingsSet(key, val string) {
-	s.tagSettingsLock.Lock()
-	defer s.tagSettingsLock.Unlock()
-	s.TagSettings[key] = val
+func (sf *StructField) TagSettingsSet(key, val string) {
+	sf.tagSettingsLock.Lock()
+	defer sf.tagSettingsLock.Unlock()
+	sf.TagSettings[key] = val
 }
 
 // TagSettingsGet returns a tag from the tag settings
-func (s *StructField) TagSettingsGet(key string) (string, bool) {
-	s.tagSettingsLock.RLock()
-	defer s.tagSettingsLock.RUnlock()
-	val, ok := s.TagSettings[key]
+func (sf *StructField) TagSettingsGet(key string) (string, bool) {
+	sf.tagSettingsLock.RLock()
+	defer sf.tagSettingsLock.RUnlock()
+	val, ok := sf.TagSettings[key]
 	return val, ok
 }
 
 // TagSettingsDelete deletes a tag
-func (s *StructField) TagSettingsDelete(key string) {
-	s.tagSettingsLock.Lock()
-	defer s.tagSettingsLock.Unlock()
-	delete(s.TagSettings, key)
+func (sf *StructField) TagSettingsDelete(key string) {
+	sf.tagSettingsLock.Lock()
+	defer sf.tagSettingsLock.Unlock()
+	delete(sf.TagSettings, key)
 }
 
-func (structField *StructField) clone() *StructField {
+func (sf *StructField) clone() *StructField {
 	clone := &StructField{
-		DBName:          structField.DBName,
-		Name:            structField.Name,
-		Names:           structField.Names,
-		IsPrimaryKey:    structField.IsPrimaryKey,
-		IsNormal:        structField.IsNormal,
-		IsIgnored:       structField.IsIgnored,
-		IsScanner:       structField.IsScanner,
-		HasDefaultValue: structField.HasDefaultValue,
-		Tag:             structField.Tag,
+		DBName:          sf.DBName,
+		Name:            sf.Name,
+		Names:           sf.Names,
+		IsPrimaryKey:    sf.IsPrimaryKey,
+		IsNormal:        sf.IsNormal,
+		IsIgnored:       sf.IsIgnored,
+		IsScanner:       sf.IsScanner,
+		HasDefaultValue: sf.HasDefaultValue,
+		Tag:             sf.Tag,
 		TagSettings:     map[string]string{},
-		Struct:          structField.Struct,
-		IsForeignKey:    structField.IsForeignKey,
+		Struct:          sf.Struct,
+		IsForeignKey:    sf.IsForeignKey,
 	}
 
-	if structField.Relationship != nil {
-		relationship := *structField.Relationship
+	if sf.Relationship != nil {
+		relationship := *sf.Relationship
 		clone.Relationship = &relationship
 	}
 
 	// copy the struct field tagSettings, they should be read-locked while they are copied
-	structField.tagSettingsLock.Lock()
-	defer structField.tagSettingsLock.Unlock()
-	for key, value := range structField.TagSettings {
+	sf.tagSettingsLock.Lock()
+	defer sf.tagSettingsLock.Unlock()
+	for key, value := range sf.TagSettings {
 		clone.TagSettings[key] = value
 	}
 
@@ -141,6 +152,10 @@ func getForeignField(column string, fields []*StructField) *StructField {
 
 // GetModelStruct get value's model struct, relationships based on struct and tag definition
 func (scope *Scope) GetModelStruct() *ModelStruct {
+	return scope.getModelStruct(scope, make([]*StructField, 0))
+}
+
+func (scope *Scope) getModelStruct(rootScope *Scope, allFields []*StructField) *ModelStruct {
 	var modelStruct ModelStruct
 	// Scope value can't be nil
 	if scope.Value == nil {
@@ -158,7 +173,18 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
 	}
 
 	// Get Cached model struct
-	if value, ok := modelStructsMap.Load(reflectType); ok && value != nil {
+	isSingularTable := false
+	if scope.db != nil && scope.db.parent != nil {
+		scope.db.parent.RLock()
+		isSingularTable = scope.db.parent.singularTable
+		scope.db.parent.RUnlock()
+	}
+
+	hashKey := struct {
+		singularTable bool
+		reflectType   reflect.Type
+	}{isSingularTable, reflectType}
+	if value, ok := modelStructsMap.Load(hashKey); ok && value != nil {
 		return value.(*ModelStruct)
 	}
 
@@ -184,7 +210,7 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
 					modelStruct.PrimaryFields = append(modelStruct.PrimaryFields, field)
 				}
 
-				if _, ok := field.TagSettingsGet("DEFAULT"); ok {
+				if _, ok := field.TagSettingsGet("DEFAULT"); ok && !field.IsPrimaryKey {
 					field.HasDefaultValue = true
 				}
 
@@ -215,7 +241,7 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
 					field.IsNormal = true
 				} else if _, ok := field.TagSettingsGet("EMBEDDED"); ok || fieldStruct.Anonymous {
 					// is embedded struct
-					for _, subField := range scope.New(fieldValue).GetModelStruct().StructFields {
+					for _, subField := range scope.New(fieldValue).getModelStruct(rootScope, allFields).StructFields {
 						subField = subField.clone()
 						subField.Names = append([]string{fieldStruct.Name}, subField.Names...)
 						if prefix, ok := field.TagSettingsGet("EMBEDDED_PREFIX"); ok {
@@ -239,6 +265,7 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
 						}
 
 						modelStruct.StructFields = append(modelStruct.StructFields, subField)
+						allFields = append(allFields, subField)
 					}
 					continue
 				} else {
@@ -335,7 +362,7 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
 									}
 
 									joinTableHandler := JoinTableHandler{}
-									joinTableHandler.Setup(relationship, ToTableName(many2many), reflectType, elemType)
+									joinTableHandler.Setup(relationship, many2many, reflectType, elemType)
 									relationship.JoinTableHandler = &joinTableHandler
 									field.Relationship = relationship
 								} else {
@@ -372,7 +399,7 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
 										} else {
 											// generate foreign keys from defined association foreign keys
 											for _, scopeFieldName := range associationForeignKeys {
-												if foreignField := getForeignField(scopeFieldName, modelStruct.StructFields); foreignField != nil {
+												if foreignField := getForeignField(scopeFieldName, allFields); foreignField != nil {
 													foreignKeys = append(foreignKeys, associationType+foreignField.Name)
 													associationForeignKeys = append(associationForeignKeys, foreignField.Name)
 												}
@@ -384,13 +411,13 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
 											for _, foreignKey := range foreignKeys {
 												if strings.HasPrefix(foreignKey, associationType) {
 													associationForeignKey := strings.TrimPrefix(foreignKey, associationType)
-													if foreignField := getForeignField(associationForeignKey, modelStruct.StructFields); foreignField != nil {
+													if foreignField := getForeignField(associationForeignKey, allFields); foreignField != nil {
 														associationForeignKeys = append(associationForeignKeys, associationForeignKey)
 													}
 												}
 											}
 											if len(associationForeignKeys) == 0 && len(foreignKeys) == 1 {
-												associationForeignKeys = []string{scope.PrimaryKey()}
+												associationForeignKeys = []string{rootScope.PrimaryKey()}
 											}
 										} else if len(foreignKeys) != len(associationForeignKeys) {
 											scope.Err(errors.New("invalid foreign keys, should have same length"))
@@ -400,9 +427,13 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
 
 									for idx, foreignKey := range foreignKeys {
 										if foreignField := getForeignField(foreignKey, toFields); foreignField != nil {
-											if associationField := getForeignField(associationForeignKeys[idx], modelStruct.StructFields); associationField != nil {
-												// source foreign keys
+											if associationField := getForeignField(associationForeignKeys[idx], allFields); associationField != nil {
+												// mark field as foreignkey, use global lock to avoid race
+												structsLock.Lock()
 												foreignField.IsForeignKey = true
+												structsLock.Unlock()
+
+												// association foreign keys
 												relationship.AssociationForeignFieldNames = append(relationship.AssociationForeignFieldNames, associationField.Name)
 												relationship.AssociationForeignDBNames = append(relationship.AssociationForeignDBNames, associationField.DBName)
 
@@ -476,7 +507,7 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
 									} else {
 										// generate foreign keys form association foreign keys
 										for _, associationForeignKey := range tagAssociationForeignKeys {
-											if foreignField := getForeignField(associationForeignKey, modelStruct.StructFields); foreignField != nil {
+											if foreignField := getForeignField(associationForeignKey, allFields); foreignField != nil {
 												foreignKeys = append(foreignKeys, associationType+foreignField.Name)
 												associationForeignKeys = append(associationForeignKeys, foreignField.Name)
 											}
@@ -488,13 +519,13 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
 										for _, foreignKey := range foreignKeys {
 											if strings.HasPrefix(foreignKey, associationType) {
 												associationForeignKey := strings.TrimPrefix(foreignKey, associationType)
-												if foreignField := getForeignField(associationForeignKey, modelStruct.StructFields); foreignField != nil {
+												if foreignField := getForeignField(associationForeignKey, allFields); foreignField != nil {
 													associationForeignKeys = append(associationForeignKeys, associationForeignKey)
 												}
 											}
 										}
 										if len(associationForeignKeys) == 0 && len(foreignKeys) == 1 {
-											associationForeignKeys = []string{scope.PrimaryKey()}
+											associationForeignKeys = []string{rootScope.PrimaryKey()}
 										}
 									} else if len(foreignKeys) != len(associationForeignKeys) {
 										scope.Err(errors.New("invalid foreign keys, should have same length"))
@@ -504,9 +535,13 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
 
 								for idx, foreignKey := range foreignKeys {
 									if foreignField := getForeignField(foreignKey, toFields); foreignField != nil {
-										if scopeField := getForeignField(associationForeignKeys[idx], modelStruct.StructFields); scopeField != nil {
+										if scopeField := getForeignField(associationForeignKeys[idx], allFields); scopeField != nil {
+											// mark field as foreignkey, use global lock to avoid race
+											structsLock.Lock()
 											foreignField.IsForeignKey = true
-											// source foreign keys
+											structsLock.Unlock()
+
+											// association foreign keys
 											relationship.AssociationForeignFieldNames = append(relationship.AssociationForeignFieldNames, scopeField.Name)
 											relationship.AssociationForeignDBNames = append(relationship.AssociationForeignDBNames, scopeField.DBName)
 
@@ -564,7 +599,10 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
 								for idx, foreignKey := range foreignKeys {
 									if foreignField := getForeignField(foreignKey, modelStruct.StructFields); foreignField != nil {
 										if associationField := getForeignField(associationForeignKeys[idx], toFields); associationField != nil {
+											// mark field as foreignkey, use global lock to avoid race
+											structsLock.Lock()
 											foreignField.IsForeignKey = true
+											structsLock.Unlock()
 
 											// association foreign keys
 											relationship.AssociationForeignFieldNames = append(relationship.AssociationForeignFieldNames, associationField.Name)
@@ -597,6 +635,7 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
 			}
 
 			modelStruct.StructFields = append(modelStruct.StructFields, field)
+			allFields = append(allFields, field)
 		}
 	}
 
@@ -607,7 +646,7 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
 		}
 	}
 
-	modelStructsMap.Store(reflectType, &modelStruct)
+	modelStructsMap.Store(hashKey, &modelStruct)
 
 	return &modelStruct
 }
@@ -620,6 +659,9 @@ func (scope *Scope) GetStructFields() (fields []*StructField) {
 func parseTagSetting(tags reflect.StructTag) map[string]string {
 	setting := map[string]string{}
 	for _, str := range []string{tags.Get("sql"), tags.Get("gorm")} {
+		if str == "" {
+			continue
+		}
 		tags := strings.Split(str, ";")
 		for _, value := range tags {
 			v := strings.Split(value, ":")

+ 75 - 35
vendor/github.com/jinzhu/gorm/scope.go

@@ -68,7 +68,7 @@ func (scope *Scope) Dialect() Dialect {
 
 // Quote used to quote string to escape them for database
 func (scope *Scope) Quote(str string) string {
-	if strings.Index(str, ".") != -1 {
+	if strings.Contains(str, ".") {
 		newStrs := []string{}
 		for _, str := range strings.Split(str, ".") {
 			newStrs = append(newStrs, scope.Dialect().Quote(str))
@@ -225,7 +225,7 @@ func (scope *Scope) SetColumn(column interface{}, value interface{}) error {
 				updateAttrs[field.DBName] = value
 				return field.Set(value)
 			}
-			if (field.DBName == dbName) || (field.Name == name && mostMatchedField == nil) {
+			if !field.IsIgnored && ((field.DBName == dbName) || (field.Name == name && mostMatchedField == nil)) {
 				mostMatchedField = field
 			}
 		}
@@ -257,7 +257,7 @@ func (scope *Scope) CallMethod(methodName string) {
 func (scope *Scope) AddToVars(value interface{}) string {
 	_, skipBindVar := scope.InstanceGet("skip_bindvar")
 
-	if expr, ok := value.(*expr); ok {
+	if expr, ok := value.(*SqlExpr); ok {
 		exp := expr.expr
 		for _, arg := range expr.args {
 			if skipBindVar {
@@ -330,7 +330,7 @@ func (scope *Scope) TableName() string {
 // QuotedTableName return quoted table name
 func (scope *Scope) QuotedTableName() (name string) {
 	if scope.Search != nil && len(scope.Search.tableName) > 0 {
-		if strings.Index(scope.Search.tableName, " ") != -1 {
+		if strings.Contains(scope.Search.tableName, " ") {
 			return scope.Search.tableName
 		}
 		return scope.Quote(scope.Search.tableName)
@@ -402,7 +402,7 @@ func (scope *Scope) InstanceGet(name string) (interface{}, bool) {
 // Begin start a transaction
 func (scope *Scope) Begin() *Scope {
 	if db, ok := scope.SQLDB().(sqlDb); ok {
-		if tx, err := db.Begin(); err == nil {
+		if tx, err := db.Begin(); scope.Err(err) == nil {
 			scope.db.db = interface{}(tx).(SQLCommon)
 			scope.InstanceSet("gorm:started_transaction", true)
 		}
@@ -590,7 +590,7 @@ func (scope *Scope) buildCondition(clause map[string]interface{}, include bool)
 		}
 		scopeQuotedTableName := newScope.QuotedTableName()
 		for _, field := range newScope.Fields() {
-			if !field.IsIgnored && !field.IsBlank {
+			if !field.IsIgnored && !field.IsBlank && field.Relationship == nil {
 				sqls = append(sqls, fmt.Sprintf("(%v.%v %s %v)", scopeQuotedTableName, scope.Quote(field.DBName), equalSQL, scope.AddToVars(field.Field.Interface())))
 			}
 		}
@@ -785,7 +785,7 @@ func (scope *Scope) orderSQL() string {
 	for _, order := range scope.Search.orders {
 		if str, ok := order.(string); ok {
 			orders = append(orders, scope.quoteIfPossible(str))
-		} else if expr, ok := order.(*expr); ok {
+		} else if expr, ok := order.(*SqlExpr); ok {
 			exp := expr.expr
 			for _, arg := range expr.args {
 				exp = strings.Replace(exp, "?", scope.AddToVars(arg), 1)
@@ -797,7 +797,9 @@ func (scope *Scope) orderSQL() string {
 }
 
 func (scope *Scope) limitAndOffsetSQL() string {
-	return scope.Dialect().LimitAndOffsetSQL(scope.Search.limit, scope.Search.offset)
+	sql, err := scope.Dialect().LimitAndOffsetSQL(scope.Search.limit, scope.Search.offset)
+	scope.Err(err)
+	return sql
 }
 
 func (scope *Scope) groupSQL() string {
@@ -839,12 +841,16 @@ func (scope *Scope) joinsSQL() string {
 }
 
 func (scope *Scope) prepareQuerySQL() {
+	var sql string
 	if scope.Search.raw {
-		scope.Raw(scope.CombinedConditionSql())
+		sql = scope.CombinedConditionSql()
 	} else {
-		scope.Raw(fmt.Sprintf("SELECT %v FROM %v %v", scope.selectSQL(), scope.QuotedTableName(), scope.CombinedConditionSql()))
+		sql = fmt.Sprintf("SELECT %v FROM %v %v", scope.selectSQL(), scope.QuotedTableName(), scope.CombinedConditionSql())
 	}
-	return
+	if str, ok := scope.Get("gorm:query_option"); ok {
+		sql += addExtraSpaceIfExist(fmt.Sprint(str))
+	}
+	scope.Raw(sql)
 }
 
 func (scope *Scope) inlineCondition(values ...interface{}) *Scope {
@@ -855,6 +861,14 @@ func (scope *Scope) inlineCondition(values ...interface{}) *Scope {
 }
 
 func (scope *Scope) callCallbacks(funcs []*func(s *Scope)) *Scope {
+	defer func() {
+		if err := recover(); err != nil {
+			if db, ok := scope.db.db.(sqlTx); ok {
+				db.Rollback()
+			}
+			panic(err)
+		}
+	}()
 	for _, f := range funcs {
 		(*f)(scope)
 		if scope.skipLeft {
@@ -864,7 +878,7 @@ func (scope *Scope) callCallbacks(funcs []*func(s *Scope)) *Scope {
 	return scope
 }
 
-func convertInterfaceToMap(values interface{}, withIgnoredField bool) map[string]interface{} {
+func convertInterfaceToMap(values interface{}, withIgnoredField bool, db *DB) map[string]interface{} {
 	var attrs = map[string]interface{}{}
 
 	switch value := values.(type) {
@@ -872,7 +886,7 @@ func convertInterfaceToMap(values interface{}, withIgnoredField bool) map[string
 		return value
 	case []interface{}:
 		for _, v := range value {
-			for key, value := range convertInterfaceToMap(v, withIgnoredField) {
+			for key, value := range convertInterfaceToMap(v, withIgnoredField, db) {
 				attrs[key] = value
 			}
 		}
@@ -885,7 +899,7 @@ func convertInterfaceToMap(values interface{}, withIgnoredField bool) map[string
 				attrs[ToColumnName(key.Interface().(string))] = reflectValue.MapIndex(key).Interface()
 			}
 		default:
-			for _, field := range (&Scope{Value: values}).Fields() {
+			for _, field := range (&Scope{Value: values, db: db}).Fields() {
 				if !field.IsBlank && (withIgnoredField || !field.IsIgnored) {
 					attrs[field.DBName] = field.Field.Interface()
 				}
@@ -897,27 +911,31 @@ func convertInterfaceToMap(values interface{}, withIgnoredField bool) map[string
 
 func (scope *Scope) updatedAttrsWithValues(value interface{}) (results map[string]interface{}, hasUpdate bool) {
 	if scope.IndirectValue().Kind() != reflect.Struct {
-		return convertInterfaceToMap(value, false), true
+		return convertInterfaceToMap(value, false, scope.db), true
 	}
 
 	results = map[string]interface{}{}
 
-	for key, value := range convertInterfaceToMap(value, true) {
-		if field, ok := scope.FieldByName(key); ok && scope.changeableField(field) {
-			if _, ok := value.(*expr); ok {
-				hasUpdate = true
-				results[field.DBName] = value
-			} else {
-				err := field.Set(value)
-				if field.IsNormal && !field.IsIgnored {
+	for key, value := range convertInterfaceToMap(value, true, scope.db) {
+		if field, ok := scope.FieldByName(key); ok {
+			if scope.changeableField(field) {
+				if _, ok := value.(*SqlExpr); ok {
 					hasUpdate = true
-					if err == ErrUnaddressable {
-						results[field.DBName] = value
-					} else {
-						results[field.DBName] = field.Field.Interface()
+					results[field.DBName] = value
+				} else {
+					err := field.Set(value)
+					if field.IsNormal && !field.IsIgnored {
+						hasUpdate = true
+						if err == ErrUnaddressable {
+							results[field.DBName] = value
+						} else {
+							results[field.DBName] = field.Field.Interface()
+						}
 					}
 				}
 			}
+		} else {
+			results[key] = value
 		}
 	}
 	return
@@ -976,6 +994,10 @@ func (scope *Scope) pluck(column string, value interface{}) *Scope {
 		return scope
 	}
 
+	if dest.Len() > 0 {
+		dest.Set(reflect.Zero(dest.Type()))
+	}
+
 	if query, ok := scope.Search.selects["query"]; !ok || !scope.isQueryForColumn(query, column) {
 		scope.Search.Select(column)
 	}
@@ -999,8 +1021,15 @@ func (scope *Scope) pluck(column string, value interface{}) *Scope {
 func (scope *Scope) count(value interface{}) *Scope {
 	if query, ok := scope.Search.selects["query"]; !ok || !countingQueryRegexp.MatchString(fmt.Sprint(query)) {
 		if len(scope.Search.group) != 0 {
-			scope.Search.Select("count(*) FROM ( SELECT count(*) as name ")
-			scope.Search.group += " ) AS count_table"
+			if len(scope.Search.havingConditions) != 0 {
+				scope.prepareQuerySQL()
+				scope.Search = &search{}
+				scope.Search.Select("count(*)")
+				scope.Search.Table(fmt.Sprintf("( %s ) AS count_table", scope.SQL))
+			} else {
+				scope.Search.Select("count(*) FROM ( SELECT count(*) as name ")
+				scope.Search.group += " ) AS count_table"
+			}
 		} else {
 			scope.Search.Select("count(*)")
 		}
@@ -1175,7 +1204,7 @@ func (scope *Scope) createTable() *Scope {
 }
 
 func (scope *Scope) dropTable() *Scope {
-	scope.Raw(fmt.Sprintf("DROP TABLE %v%s", scope.QuotedTableName(), scope.getTableOptions())).Exec()
+	scope.Raw(fmt.Sprintf("DROP TABLE %v", scope.QuotedTableName())).Exec()
 	return scope
 }
 
@@ -1269,7 +1298,8 @@ func (scope *Scope) autoIndex() *Scope {
 				if name == "INDEX" || name == "" {
 					name = scope.Dialect().BuildKeyName("idx", scope.TableName(), field.DBName)
 				}
-				indexes[name] = append(indexes[name], field.DBName)
+				name, column := scope.Dialect().NormalizeIndexAndColumn(name, field.DBName)
+				indexes[name] = append(indexes[name], column)
 			}
 		}
 
@@ -1280,7 +1310,8 @@ func (scope *Scope) autoIndex() *Scope {
 				if name == "UNIQUE_INDEX" || name == "" {
 					name = scope.Dialect().BuildKeyName("uix", scope.TableName(), field.DBName)
 				}
-				uniqueIndexes[name] = append(uniqueIndexes[name], field.DBName)
+				name, column := scope.Dialect().NormalizeIndexAndColumn(name, field.DBName)
+				uniqueIndexes[name] = append(uniqueIndexes[name], column)
 			}
 		}
 	}
@@ -1301,6 +1332,7 @@ func (scope *Scope) autoIndex() *Scope {
 }
 
 func (scope *Scope) getColumnAsArray(columns []string, values ...interface{}) (results [][]interface{}) {
+	resultMap := make(map[string][]interface{})
 	for _, value := range values {
 		indirectValue := indirect(reflect.ValueOf(value))
 
@@ -1319,7 +1351,10 @@ func (scope *Scope) getColumnAsArray(columns []string, values ...interface{}) (r
 				}
 
 				if hasValue {
-					results = append(results, result)
+					h := fmt.Sprint(result...)
+					if _, exist := resultMap[h]; !exist {
+						resultMap[h] = result
+					}
 				}
 			}
 		case reflect.Struct:
@@ -1334,11 +1369,16 @@ func (scope *Scope) getColumnAsArray(columns []string, values ...interface{}) (r
 			}
 
 			if hasValue {
-				results = append(results, result)
+				h := fmt.Sprint(result...)
+				if _, exist := resultMap[h]; !exist {
+					resultMap[h] = result
+				}
 			}
 		}
 	}
-
+	for _, v := range resultMap {
+		results = append(results, v)
+	}
 	return
 }
 

+ 52 - 2
vendor/github.com/jinzhu/gorm/search.go

@@ -32,7 +32,57 @@ type searchPreload struct {
 }
 
 func (s *search) clone() *search {
-	clone := *s
+	clone := search{
+		db:               s.db,
+		whereConditions:  make([]map[string]interface{}, len(s.whereConditions)),
+		orConditions:     make([]map[string]interface{}, len(s.orConditions)),
+		notConditions:    make([]map[string]interface{}, len(s.notConditions)),
+		havingConditions: make([]map[string]interface{}, len(s.havingConditions)),
+		joinConditions:   make([]map[string]interface{}, len(s.joinConditions)),
+		initAttrs:        make([]interface{}, len(s.initAttrs)),
+		assignAttrs:      make([]interface{}, len(s.assignAttrs)),
+		selects:          s.selects,
+		omits:            make([]string, len(s.omits)),
+		orders:           make([]interface{}, len(s.orders)),
+		preload:          make([]searchPreload, len(s.preload)),
+		offset:           s.offset,
+		limit:            s.limit,
+		group:            s.group,
+		tableName:        s.tableName,
+		raw:              s.raw,
+		Unscoped:         s.Unscoped,
+		ignoreOrderQuery: s.ignoreOrderQuery,
+	}
+	for i, value := range s.whereConditions {
+		clone.whereConditions[i] = value
+	}
+	for i, value := range s.orConditions {
+		clone.orConditions[i] = value
+	}
+	for i, value := range s.notConditions {
+		clone.notConditions[i] = value
+	}
+	for i, value := range s.havingConditions {
+		clone.havingConditions[i] = value
+	}
+	for i, value := range s.joinConditions {
+		clone.joinConditions[i] = value
+	}
+	for i, value := range s.initAttrs {
+		clone.initAttrs[i] = value
+	}
+	for i, value := range s.assignAttrs {
+		clone.assignAttrs[i] = value
+	}
+	for i, value := range s.omits {
+		clone.omits[i] = value
+	}
+	for i, value := range s.orders {
+		clone.orders[i] = value
+	}
+	for i, value := range s.preload {
+		clone.preload[i] = value
+	}
 	return &clone
 }
 
@@ -98,7 +148,7 @@ func (s *search) Group(query string) *search {
 }
 
 func (s *search) Having(query interface{}, values ...interface{}) *search {
-	if val, ok := query.(*expr); ok {
+	if val, ok := query.(*SqlExpr); ok {
 		s.havingConditions = append(s.havingConditions, map[string]interface{}{"query": val.expr, "args": val.args})
 	} else {
 		s.havingConditions = append(s.havingConditions, map[string]interface{}{"query": query, "args": values})

+ 3 - 3
vendor/github.com/jinzhu/gorm/utils.go

@@ -58,15 +58,15 @@ func newSafeMap() *safeMap {
 }
 
 // SQL expression
-type expr struct {
+type SqlExpr struct {
 	expr string
 	args []interface{}
 }
 
 // Expr generate raw SQL expression, for example:
 //     DB.Model(&product).Update("price", gorm.Expr("price * ? + ?", 2, 100))
-func Expr(expression string, args ...interface{}) *expr {
-	return &expr{expr: expression, args: args}
+func Expr(expression string, args ...interface{}) *SqlExpr {
+	return &SqlExpr{expr: expression, args: args}
 }
 
 func indirect(reflectValue reflect.Value) reflect.Value {

+ 23 - 22
vendor/github.com/jinzhu/gorm/wercker.yml

@@ -9,22 +9,22 @@ services:
           MYSQL_USER: gorm
           MYSQL_PASSWORD: gorm
           MYSQL_RANDOM_ROOT_PASSWORD: "yes"
-    - name: mysql57
-      id: mysql:5.7
+    - name: mysql
+      id: mysql:latest
       env:
           MYSQL_DATABASE: gorm
           MYSQL_USER: gorm
           MYSQL_PASSWORD: gorm
           MYSQL_RANDOM_ROOT_PASSWORD: "yes"
-    - name: mysql56
-      id: mysql:5.6
+    - name: mysql57
+      id: mysql:5.7
       env:
           MYSQL_DATABASE: gorm
           MYSQL_USER: gorm
           MYSQL_PASSWORD: gorm
           MYSQL_RANDOM_ROOT_PASSWORD: "yes"
-    - name: mysql55
-      id: mysql:5.5
+    - name: mysql56
+      id: mysql:5.6
       env:
           MYSQL_DATABASE: gorm
           MYSQL_USER: gorm
@@ -83,7 +83,7 @@ build:
                 code: |
                     cd $WERCKER_SOURCE_DIR
                     go version
-                    go get -t ./...
+                    go get -t -v ./...
 
         # Build the project
         - script:
@@ -95,54 +95,55 @@ build:
         - script:
                 name: test sqlite
                 code: |
-                    go test ./...
+                    go test -race -v ./...
 
         - script:
                 name: test mariadb
                 code: |
-                    GORM_DIALECT=mysql GORM_DSN="gorm:gorm@tcp(mariadb:3306)/gorm?charset=utf8&parseTime=True" go test ./...
+                    GORM_DIALECT=mysql GORM_DSN="gorm:gorm@tcp(mariadb:3306)/gorm?charset=utf8&parseTime=True" go test -race ./...
 
         - script:
-                name: test mysql5.7
+                name: test mysql
                 code: |
-                    GORM_DIALECT=mysql GORM_DSN="gorm:gorm@tcp(mysql57:3306)/gorm?charset=utf8&parseTime=True" go test ./...
+                    GORM_DIALECT=mysql GORM_DSN="gorm:gorm@tcp(mysql:3306)/gorm?charset=utf8&parseTime=True" go test -race ./...
 
         - script:
-                name: test mysql5.6
+                name: test mysql5.7
                 code: |
-                    GORM_DIALECT=mysql GORM_DSN="gorm:gorm@tcp(mysql56:3306)/gorm?charset=utf8&parseTime=True" go test ./...
+                    GORM_DIALECT=mysql GORM_DSN="gorm:gorm@tcp(mysql57:3306)/gorm?charset=utf8&parseTime=True" go test -race ./...
 
         - script:
-                name: test mysql5.5
+                name: test mysql5.6
                 code: |
-                    GORM_DIALECT=mysql GORM_DSN="gorm:gorm@tcp(mysql55:3306)/gorm?charset=utf8&parseTime=True" go test ./...
+                    GORM_DIALECT=mysql GORM_DSN="gorm:gorm@tcp(mysql56:3306)/gorm?charset=utf8&parseTime=True" go test -race ./...
 
         - script:
                 name: test postgres
                 code: |
-                    GORM_DIALECT=postgres GORM_DSN="host=postgres user=gorm password=gorm DB.name=gorm port=5432 sslmode=disable" go test ./...
+                    GORM_DIALECT=postgres GORM_DSN="host=postgres user=gorm password=gorm DB.name=gorm port=5432 sslmode=disable" go test -race ./...
 
         - script:
                 name: test postgres96
                 code: |
-                    GORM_DIALECT=postgres GORM_DSN="host=postgres96 user=gorm password=gorm DB.name=gorm port=5432 sslmode=disable" go test ./...
+                    GORM_DIALECT=postgres GORM_DSN="host=postgres96 user=gorm password=gorm DB.name=gorm port=5432 sslmode=disable" go test -race ./...
 
         - script:
                 name: test postgres95
                 code: |
-                    GORM_DIALECT=postgres GORM_DSN="host=postgres95 user=gorm password=gorm DB.name=gorm port=5432 sslmode=disable" go test ./...
+                    GORM_DIALECT=postgres GORM_DSN="host=postgres95 user=gorm password=gorm DB.name=gorm port=5432 sslmode=disable" go test -race ./...
 
         - script:
                 name: test postgres94
                 code: |
-                    GORM_DIALECT=postgres GORM_DSN="host=postgres94 user=gorm password=gorm DB.name=gorm port=5432 sslmode=disable" go test ./...
+                    GORM_DIALECT=postgres GORM_DSN="host=postgres94 user=gorm password=gorm DB.name=gorm port=5432 sslmode=disable" go test -race ./...
 
         - script:
                 name: test postgres93
                 code: |
-                    GORM_DIALECT=postgres GORM_DSN="host=postgres93 user=gorm password=gorm DB.name=gorm port=5432 sslmode=disable" go test ./...
+                    GORM_DIALECT=postgres GORM_DSN="host=postgres93 user=gorm password=gorm DB.name=gorm port=5432 sslmode=disable" go test -race ./...
 
         - script:
-                name: test mssql
+                name: codecov
                 code: |
-                    GORM_DIALECT=mssql GORM_DSN="sqlserver://gorm:LoremIpsum86@mssql:1433?database=gorm" go test ./...
+                    go test -race -coverprofile=coverage.txt -covermode=atomic ./...
+                    bash <(curl -s https://codecov.io/bash)

+ 3 - 3
vendor/vendor.json

@@ -741,10 +741,10 @@
 			"revisionTime": "2018-08-02T23:36:05Z"
 		},
 		{
-			"checksumSHA1": "WDpDbiRNtez+uaR3w0WlglNe1cg=",
+			"checksumSHA1": "fdijS3bWi3PCE9gBBKkTW1zc9TY=",
 			"path": "github.com/jinzhu/gorm",
-			"revision": "123d4f50ef8a8209ee8434daa41c6045a9111864",
-			"revisionTime": "2018-09-09T23:11:00Z"
+			"revision": "5c235b72a414e448d1f441aba24a47fd6eb976f4",
+			"revisionTime": "2021-11-20T01:15:37Z"
 		},
 		{
 			"checksumSHA1": "4eelJOSLZoDzLuaJvgilOBVNovU=",