I'm trying to pass a variable number of arguments to db.Query() in Go. I'm doing something like:
var values []interface{}
query := []string{"SELECT * FROM table"}
sep := "WHERE"
if ... {
values = append(values, something)
query = append(query, fmt.Sprintf(` %s field_a=$%d`, sep, len(values))
sep = "AND"
}
if ... {
values = append(values, something)
query = append(query, fmt.Sprintf(` %s field_b=$%d`, sep, len(values))
sep = "AND"
}
// Add an arbitrary number of conditional arguments...
rows, err := db.Query(strings.Join(query, " "), values...)
The query looks fine, and the values are all there, but I'm not getting anything back from the query. Some of the values are integers, some strings. When I manually try the exact same query (copy/paste) in psql, I substituting the actual values for $1, $2, etc, I get correct results. What am I missing?
Edit
Here's an example of what the final query (the result of strings.Join()
) should look like:
SELECT
table1.field1, table1.field2, table1.field3,
table2.field4, table2.field6, table2.field6
FROM table1, table2
WHERE
table1.field2=$1 AND
table2.field3 IN ($2, $3)
When I try:
SELECT
table1.field1, table1.field2, table1.field3,
table2.field4, table2.field6, table2.field6
FROM table1, table2
WHERE
table1.field2='something' AND
table2.field3 IN (40, 50)
from psql
, it works fine. When I call:
var values []interface{}
values = append(values, "something")
values = append(values, 40)
values = append(values, 50)
db.Query(`SELECT
table1.field1, table1.field2, table1.field3,
table2.field4, table2.field6, table2.field6
FROM table1, table2
WHERE
table1.field2=$1 AND
table2.field3 IN ($2, $3)`, values...)
from Go, I get a Rows object that returns false
the first time rows.Next()
is called, and a nil error.