Skip to main content

Custom types

Any type database/sql can read and write works as a column. ant adds types such as JSON whose conditions stay typed.

Enums and other named types​

A named type over a basic type, such as a Go enum, needs no methods.

type Status string

const Paid Status = "paid"

type Invoice struct {
ID int64
Status Status
}

var Invoices = ant.Fields[Invoice]()

paid, err := db.Invoices.Where(ant.Eq(&Invoices.Status, Paid)).All(ctx)
// SELECT ... FROM "invoices" WHERE "invoices"."status" = $1

Convert your own type​

A type that implements driver.Valuer and sql.Scanner converts itself wherever it appears, with no registration. A pointer to the type is a nullable column, and conditions send the converted value.

type Money struct {
Cents int64
}

func (m Money) Value() (driver.Value, error) {
return fmt.Sprintf("%d.%02d", m.Cents/100, m.Cents%100), nil
}

func (m *Money) Scan(src any) error {
text, ok := src.(string)
if !ok {
return fmt.Errorf("money: unexpected %T", src)
}

return m.parse(text)
}

// A type can name its column, for migrations.
func (Money) ColumnType(dialect string) string {
return "numeric(19,4)"
}

Without ColumnType, set the column type in Configure with b.Column(&...).Type("numeric(19,4)"), or migrations stop with ant.ErrNoColumnType.

Use a custom type for a value with its own encoding, such as money or a phone number. Use ant.JSON for a document you may query inside.

Slice types​

A slice type that implements both interfaces is one column. It is not a has-many relation, even when its elements are structs.

type Tags []string

func (t Tags) Value() (driver.Value, error) {
return strings.Join(t, ","), nil
}

func (t *Tags) Scan(src any) error {
text, ok := src.(string)
if !ok {
return fmt.Errorf("tags: unexpected %T", src)
}

*t = strings.Split(text, ",")

return nil
}

func (Tags) ColumnType(dialect string) string {
return "text"
}

type Note struct {
ID int64
Tags Tags
}

note := &Note{Tags: Tags{"go", "orm"}}

err := db.Notes.Insert(ctx, note)
// INSERT INTO "notes" ("tags") VALUES ($1) RETURNING "id" -- $1 = go,orm

note.Tags = append(note.Tags, "sql")

err = db.SaveChanges(ctx)
// UPDATE "notes" SET "tags" = $1 WHERE "notes"."id" = $2 -- $1 = go,orm,sql

Methods on a pointer​

Value may have a pointer receiver. ant binds the field through a pointer so the method runs even when the field is not a pointer.

type Temp struct {
Milli int64
}

func (t *Temp) Value() (driver.Value, error) {
return t.Milli, nil
}

func (t *Temp) Scan(src any) error {
t.Milli = src.(int64)

return nil
}

JSON​

ant.JSON[T] stores a Go value in a JSON column (jsonb on PostgreSQL, json elsewhere). Tracking notices a change anywhere inside the value. It marshals as the document it holds, so a model can go straight into an API response.

type Prefs struct {
Theme string `json:"theme"`
Tags []string `json:"tags"`
}

type Device struct {
ID int64
Prefs ant.JSON[Prefs]
}

phone := &Device{Prefs: ant.JSON[Prefs]{V: Prefs{Theme: "dark"}}}

err := db.Devices.Insert(ctx, phone)

phone.Prefs.V.Theme = "light"

err = db.SaveChanges(ctx)
// UPDATE "devices" SET "prefs" = $1 WHERE "devices"."id" = $2

A NULL column reads as the zero value of T. Writing text that is not valid UTF-8 returns an error, where encoding/json would store U+FFFD.

ant.JSON[[]string] is the simple way to keep a list in a row.

Query inside JSON (PostgreSQL)​

The postgres package reads and updates parts of a document. Paths are bound as parameters.

dark := postgres.JSONText(&Devices.Prefs, "theme").Eq("dark")
// "devices"."prefs" #>> $1::text[] = $2 -- $1 = {"theme"}

second := postgres.JSONText(&Devices.Prefs, "tags", "1").Eq("b")
// "devices"."prefs" #>> $1::text[] = $2 -- $1 = {"tags","1"}

contains := postgres.JSONContains(&Devices.Prefs, map[string]any{"theme": "light"})
// ("devices"."prefs" @> $1::jsonb)

hasKey := postgres.JSONHasKey(&Devices.Prefs, "theme")
// (jsonb_exists("devices"."prefs", $1))

phones, err := db.Devices.Where(dark).All(ctx)

postgres.JSONSet changes one value inside a document without loading it. postgres.JSONLength measures one.

_, err := db.Devices.Where(ant.Eq(&Devices.ID, id)).
Update(ctx, ant.SetExpr(&Devices.Prefs, postgres.JSONSet(&Devices.Prefs, "light", "theme")))
// UPDATE "devices" SET "prefs" = jsonb_set("devices"."prefs", $1::text[], $2::jsonb)
// WHERE "devices"."id" = $3

Other stored forms​

TypeStores
ant.Gob[T]A Go value with encoding/gob, for data only Go reads
ant.UnixTimeA time as whole seconds in a bigint. Works as CreatedAt and UpdatedAt
[]byteBinary data
secure.Value[T]A value encrypted with AES-256-GCM

ant.UnixTime stores the zero time as 0 and reads 0 back as the zero time, so the Unix epoch (1970-01-01 00:00:00 UTC), also stored as 0, comes back as the zero time. secure.Value, like ant.JSON, refuses text that is not valid UTF-8.

Limits of the drivers​

database/sql or the driver refuses these, and ant doesn't work around them:

  • sql.Null[uint64] above math.MaxInt64. A plain uint64 field is accepted.
  • NULL into a named []byte type such as json.RawMessage or net.IP. Use a pointer to the type for a column that allows NULL.
  • PostgreSQL INTERVAL into a time.Duration. Store microseconds, or read it into pgtype.Interval.

See databases for the rest.

PostgreSQL types​

type Item struct {
ID int64
Labels postgres.Array[string] // text[]
Scores postgres.Array[int] // bigint[]
At postgres.Point // point
Embed postgres.Vector // pgvector
}

var Items = ant.Fields[Item]()

An Array holds no NULL element, so reading an array that has one is an error that says so, rather than the text "NULL" or false. A quoted "NULL" is still the text.

Points and vectors have conditions and orderings of their own, and full-text search works on any text column.

near := postgres.Near(&Items.At, postgres.Point{X: 1, Y: 1}, 5)
closest := postgres.Distance(&Items.At, postgres.Point{}).Asc()
similar := postgres.CosineDistance(&Items.Embed, postgres.Vector{0.9, 0.1}).Asc()
search := postgres.Match(&Posts.Title, "english", "quick fox")

items, err := db.Items.Where(near).Order(closest).All(ctx)

postgres.L2Distance is the Euclidean version of CosineDistance. Vectors need the pgvector extension in your database.