go-gorm / sharding

High performance table sharding plugin for Gorm.
MIT License
255 stars 48 forks source link

fix conn data race #128

Closed liangjunmo closed 11 months ago

liangjunmo commented 11 months ago

What did this pull request do?

Fix conn DARA RACE issue. There are some related issues like #96.

User Case Description

I use this package for sharding bill table. It runs normally on test environment, but occur DATA RACE issue on online environment.

I write unit test for this issue:

Run this unit test on main branch with go test --race -count=1 -v --run=TestDataRace, it will output:

=== RUN   TestDataRace
==================
WARNING: DATA RACE
Write at 0x00c0000b3048 by goroutine 15:
  command-line-arguments.(*Sharding).switchConn()
      /Users/liangjunmo/workspace/gorm-sharding/sharding.go:268 +0x168
  command-line-arguments.(*Sharding).switchConn-fm()
      <autogenerated>:1 +0x44
  gorm.io/gorm.(*processor).Execute()
      /Users/liangjunmo/.gvm/pkgsets/go1.19.9/global/pkg/mod/gorm.io/gorm@v1.25.1/callbacks.go:130 +0xbe1
  gorm.io/gorm.(*DB).Find()
      /Users/liangjunmo/.gvm/pkgsets/go1.19.9/global/pkg/mod/gorm.io/gorm@v1.25.1/finisher_api.go:172 +0x238
  command-line-arguments.TestDataRace.func1()
      /Users/liangjunmo/workspace/gorm-sharding/sharding_test.go:413 +0x20d

Previous write at 0x00c0000b3048 by goroutine 14:
  command-line-arguments.(*Sharding).switchConn()
      /Users/liangjunmo/workspace/gorm-sharding/sharding.go:268 +0x168
  command-line-arguments.(*Sharding).switchConn-fm()
      <autogenerated>:1 +0x44
  gorm.io/gorm.(*processor).Execute()
      /Users/liangjunmo/.gvm/pkgsets/go1.19.9/global/pkg/mod/gorm.io/gorm@v1.25.1/callbacks.go:130 +0xbe1
  gorm.io/gorm.(*DB).Find()
      /Users/liangjunmo/.gvm/pkgsets/go1.19.9/global/pkg/mod/gorm.io/gorm@v1.25.1/finisher_api.go:172 +0x238
  command-line-arguments.TestDataRace.func1()
      /Users/liangjunmo/workspace/gorm-sharding/sharding_test.go:413 +0x20d

Goroutine 15 (running) created at:
  command-line-arguments.TestDataRace()
      /Users/liangjunmo/workspace/gorm-sharding/sharding_test.go:407 +0x87
  testing.tRunner()
      /Users/liangjunmo/.gvm/gos/go1.19.9/src/testing/testing.go:1446 +0x216
  testing.(*T).Run.func1()
      /Users/liangjunmo/.gvm/gos/go1.19.9/src/testing/testing.go:1493 +0x47

Goroutine 14 (running) created at:
  command-line-arguments.TestDataRace()
      /Users/liangjunmo/workspace/gorm-sharding/sharding_test.go:407 +0x87
  testing.tRunner()
      /Users/liangjunmo/.gvm/gos/go1.19.9/src/testing/testing.go:1446 +0x216
  testing.(*T).Run.func1()
      /Users/liangjunmo/.gvm/gos/go1.19.9/src/testing/testing.go:1493 +0x47
==================
    testing.go:1319: race detected during execution of test
--- FAIL: TestDataRace (0.05s)
=== CONT
    testing.go:1319: race detected during execution of test
FAIL
FAIL    command-line-arguments  0.867s
FAIL