I need to check if my query returns true or false. If it returns false, I want it to error out. Here is my code:
func (dr *dbrepo) checkIfUnique(datacenterstring) error {
statement := `select exists(select 1 from source where datacenter = $3)`
_, checkIfExists := dr.db.Query(statement)
if checkIfExists != nil {
log.Print("Error is not unique", checkIfExists)
return checkIfExists
}
return nil
}
The problem is: I think I need to convert checkIfExists
from a row to a bool and then see if it is true or false. But I am not sure on how to do that. Any ideas? Is there a better way to do this?
Query()
does not return true or false. It returns two values: *Rows
& error
.
func (db *DB) Query(query string, args ...interface{}) (*Rows, error) {
...
}
In your case: checkIfExists
is the error. With this error, you can already tell of the query succeeded or failed. Like you do it:
if checkIfExists != nil {
return checkIfExists
}
If you want more information (such as the rows retrieved by your query), then you will need to replace the _
with a variable. Let's call it rows
and then you use rows.Scan()
to copy the data in the columns to your destinations. See database/sql
docs for more information.