-
Notifications
You must be signed in to change notification settings - Fork 2
Auto Increment in PostGres
aodin edited this page Jun 3, 2016
·
1 revision
Sol will exclude zero value fields marked omitempty
during INSERT
. This behavior can be used to intelligently manage both PostGres auto increment columns and other values set on the database. An example:
package main
import (
"log"
"github.com/aodin/sol"
"github.com/aodin/sol/postgres"
"github.com/aodin/sol/types"
)
var Things = postgres.Table("things",
sol.Column("id", postgres.Serial()),
sol.Column("name", types.Varchar().Limit(32).NotNull()),
sol.PrimaryKey("id"),
)
type Thing struct {
ID uint64 `db:",omitempty"`
Name string
}
func (thing *Thing) Save(conn sol.Conn) {
conn.Query(Things.Insert().Values(thing).Returning(), thing)
}
func NewThing(name string) (thing Thing) {
thing.Name = name
return
}
func main() {
conn, err := sol.Open("postgres", <credentials>)
if err != nil {
log.Fatal(err)
}
conn.Must().Query(Things.Create().IfNotExists().Temporary())
gopher := NewThing("Gopher")
gopher.Save(conn)
log.Printf("%+v", gopher) // {ID:1 Name:Gopher}
}
The Save
method will produce the following SQL when an ID is zero:
INSERT INTO things (name) VALUES ($1) RETURNING things.id, things.name