DATA-DOG / go-sqlmock

Sql mock driver for golang to test database interactions
Other
6.05k stars 406 forks source link

Question: Query matching issue for long queries #212

Closed xyzzzyx closed 4 years ago

xyzzzyx commented 4 years ago

Getting issues while trying to match the following query: SELECT v.col1, v.col2 as colTemp1, col3, col4 as colTemp2, a.col5 FROM table1 a JOIN table2 m USING (s1) LEFT OUTER JOIN table3 v USING (s2) LEFT OUTER JOIN table4 d USING (s3) LEFT OUTER JOIN table5 t USING (s4) LEFT OUTER JOIN table6 p USING (s5) LEFT OUTER JOIN table7 USING(s6) LEFT OUTER JOIN table8 qc USING(s7) WHERE something = ? AND v.something1 = 1 AND v.something2 = 1

but get "was not expected, next expectation is: ExpectedQuery => expecting Query, QueryContext or QueryRow which" error.

Trying to match the query as follows:

queryReg := regexp.QuoteMeta(query) mock.ExpectQuery(queryReg).WithArgs("1").WillReturnRows(rs)

What would be the correct query string that won't have match issues?

xyzzzyx commented 4 years ago

Hey @l3pp4rd, any idea why I might be getting the above error?

moemoe89 commented 4 years ago

@xyzzzyx I've experienced similar issue when using brackets () on my query. Is it work if you escaping the brackets or special characters? for example: JOIN table2 m USING \\(s1\\)

l3pp4rd commented 4 years ago

maybe someone would like to contribute on the error messages in query matching, for example showing unmatched position in query string on error message, since this is a very common problem finding out what exactly was not matched.

xyzzzyx commented 4 years ago

@moemoe89 escaping the brackets worked for me. Thanks! Closing

xyzzzyx commented 4 years ago

@moemoe89 @l3pp4rd I am using sqlx library for querying the db and getting a query mismatch whenever I use the where clause. Are you using sqlx library?

moemoe89 commented 4 years ago

@xyzzzyx yes i do. you could see my example code on my repo: https://github.com/moemoe89/simple-go-clean-arch/blob/master/api/v1/user/repository_test.go for getting reference how it works

xyzzzyx commented 4 years ago

Hey @moemoe89 Thanks for pointing me to the example. However, I am using the following to query the database and don't want to change it: stmt, err := c.DB.Preparex(query) if err != nil { log.Fatalln(err) } defer stmt.Close()

//query contains where clause rows, err := stmt.Queryx(ID) if err != nil { log.Fatalln(err) } defer rows.Close()

The query to database works but I get a query mismatch whenever I try to mock it as follows:

mock.ExpectQuery(query).WithArgs("1234").WillReturnRows(rs) elements := dbInstance.testingThisMethod("1234")

The test case passes when not using WithArgs and not passing ID to Queryx. Do you have an example that uses preparex and queryx or have an idea regarding how mock the above query with the where caluse?