简体   繁体   中英

How to use go-sqlmock when I have concurrent query in my program?

sqlmock needs to match the SQL in order. But if I have concurrent query in my code just like this:

    condition1 := make(map[string]string)
    condition2 := make(map[string]string)

    var count int64
    var user User
    var task Task

    var wg sync.WaitGroup
    wg.Add(3)

    wgDone := make(chan interface{})
    errCh := make(chan error)

    go func(wg *sync.WaitGroup) {
        defer wg.Done()

        err := conn.Where(condition1).Find(&user).Error
        if err != nil {
            errCh <- err
        }
    }(&wg)

    go func(wg *sync.WaitGroup) {
        defer wg.Done()

        err := conn.Where(condition2).Find(&task).Error
        if err != nil {
            errCh <- err
        }
    }(&wg)

    go func(wg *sync.WaitGroup) {
        defer wg.Done()

        err := conn.Count(&count).Error
        if err != nil {
            errCh <- err
        }
    }(&wg)
    
    go func() {
        wg.Wait()
        close(wgDone)
    }()

    select {
    case err := <-errCh:
        return err
    case <-wgDone:
        break
    }
    
    ...

It is said that we can't know the execution order of the SQL. So I dont't know how to use sqlmock to match the sql correctly.

TheMatchExpectationsInOrder method disables in-order checking for exactly this scenario.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM