Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golfing postgres how can I return count number from the query

Tags:

I am very new to Golang and am using the PQ package for postgres. What I am trying to do is prevent duplicate emails, so I have a query that checks to see if a user email is already in the database

check_duplicate_emails, err := db.Prepare("select count(*) from profiles where email=$1")
    rows, err := check_duplicate_emails.Exec(email)

        if rows != nil {
        fmt.Fprintf(w,"Duplicate Email")
    } 

That is my code above how can I make it such that I can check like this

if rows >0 { ...}

when I try to do that I get the error

invalid operation: rows > 0 (mismatched types sql.Result and int)

How can I solve this issue as I been looking around to resolve it for a bit now.

like image 845
user1591668 Avatar asked Sep 28 '16 01:09

user1591668


2 Answers

What's happening here is that you've told Go that your query won't be returning any rows (see docs for Exec())

You should probably use either:

  • a combination of QueryRow and Scan() (example in QueryRow is a good one), or
  • a "select somecol from ... where ..." without the count(*) query with Query and look at the rows.Next() to see if there was a first row.
like image 193
BJ Black Avatar answered Sep 23 '22 16:09

BJ Black


Looking at the documentation, you need to call rows.Next() and check that it succeeds:

if rows.Next() {
    fmt.Fprintf(w, "Duplicate Email")
}
else if rows.Err() {
    fmt.Fprintf(w, "Oops, error %s", rows.Err())
}
else {
    fmt.Fprintf(w, "OK, unique email address")
}

If there is no data, rows.Next() will return nil - rows.Err() should also be called to check for errors.

Please also note the other answer from BJ Black - the check_duplicate_emails.Exec(email) line is also wrong.

like image 35
Ken Y-N Avatar answered Sep 26 '22 16:09

Ken Y-N