Skip to content

Commit 199d13d

Browse files
authored
Merge pull request #460 from VojtechVitek/master
Fix deadlock in sqladapter
2 parents d90922b + d53b67f commit 199d13d

File tree

1 file changed

+16
-19
lines changed

1 file changed

+16
-19
lines changed

Diff for: internal/sqladapter/database.go

+16-19
Original file line numberDiff line numberDiff line change
@@ -151,25 +151,23 @@ func NewBaseDatabase(p PartialDatabase) BaseDatabase {
151151
// BaseDatabase and PartialDatabase
152152
type database struct {
153153
PartialDatabase
154-
baseTx BaseTx
155-
156154
db.Settings
157155

156+
lookupNameOnce sync.Once
157+
name string
158+
159+
mu sync.Mutex // guards ctx, txOptions
158160
ctx context.Context
159161
txOptions *sql.TxOptions
160162

161-
collectionMu sync.Mutex
162-
mu sync.Mutex
163-
164-
name string
163+
sessMu sync.Mutex // guards sess, baseTx
165164
sess *sql.DB
166-
sessMu sync.Mutex
167-
168-
psMu sync.Mutex
165+
baseTx BaseTx
169166

170167
sessID uint64
171168
txID uint64
172169

170+
cacheMu sync.Mutex // guards cachedStatements and cachedCollections
173171
cachedStatements *cache.Cache
174172
cachedCollections *cache.Cache
175173

@@ -243,12 +241,11 @@ func (d *database) Transaction() BaseTx {
243241

244242
// Name returns the database named
245243
func (d *database) Name() string {
246-
d.mu.Lock()
247-
defer d.mu.Unlock()
248-
249-
if d.name == "" {
250-
d.name, _ = d.PartialDatabase.LookupName()
251-
}
244+
d.lookupNameOnce.Do(func() {
245+
if d.name == "" {
246+
d.name, _ = d.PartialDatabase.LookupName()
247+
}
248+
})
252249

253250
return d.name
254251
}
@@ -312,8 +309,8 @@ func (d *database) SetMaxOpenConns(n int) {
312309

313310
// ClearCache removes all caches.
314311
func (d *database) ClearCache() {
315-
d.collectionMu.Lock()
316-
defer d.collectionMu.Unlock()
312+
d.cacheMu.Lock()
313+
defer d.cacheMu.Unlock()
317314
d.cachedCollections.Clear()
318315
d.cachedStatements.Clear()
319316
if d.template != nil {
@@ -376,8 +373,8 @@ func (d *database) Close() error {
376373

377374
// Collection returns a db.Collection given a name. Results are cached.
378375
func (d *database) Collection(name string) db.Collection {
379-
d.collectionMu.Lock()
380-
defer d.collectionMu.Unlock()
376+
d.cacheMu.Lock()
377+
defer d.cacheMu.Unlock()
381378

382379
h := cache.String(name)
383380

0 commit comments

Comments
 (0)