Skip to main content

Defining models

A model is a Go struct with no base type, tags or generated code. Exported fields are columns. List the model in your database struct to register it.

A model​

type Article struct {
ID int64
Title string
Views int
}

type BlogDB struct {
ant.Context
Articles ant.Table[Article]
}

var Articles = ant.Fields[Article]()

This maps to the table articles, with id as a database-generated primary key. Open fails at startup if a model can't be mapped. See keys for other primary keys.

Add IDs and timestamps with ant.Base​

ant.Base holds ID, CreatedAt and UpdatedAt.

type Article struct {
ant.Base
Title string
}

article := &Article{Title: "Hello"}

err := db.Articles.Insert(ctx, article)
// INSERT INTO "articles" ("created_at", "updated_at", "title") VALUES ($1, $2, $3) RETURNING "id"

fmt.Println(article.ID, article.CreatedAt, article.UpdatedAt) // all filled in

Any model with a time.Time field named CreatedAt or UpdatedAt gets the same timestamps.

Table and column names​

GoDatabase
type OrderItemtable order_items
UserIDcolumn user_id
HTTPPortcolumn http_port
IDprimary key id

Table names are plural. ant adds s, or es after s, x, ch and sh, and turns a consonant followed by y into ies. That gives categories for Category, and also persons for Person and childs for Child. Set b.Table when the result reads wrong.

Rename a column or a table​

A tag renames a column. Configure renames a table.

type Device struct {
ID int64
Name string `ant:"column=display_name"`
}

func (Device) Configure(b *ant.ModelBuilder[Device]) {
b.Table("hardware")
}

Leave a field out​

A field tagged ant:"-" and any unexported field is not a column. ant never reads, writes or queries it.

type Session struct {
ID int64
Token string
Cached string `ant:"-"`
secret string
}

Change the naming rules​

ant.WithNaming replaces the conventions for every model. A nil function keeps the default for that part. A name set explicitly is kept.

db, err := ant.Open[AppDB](ctx, postgres.Dialect, dsn,
ant.WithNaming(ant.Naming{
Table: func(name string) string { return "tbl_" + name },
Column: func(name string) string { return "col_" + name },
}),
)

ant.WithConvention runs a rule on every model as it is configured. A model's Configure method runs after the rule and can override it.

rule := func(m *ant.ModelConvention) {
for _, f := range m.Fields() {
if f.Type.Kind() == reflect.String {
f.SetLength(100)
}
}
}

db, err := ant.Open[AppDB](ctx, postgres.Dialect, dsn, ant.WithConvention(rule))
Set once per process

Naming and conventions are global: ant reflects each model once per process, so they come from the first Open.