I have a list of uuid strings that I want to use to filter a query. I can get the query to work if I loop over elements in my list like so:
for i, fileUID := range fileUIDs {
db.Exec("DELETE FROM files WHERE uid = $1::uuid", fileUID)
}
But I'd like to get it working using the list:
db.Exec("DELETE FROM files WHERE uid IN $1::uuid[]", fileUIDs)
Is this possible? I can't seem to get it working.
I tried the solution in How to execute an IN lookup in SQL using Golang? but I get errors like pq: syntax error at or near ","
when using plain ?
or pq: syntax error at or near "::"
when using ?:uuid
. I used the following:
fileUIDArgs := make([]interface{}, len(fileUIDs))
for i, fileUID := range fileUIDs {
fileUIDArgs[i] = interface{}(fileUID)
}
//also tried using "?::uuid"
myPsql := "DELETE FROM files WHERE uid IN (" + "?" + strings.Repeat(",?", len(uidStrings)-1) + ")"
db.Exec(myPsql, fileUIDArgs...)
Using fmt. Make sure that your uuids doesn't contain any SQL-injection.
ary := []string{
"1442edc8-9e1f-4213-8622-5610cdd66790",
"0506ca17-d254-40b3-9ef0-bca6d15ad49d",
"e46f3708-6da5-4b82-9c92-f89394dffe5d",
"fb8bf848-73a2-4253-9fa3-e9d5e16ef94a",
"84691fa5-3391-4c02-9b16-82389331b7ac",
"adba3c9d-b4ab-4e62-a650-414970645be7",
}
query := fmt.Sprintf(`DELETE FROM files WHERE uid IN ('%s'::uuid);`,
strings.Join(ary, "'::uuid,'"))
db.Exec(query) // etc
Rid out of potential SQL-injections:
ary := []string{ /* list of uuids */ }
query := `DELETE FROM files WHERE uid IN (`
aryInterfaces := make([]interface{}, len(ary))
for i, v := range ary {
query += "$" + strconv.FormatInt(int64(i+1), 10)
if i < len(ary)-1 {
query += ","
}
aryInterfaces[i] = v
}
query += ")"
db.Exec(query, aryInterface...)
BONUS Postgresql uses $1, $2, $3
etc instead of ?, ?, ?
. Here is a little helper function and here is its proof of concept.