So, I have a reasonably complicated query which I am trying to debug, but for a simple example let's say I have something like this:
q := "SELECT id FROM users WHERE timestamp > ? AND timestamp < ?"
I will do a Query() on this the usual way, e.g.
db.Query(q, 1546300800,1561127488)
And I would like to log/println/whatever (for debugging) the interpolated query, to end up with
SELECT id FROM users WHERE timestamp > 1546300800 AND timestamp < 1561127488
Wondering if anyone has a trick for me here.
Based on @mkopriva's comments,
Not in Go as it does not do the interpolation, both the query string and the argument values are sent to the db server, which does the interpolation. So if the db server doesn't provide such a feature then you're out of luck. Alternatively you could try searching for a 3rd party package that does the interpolation, however if you find one keep in mind that to be accurate it needs to keep up with the target server's version, if it doesn't do that you may see logs that don't match the actual query being executed
I cannot accomplish this using tooling, as go never has the interpolated query. Sticking to spitting out the non-interpolated query along with the pile of arguments.
You could try something like the following-
NOTE:
For sake of example:
queryParam1 := strconv.Itoa(1546300800)
queryParam2 := strconv.Itoa(1561127488)
// create new instance of *strings.Replacer
replacer := strings.NewReplacer("?", queryParam1, "?", queryParam2)
// prepare query with replacement instructions
query := fmt.Sprint(
replacer.Replace(
"SELECT id FROM users WHERE timestamp > ? AND timestamp < ?",
),
)
// used for debugging
log.Println("Query:", query)
// execute query
db.Query(query)
Again, this is insecure if you allow users to arbitrarily set query params.