Skip to content

Commit

Permalink
Use sync.Map for DB.values (go-gorm#2064)
Browse files Browse the repository at this point in the history
* Replace the regular map with a sync.Map to avoid fatal concurrent map reads/writes

* fix the formatting
  • Loading branch information
akhleung authored and jinzhu committed Sep 9, 2018
1 parent d3e666a commit 73e7561
Showing 1 changed file with 7 additions and 8 deletions.
15 changes: 7 additions & 8 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ type DB struct {
logMode int
logger logger
search *search
values map[string]interface{}
values sync.Map

// global db
parent *DB
Expand Down Expand Up @@ -72,7 +72,6 @@ func Open(dialect string, args ...interface{}) (db *DB, err error) {
db = &DB{
db: dbSQL,
logger: defaultLogger,
values: map[string]interface{}{},
callbacks: DefaultCallback,
dialect: newDialect(dialect, dbSQL),
}
Expand Down Expand Up @@ -680,13 +679,13 @@ func (s *DB) Set(name string, value interface{}) *DB {

// InstantSet instant set setting, will affect current db
func (s *DB) InstantSet(name string, value interface{}) *DB {
s.values[name] = value
s.values.Store(name, value)
return s
}

// Get get setting by name
func (s *DB) Get(name string) (value interface{}, ok bool) {
value, ok = s.values[name]
value, ok = s.values.Load(name)
return
}

Expand Down Expand Up @@ -750,16 +749,16 @@ func (s *DB) clone() *DB {
parent: s.parent,
logger: s.logger,
logMode: s.logMode,
values: map[string]interface{}{},
Value: s.Value,
Error: s.Error,
blockGlobalUpdate: s.blockGlobalUpdate,
dialect: newDialect(s.dialect.GetName(), s.db),
}

for key, value := range s.values {
db.values[key] = value
}
s.values.Range(func(k, v interface{}) bool {
db.values.Store(k, v)
return true
})

if s.search == nil {
db.search = &search{limit: -1, offset: -1}
Expand Down

0 comments on commit 73e7561

Please sign in to comment.