On Tue, Oct 20, 2020 at 6:51 PM <billyp...@gmail.com> wrote:

>         var count int
>         var favorited string
>
>         fetchBookmarks := Config.DB.QueryRow("SELECT COUNT(*) FROM
> favorites where userID = ? and postID = ? and status = ?", userID, postID,
> "added").Scan(&count)
>
>         if fetchBookmarks != nil {
>             fmt.Println("error")
>         }
>
>         if count == 0 {
>             favorited = "no"
>         } else {
>             favorited = "yes"
>         }
>
>
While I think you have other problems if a Ping() to the database takes
above 1.5s, The above looks a bit misleading. You aren't really counting
all rows since you are doing a point-query, so you can essentially just
`SELECT 1 FROM favorites ...` and check if a row is returned. I'd also
definitely look into baking this into an (OUTER) JOIN. The lookup is much
faster if the database is doing the work close to the data than if you pay
the RTT twice in every iteration of the loop. Even in moderately fast
environments (<10ms RTT) these kinds of query structures tend to cost a lot
since they serialize the query. While you might be able to run many of them
concurrently, each individual query is going to take time to complete.

Another point is that you are currently mixing presentation with logic.
Your `count` variable is the logic part, but `favorited` pertains to
presentation. I'd propose making `favorited` a boolean value. Callers of
the function can then use this value more directly, whereas they will have
to do string comparison in the above scheme. There are a lot of subtle bugs
that can creep in as a result of this. You might even want to make results
into a struct and bind a method for presentation to the struct.

Also, I'd propose adding some observability to the errors as they occur.
Something like `log.Printf("Failure querying favorites for (User:%v,
Post:%v, Status:%v): %v", userID, postID, "added", err)`. This will make
the system tell you what is wrong in a log line rather than you having to
make an educated guess. It doesn't take much time, and when things start
going wrong in a code base for some reason, you don't have the benefit of
time at hand most often. Better get it in when things are not looking like
chaos.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAGrdgiU4G2eAaLN_MF5entdd1V4yqoGSNaQGJ6v1BtnAxLTgDg%40mail.gmail.com.

Reply via email to