From fabe57aa8a7c3e3e18a9146e7beb121a77d32727 Mon Sep 17 00:00:00 2001 From: maxshuang Date: Mon, 16 May 2022 15:09:10 +0800 Subject: [PATCH] fix(orm): using more proper dsn for sqlite (#394) --- pkg/orm/mock.go | 17 +++++++++++------ pkg/orm/mock_test.go | 6 +----- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/pkg/orm/mock.go b/pkg/orm/mock.go index 170a052d675..818fc6dee75 100644 --- a/pkg/orm/mock.go +++ b/pkg/orm/mock.go @@ -2,24 +2,29 @@ package orm import ( "context" + "fmt" "time" cerrors "github.com/hanfei1991/microcosm/pkg/errors" + "github.com/hanfei1991/microcosm/pkg/uuid" "github.com/pingcap/log" "go.uber.org/zap" "gorm.io/driver/sqlite" "gorm.io/gorm" ) +func randomDBFile() string { + return uuid.NewGenerator().NewString() + ".db" +} + // NewMockClient creates a mock orm client func NewMockClient() (Client, error) { // ref:https://www.sqlite.org/inmemorydb.html - // TODO: Opening in-memory db with shared cache can avoid new DB create - // when starting a new connection. But it will cause other cases fail because - // we has enabled 't.Parallel()'. Cases will share the same in-memory DB if they are - // in same process. - // db, err := gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{ - db, err := gorm.Open(sqlite.Open("file::memory:"), &gorm.Config{ + // using dsn(file:%s?mode=memory&cache=shared) format here to + // 1. Create different DB for different TestXXX() + // 2. Enable DB shared for different connection + dsn := fmt.Sprintf("file:%s?mode=memory&cache=shared", randomDBFile()) + db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{ SkipDefaultTransaction: true, // TODO: logger }) diff --git a/pkg/orm/mock_test.go b/pkg/orm/mock_test.go index 33ef83e3929..24780365ed7 100644 --- a/pkg/orm/mock_test.go +++ b/pkg/orm/mock_test.go @@ -32,11 +32,7 @@ func TestGenEpochMock(t *testing.T) { // Being a lightweight database, SQLite can’t handle a high level of concurrency // NOTICE: Not Recommend to do high concurrenct test in unit test - // TODO: - // (1) if we enable 'cache=shared', need disable 't.Parallel()' and close DB when the test run finish. - // we still will meet 'database table is lock' error for high concurrency - // (2) if we disable 'cache=shared', a new connection will create a new DB, and cause the 'no such table' - // error as consequence + // TODO: we can add retry for sqlite error 'database table is lock' later /* var wg sync.WaitGroup for i := 0; i < 10; i++ {