Skip to content

Commit

Permalink
fix(orm): using more proper dsn for sqlite (pingcap#394)
Browse files Browse the repository at this point in the history
  • Loading branch information
maxshuang authored May 16, 2022
1 parent aaa2615 commit fabe57a
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 11 deletions.
17 changes: 11 additions & 6 deletions pkg/orm/mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
})
Expand Down
6 changes: 1 addition & 5 deletions pkg/orm/mock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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++ {
Expand Down

0 comments on commit fabe57a

Please sign in to comment.