Repository: go-gorm/gorm
Pull request #4346 (2021-05-02 09:47:47)

slim trace if depth
<!--
Make sure these boxes checked before submitting your pull request.

For significant changes, please open an issue to make an agreement on an implementation design/plan first before starting it.
-->
simplify defaultLogger's Trace if depth 



Patch:
diff --git a/logger/logger.go b/logger/logger.go
index f14748c..381199d 100644
--- a/logger/logger.go
+++ b/logger/logger.go
@@ -139,31 +139,34 @@ func (l logger) Error(ctx context.Context, msg string, data ...interface{}) {
 
 // Trace print sql message
 func (l logger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
-	if l.LogLevel > Silent {
-		elapsed := time.Since(begin)
-		switch {
-		case err != nil && l.LogLevel >= Error && (!errors.Is(err, ErrRecordNotFound) || !l.IgnoreRecordNotFoundError):
-			sql, rows := fc()
-			if rows == -1 {
-				l.Printf(l.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, "-", sql)
-			} else {
-				l.Printf(l.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, rows, sql)
-			}
-		case elapsed > l.SlowThreshold && l.SlowThreshold != 0 && l.LogLevel >= Warn:
-			sql, rows := fc()
-			slowLog := fmt.Sprintf("SLOW SQL >= %v", l.SlowThreshold)
-			if rows == -1 {
-				l.Printf(l.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, "-", sql)
-			} else {
-				l.Printf(l.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, rows, sql)
-			}
-		case l.LogLevel == Info:
-			sql, rows := fc()
-			if rows == -1 {
-				l.Printf(l.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, "-", sql)
-			} else {
-				l.Printf(l.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, rows, sql)
-			}
+
+	if l.LogLevel <= Silent {
+		return
+	}
+
+	elapsed := time.Since(begin)
+	switch {
+	case err != nil && l.LogLevel >= Error && (!errors.Is(err, ErrRecordNotFound) || !l.IgnoreRecordNotFoundError):
+		sql, rows := fc()
+		if rows == -1 {
+			l.Printf(l.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, "-", sql)
+		} else {
+			l.Printf(l.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, rows, sql)
+		}
+	case elapsed > l.SlowThreshold && l.SlowThreshold != 0 && l.LogLevel >= Warn:
+		sql, rows := fc()
+		slowLog := fmt.Sprintf("SLOW SQL >= %v", l.SlowThreshold)
+		if rows == -1 {
+			l.Printf(l.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, "-", sql)
+		} else {
+			l.Printf(l.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, rows, sql)
+		}
+	case l.LogLevel == Info:
+		sql, rows := fc()
+		if rows == -1 {
+			l.Printf(l.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, "-", sql)
+		} else {
+			l.Printf(l.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, rows, sql)
 		}
 	}
 }
diff --git a/schema/relationship.go b/schema/relationship.go
index fee96cb..b2d485d 100644
--- a/schema/relationship.go
+++ b/schema/relationship.go
@@ -7,6 +7,7 @@ import (
 
 	"github.com/jinzhu/inflection"
 	"gorm.io/gorm/clause"
+	"gorm.io/gorm/utils"
 )
 
 // RelationshipType relationship type
@@ -404,11 +405,14 @@ func (schema *Schema) guessRelation(relation *Relationship, field *Field, cgl gu
 
 	if len(relation.foreignKeys) > 0 {
 		for _, foreignKey := range relation.foreignKeys {
-			if f := foreignSchema.LookUpField(foreignKey); f != nil {
-				foreignFields = append(foreignFields, f)
-			} else {
+			ff := foreignSchema.LookUpField(foreignKey)
+			pf := primarySchema.LookUpField(foreignKey)
+			isKeySame := utils.ExistsIn(foreignKey, &relation.primaryKeys)
+			if ff == nil || (pf != nil && ff != nil && schema == primarySchema && primarySchema != foreignSchema && !isKeySame) {
 				reguessOrErr()
 				return
+			} else {
+				foreignFields = append(foreignFields, ff)
 			}
 		}
 	} else {
diff --git a/utils/utils.go b/utils/utils.go
index ecba7fb..ce6f35d 100644
--- a/utils/utils.go
+++ b/utils/utils.go
@@ -111,3 +111,15 @@ func ToString(value interface{}) string {
 	}
 	return ""
 }
+
+func ExistsIn(a string, list *[]string) bool {
+	if list == nil {
+		return false
+	}
+	for _, b := range *list {
+		if b == a {
+			return true
+		}
+	}
+	return false
+}


Test patch:
diff --git a/schema/relationship_test.go b/schema/relationship_test.go
index 2971698..391e3a2 100644
--- a/schema/relationship_test.go
+++ b/schema/relationship_test.go
@@ -482,3 +482,22 @@ func TestSameForeignKey(t *testing.T) {
 		},
 	)
 }
+
+func TestBelongsToWithSameForeignKey(t *testing.T) {
+	type Profile struct {
+		gorm.Model
+		Name         string
+		ProfileRefer int
+	}
+
+	type User struct {
+		gorm.Model
+		Profile      Profile `gorm:"ForeignKey:ProfileRefer"`
+		ProfileRefer int
+	}
+
+	checkStructRelation(t, &User{}, Relation{
+		Name: "Profile", Type: schema.BelongsTo, Schema: "User", FieldSchema: "Profile",
+		References: []Reference{{"ID", "Profile", "ProfileRefer", "User", "", false}},
+	})
+}