Skip to content

database is locked

Hello!

First I would like to thank for your work. I have run into the named database is locked error.

For instance this is how an user service looks like. I use the same *DB instance all across services.

type DB struct {
	db     *sql.DB
}

type UserService struct {
	db *DB
}

func NewUserService(db *DB) *UserService {
	return &UserService{db: db}
}

func (s *UserService) FindUserByID(ctx context.Context, id string) (asm.User, error) {
	tx, err := s.db.BeginTx(ctx, nil)
	if err != nil {
		return asm.User{}, fmt.Errorf("find user %v failed: %w", id, err)
	}
	defer tx.Rollback()

	user, err := selectUser(ctx, tx, id)
	if err != nil {
		return asm.User{}, fmt.Errorf("find user %v failed: %w", id, err)
	}
	return user, nil
}

func selectUser(ctx context.Context, tx *Tx, id string) (asm.User, error) {
	var user asm.User
	if err := tx.QueryRowContext(ctx, _selectUser, id).Scan(&user.SapID, &user.ID, &user.Name); err != nil {
		return asm.User{}, err
	}
	return user, nil
}

I could overcome the problem using the below settings.

	// Sqlite cannot handle concurrent writes,
	// so we limit sqlite to one connection.
	// https://github.com/mattn/go-sqlite3/issues/274
	db.db.SetMaxOpenConns(1)

Have you faced with this kind of issue previously? (I am asking b/c I haven't seen any issues regarding this.)

Do I miss something?

Thanks for your help in advance.

OS: Windows 10
Go: 1.17

Edited by András Mózes