The GetEntity method is part of sqac’s CRUD API and is used to retrieve an existing row of the specified entity from it’s related database table. Structs annotated with ‘sqac:’ tags are colloquially known as sqac entities, hence the parameter name ‘ent’.
The ent parameter must be a pointer to a go struct of the sqac table declaration in which the primary-key fields have been populated. The GetEntity method can be thought of as a fully-keyed SELECT SINGLE statement. If an error is encountered, it will be returned to the caller.
PublicDB.GetEntitiesCP is a more flexible and useful method.
The following example illustrates the deletion of an existing record (entity) from database table “depot”.
package main
import (
"log"
"github.com/1414C/sqac"
_ "github.com/mattn/go-sqlite3"
)
func main() {
var (
Handle sqac.PublicDB
)
// Declare a struct to be used as the source for table creation
type Depot struct {
DepotNum int `db:"depot_num" sqac:"primary_key:inc"`
CreateDate time.Time `db:"create_date" sqac:"nullable:false;default:now();"`
Country string `db:"country" sqac:"nullable:false;default:CA"`
Province string `db:"province" sqac:"nullable:false;default:AB"`
Region string `db:"region" sqac:"nullable:false;default:YYC"`
Population int `db:"population" sqac:"nullable:false;default:0;index:non-unique"`
}
// Create a PublicDB instance to connect to the test sqlite db
Handle = sqac.Create("sqlite", false, false, "testdb.sqlite")
// Create a new table in the database
err := Handle.DestructiveResetTables(Depot{})
if err != nil {
log.Errorf("%s", err.Error())
}
// Insert a new record into table "depot"
var depotRecord = Depot{
Country: "CA",
Province: "BC",
Region: "YVR",
Population: 2500000,
}
err = Handle.Create(&depotRecord)
if err != nil {
log.Errorf(err.Error())
} else {
log.Println("New record: ", depotRecord)
}
// Retrieve the existing record using the fully populated depotRecord's primary-key value
var readRecord = Depot{
DepotNum: depotRecord.DepotNum,
}
err = Handle.GetEntity(&readRecord)
if err != nil {
log.Errorf(err.Error())
} else {
log.Println("Retrieved record: ",readRecord)
}
// Close the connection
Handle.Close()
}