Querying for One Record by ID

Querying for one record is necessary in applications when a singular view of a data record is required. Doing so in pop is straightforward, and builds on some of the code we've already used.

package main

import (
    "bitbucket.org/pop-book/models"
    "fmt"
    "github.com/gobuffalo/pop"
    "log"
)

func main() {
    tx, err := pop.Connect("development")
    if err != nil {
        log.Panic(err)
    }
    // Case 1: good entry
    id := "240ec3c5-019d-4031-9c27-8a553e022297" // frank
    frank := models.User{}
    err = tx.Find(&frank, id)
    if err != nil {
        fmt.Print("ERROR!\n")
        fmt.Printf("%v\n", err)
    } else {
        fmt.Print("Success!\n")
        fmt.Printf("%v\n", frank)
    }

    // Case 2: bad entry
    id = "00000000-0000-0000-0000-000000000000" // doesn't exist
    nuthin := models.User{}
    err = tx.Find(&nuthin, id)
    if err != nil {
        fmt.Print("ERROR!\n")
        fmt.Printf("%v\n", err)
    } else {
        fmt.Print("Success!\n")
        fmt.Printf("%v\n", nuthin)
    }
}

When we first initialize the frank data element with frank := models.User{} that data element is empty. We have to then pass a pointer to that element along with the ID to the connection's Find function. The Find function then populates that element with the data if it exists (as in Case 1) or returns an error (as in Case 2). If we compile and run this code it will generates something like

$ ./main
Success!
{"id":"240ec3c5-019d-4031-9c27-8a553e022297","created_at":"2017-12-19T14:06:20.478384-05:00","updated_at":"2017-12-19T14:06:20.478385-05:00","title":"Mr.","first_name":"Frank","last_name":"Castle","bio":"USMC, badass."}
ERROR!
sqlite select one: sql: no rows in result set

results matching ""

    No results matching ""