@@ -17,6 +17,10 @@ var DefaultTableNameHandler = func(db *DB, defaultTableName string) string {
17
17
return defaultTableName
18
18
}
19
19
20
+ // lock for mutating global cached model metadata
21
+ var structsLock sync.Mutex
22
+
23
+ // global cache of model metadata
20
24
var modelStructsMap sync.Map
21
25
22
26
// ModelStruct model definition
@@ -419,8 +423,12 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
419
423
for idx , foreignKey := range foreignKeys {
420
424
if foreignField := getForeignField (foreignKey , toFields ); foreignField != nil {
421
425
if associationField := getForeignField (associationForeignKeys [idx ], modelStruct .StructFields ); associationField != nil {
422
- // source foreign keys
426
+ // mark field as foreignkey, use global lock to avoid race
427
+ structsLock .Lock ()
423
428
foreignField .IsForeignKey = true
429
+ structsLock .Unlock ()
430
+
431
+ // association foreign keys
424
432
relationship .AssociationForeignFieldNames = append (relationship .AssociationForeignFieldNames , associationField .Name )
425
433
relationship .AssociationForeignDBNames = append (relationship .AssociationForeignDBNames , associationField .DBName )
426
434
@@ -523,8 +531,12 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
523
531
for idx , foreignKey := range foreignKeys {
524
532
if foreignField := getForeignField (foreignKey , toFields ); foreignField != nil {
525
533
if scopeField := getForeignField (associationForeignKeys [idx ], modelStruct .StructFields ); scopeField != nil {
534
+ // mark field as foreignkey, use global lock to avoid race
535
+ structsLock .Lock ()
526
536
foreignField .IsForeignKey = true
527
- // source foreign keys
537
+ structsLock .Unlock ()
538
+
539
+ // association foreign keys
528
540
relationship .AssociationForeignFieldNames = append (relationship .AssociationForeignFieldNames , scopeField .Name )
529
541
relationship .AssociationForeignDBNames = append (relationship .AssociationForeignDBNames , scopeField .DBName )
530
542
@@ -582,7 +594,10 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
582
594
for idx , foreignKey := range foreignKeys {
583
595
if foreignField := getForeignField (foreignKey , modelStruct .StructFields ); foreignField != nil {
584
596
if associationField := getForeignField (associationForeignKeys [idx ], toFields ); associationField != nil {
597
+ // mark field as foreignkey, use global lock to avoid race
598
+ structsLock .Lock ()
585
599
foreignField .IsForeignKey = true
600
+ structsLock .Unlock ()
586
601
587
602
// association foreign keys
588
603
relationship .AssociationForeignFieldNames = append (relationship .AssociationForeignFieldNames , associationField .Name )
0 commit comments