Update

The Update method is part of sqac’s CRUD API and is used to update an existing row of the specified entity into 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 populated go struct of the sqac table declaration. If the table contains a primary-key in the database, the key column(s) may not be updated, but must be included. If an error is encountered, it will be returned to the caller.

CRUD Update Example

The following example illustrates the update of an existing record (entity) in 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)
  }

  // Update the existing record using the fully populated depotRecord
  // struct as a starting point.
  depotRecord.Province = "ON"
  depotRecord.Region = "YYZ"
  depotRecord.Population = 4500000
  err = Handle.Update(&depotRecord)
  if err != nil {
      log.Errorf(err.Error())
  } else {
      log.Println("Updated record: ", depotRecord)
  }

  // Close the connection
  Handle.Close()
}