Map database records to Go structs

Let’s suppose the database we’re working on has a “books” table that was created like this:

CREATE TABLE "books" (
  "author_id" INTEGER,
  "subject_id" INTEGER,
  CONSTRAINT "books_id_pkey" PRIMARY KEY ("id")

We can represent a single record from such table and the fields accompanying it with a Go struct accompanied by struct tags in exported fields:

type Book struct {
  ID          uint   `db:"id"`
  Title       string `db:"title"`
  AuthorID    uint   `db:"author_id"`
  SubjectID   uint   `db:"subject_id"`

The db field tag will then be required so upper/db can map columns to struct fields.

Please note that:

  • Fields and columns must be similar in type (upper/db will handle most reasonable conversions automatically).

  • Fields must be exported and have a db tag, otherwise they will be ignored.

In the event the table contains a column configured to represent automatically-generated values like IDs, serials, dates, etc. the omitempty option will have to be added to the db tag:

type Book struct {
  ID uint `db:"id,omitempty"`

This option will make upper/db ignore zero-valued fields when building INSERT and UPDATE statements so they can be correctly generated by the database itself.