Create

The Create method is part of sqac’s CRUD API and is used to insert a single-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 an error is encountered, it will be returned to the caller.

Notice that the inserted record is returned to the caller via the pointer reference following the insertion. The caller receives the new record in its entirety including auto-incrementing and defaulted column values.

CRUD Create Example

The following example illustrates the insertion of a new record (entity) into 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 newRecord = Depot{
      Country: "CA",
      Province: "BC",
      Region: "YVR",
      Population: 2500000,
  }
  
  err = Handle.Create(&newRecord)
  if err != nil {
      log.Errorf(err.Error())
  } else {
      log.Println("New record: ", newRecord)
  }

  // Close the connection
  Handle.Close()
}