Skip to content

Latest commit

 

History

History
669 lines (620 loc) · 42 KB

ROADMAP.md

File metadata and controls

669 lines (620 loc) · 42 KB

Roadmap

Every feature ant has, or has decided about, grouped by area. The list comes from the feature catalogs of EF Core, Eloquent, and the Go libraries, with features that overlap merged into one line.

  • [x] is shipped. The API named is the one to use.
  • [ ] is not, and the reason is under it, as Skipped:. Read it before working on the item: most record a decision, and some name the owner as the one to make it.
  • Not planned lists what ant leaves out on purpose.

Releases are the git tags (git tag, or the GitHub releases page). This file does not follow them: items are grouped by what they are, not by when they shipped. Design decisions behind an item are in docs/decisions/.

Standing goals

The work keeps to these. A change that breaks one needs a decision.

  • No public query API takes any, except the arguments of raw SQL.
  • Include runs exactly one extra statement per relation.
  • Zero values are written when they changed, and nothing is written when nothing changed.
  • Every test passes on every database it targets. A feature a database lacks returns a documented error, and per-dialect skips are only for those differences.
  • Paging and chunking are tested with at least 100,000 rows.
  • Composite keys work with Find, Include, and SaveChanges.
  • Hooks, interceptors, and observers each have tests of their order.
  • Sensitive values never appear in default logs, which a test checks.
  • Tracing adds no dependency to the root package.
  • A model change produces SQL with no database connection, and that SQL applies cleanly on PostgreSQL, the database with migrations. check fails CI when the models and the snapshot differ. Replacing migrate.Source is covered by a test.
  • The analyzer runs under go vet -vettool.
  • Fixtures and factories are used by ant's own integration suite.
  • Benchmarks are published and reproducible.
  • The security review has no open high-severity findings.

Model definition and mapping

  • Plain struct models with no required base type
  • Embeddable base: ant.Base
  • Model registry that reflects each struct once
  • Field probes: ant.Fields[T]()
  • Probe resolution by address and type
  • Table name convention: User to users
  • Column name convention: UserID to user_id
  • Exclude a field: ant:"-"
  • Column name override: ant:"column=name"
  • Table name override: b.Table("users")
  • Fluent configuration: Configure(b *ant.ModelBuilder[E])
  • Nullable columns through pointers and sql.Null[T]
  • Custom types through sql.Scanner and driver.Valuer
  • Relation detection: []Post and *User fields are not columns
  • Embedded structs: anonymous, or ant:"embedded"
  • Embedded prefix: ant:"embedded,prefix=addr_"
  • Owned types: ant:"embedded,prefix=address_" on a struct field
    • A tag rather than b.Owned, in line with how embedded structs already worked.
  • Collections of owned types in a separate table
    • Skipped: A slice of structs in a table of its own is a has-many relation, which already works and has an ID you can reach. For a list that is only ever read with its parent, ant.JSON[[]T] keeps it in one column.
  • Nested owned types
  • Table splitting
    • Several models on one table. Migrations merge them into one table definition.
  • Entity splitting
    • Skipped: One model across two tables would need a join on every read and two writes on every save, hidden behind a call that looks like one row. A 1:1 relation states that cost, and a view covers reads.
  • Keyless models for views and raw results: b.NoKey()
  • View mapping: b.View("active_users")
  • Table schema: b.Schema("sales")
  • Field access control: ant:"readonly", ant:"writeonly"
  • Single-table inheritance with a discriminator: b.Discriminator
  • Table-per-type inheritance
    • Skipped: Go has no inheritance to map, so every query would need joins to rebuild something the language does not have. A 1:1 relation from the specific table to the shared one is the same schema, and says so.
  • Table-per-concrete-type inheritance
    • Embed a shared struct in each model. Each gets its own table, and no ant feature is involved.
  • Polymorphic models through type switches on a discriminator
    • Skipped: Query results have one static type, []T, so returning several types would mean []any and giving up what ant is for. Map rows to types with a short switch on the field, which tests/features/model_definition/inheritance_test.go shows.
  • Custom naming strategy: ant.WithNaming(fn)
    • Global, set in the first Open, because models are reflected once per process.
  • Bulk conventions: ant.WithConvention(fn)
  • Column type, length, precision, scale, and collation: b.Column(&Users.Name).Type(...)
  • Fixed-length strings: .Fixed(n)
    • Unicode settings do not apply: PostgreSQL text encoding belongs to the database, not the column.
  • Table and column comments: b.Comment, .Comment
  • Column order
    • Columns follow the struct's field order. Reordering later is not offered, since PostgreSQL cannot do it without rebuilding the table.
  • Unique constraint tag: ant:"unique"
  • Indexes: b.Index(&Users.Email)
  • Unique indexes: .Unique()
  • Composite indexes, sort order, names, filters, and included columns
  • Functional, full-text, and spatial indexes: b.IndexExpr(expr), .Using("gin")
  • Check constraints: b.Check(name, sql)
  • Table triggers declaration
    • Skipped: Triggers go in migrations/code, where they are plain SQL that the runner reapplies when the file changes. Declaring one in Go would only wrap the same SQL in a string, and drift could not compare it. examples/ledger in ant-examples does this.
  • Mixins through embedded configuration: ConfigureMixin(m *ant.Mixin)
  • Field validators: b.Validate(&Users.Age, fn)
  • Built-in validators: package validate
  • Immutable fields: ant:"immutable"
  • Sensitive fields hidden from logs: .Sensitive()
  • Deprecated field annotation
    • Skipped: Go already has this: a // Deprecated: comment on the field, which gopls and staticcheck report at every use, including probes.
  • Strict mode that rejects unknown result columns: ant.WithStrict()
  • Discard unknown columns: ant.WithLooseScan()

Keys and identity

  • ID primary key by convention
  • Explicit primary key: b.Key(&Users.Email)
  • Application-assigned integer keys: b.Key(&Tickets.ID).NotGenerated()
  • Database-generated integer keys
  • Explicit key values on insert
  • String and UUID keys supplied by the application
  • Composite primary keys: b.CompositeKey(ant.F(&Tickets.A), ant.F(&Tickets.B)), db.Table.FindKey(ctx, a, b)
  • Composite foreign keys
    • As a constraint, through b.ForeignKey. Relations stay single-column, so a relation on a composite key is marked .NoForeignKey(), and joins name both columns.
  • Alternate keys: .References(&Users.Email)
  • Application-generated keys: ant.GenerateKey(b, &Users.ID, uuid.NewString)
  • UUID, ULID, and snowflake helpers: package ids
  • Sequences: b.Column(&Orders.Number).Sequence(name)
  • Case-insensitive string keys
    • .Type("citext"), or a named type with a ColumnType method. That needs the citext extension, created in migrations/code.
  • Value objects as keys

Value handling

  • Value converters
    • Named types with sql.Scanner and driver.Valuer, by decision 42.
  • Built-in converters
    • ant.JSON, ant.Gob, ant.UnixTime, and postgres.Array. Same decision.
  • Bulk converters for a type
    • A type that implements the interfaces converts wherever it appears, with no registration. Same decision.
  • Enum mapping to string or integer: named Go types, or Scanner and Valuer
  • Enums as native database types: .Enum
  • JSON columns: ant.JSON[T]
  • JSON path conditions: postgres.JSONText(&Users.Meta, "a", "b")
  • JSON contains and length conditions: postgres.JSONContains, JSONHasKey, JSONLength
  • Update inside a JSON column: postgres.JSONSet
  • Array columns on PostgreSQL: postgres.Array[T]
  • PostgreSQL's own column types for standard Go types: time.Duration as interval, net.IP and netip as inet and cidr, json.RawMessage and maps as jsonb, decimal.Decimal as numeric, and plain slices as arrays
  • Primitive collections stored as JSON: ant.JSON[[]string]
  • Encrypted fields with key rotation: secure.Value[T]
    • A field type rather than .Encrypt, so a value cannot be read as plain text by mistake. See encrypted fields.
  • Default values in the database: ant:"default"
  • Computed columns, stored or virtual: ant:"readonly"
  • Generated values on insert: ant:"default", ant:"readonly"
  • Accessors and mutators: Go methods, with Scanner and Valuer for stored forms
  • Binary columns: []byte
  • Clock for automatic timestamps: ant.WithNow(fn)
  • Spatial types: postgres.Point, postgres.Near
    • Native point only. PostGIS has hundreds of functions: ant.SQL reaches them.
  • Vector columns and similarity conditions: postgres.Vector
    • Its test skips on a server without pgvector, as the plain test image is.
  • Full-text conditions: postgres.Match
  • Hierarchy types on SQL Server through a dialect extension
    • Skipped: SQL Server only. Nothing to attach it to until that dialect has a real user.
  • Serializers for JSON, gob, and Unix time: ant.JSON, ant.Gob, ant.UnixTime
    • Field types rather than a tag, so the compiler sees them.

Relations

  • One-to-many by convention: Post.UserID
  • Many-to-one by convention: Post.User
  • One-to-one by convention
  • Self-referencing relations
  • Explicit relation configuration: b.HasMany(&Users.Posts).ForeignKey(&Posts.UserID)
  • Explicit one relation: b.HasOne, b.BelongsTo
  • Relation to a non-primary key: .References(&Users.Email)
  • Delete behavior: .OnDelete(ant.Cascade), ant.SetNull, ant.Restrict, ant.NoAction
  • Update behavior: .OnUpdate(...)
  • Default model for a missing relation is a nil pointer
  • Many-to-many: b.ManyToMany(&Users.Roles).Through("user_roles")
  • Join model with payload: a model with two one-to-many relations
  • Self-referencing many-to-many: PivotColumns
  • Pivot attributes in results
    • Skipped: []T has nowhere to carry extra columns without a wrapper type on every relation. When a join table holds data of its own, it is a model: make it one, with two has-many relations, and all of this comes for free and typed.
  • Filter and order by pivot columns
    • Skipped: Same reason as pivot attributes: model the join table and query it directly.
  • Pivot timestamps
    • Skipped: Same reason as pivot attributes: a modeled join table gets timestamps like any other model.
  • Attach and detach: ant.Link(ctx, db, user, &Users.Roles, role), ant.Unlink
  • Sync and toggle: ant.SyncLinks, ant.Toggle
  • Update a pivot row: ant.UpdatePivot
    • Skipped: Same reason as pivot attributes: update the modeled join table.
  • Has one through: b.HasOneThrough
  • Has many through: b.HasManyThrough
  • Polymorphic relations: .ForeignKey(&Comments.OwnerID).Morph(&Comments.OwnerType, "post")
  • Polymorphic many-to-many
    • Skipped: It stacks the costs of polymorphism on those of a pivot, with no foreign key to protect either side. Use a modeled join table with a .Morph relation.
  • Morph type map
    • The value given to .Morph, so renaming a Go type cannot change what is stored.
  • Latest or oldest of many: .Latest, .Oldest
  • Touch parent timestamps: .Touch()
  • Scoped relations: .Where
  • Relations without navigation on one side
  • Automatic parent population on children: .Inverse
  • Association operations: through tracked slices, Link, and CountRelated

Querying

  • Query from a table: db.Users.Where(...)
  • Equality: ant.Eq(&Users.Age, 18)
  • Inequality: ant.Ne
  • Comparisons: ant.Gt, ant.Gte, ant.Lt, ant.Lte
  • Set membership: ant.In(&Users.Age, 18, 21)
  • Negated membership: ant.NotIn
  • Range: ant.Between(&Users.Age, 18, 65)
  • Pattern match: ant.Like(&Posts.Title, "Draft%")
  • Null checks: ant.IsNull(&Users.Bio), ant.IsNotNull
  • Nil pointer in ant.Eq renders IS NULL
  • Logical grouping: ant.And, ant.Or, ant.Not
  • Column comparison: ant.EqCol(&Users.ID, &Posts.UserID)
  • Ordering: q.OrderBy(&Users.Name)
  • Descending and secondary ordering: q.OrderByDesc, q.ThenBy, q.ThenByDesc
  • Limit and offset: q.Limit(10), q.Offset(20)
  • All rows: q.All(ctx)
  • First row: q.First(ctx)
  • Exactly one row: q.Single(ctx)
  • Find by primary key: db.Users.Find(ctx, id)
  • Find with fallback: ant.ErrNotFound from Find, First, and Single
  • Raw SQL into structs: ant.Raw[User](db, sql, args...).All(ctx)
  • Raw scalar and unmapped type results: ant.Raw[int], ant.Raw[Summary]
  • Raw non-query statements: ant.Raw[any](db, sql).Exec(ctx)
  • Raw SQL with named arguments: sql.Named("age", 18) and @age
  • Slice expansion in raw SQL arguments: ant.Raw[User](db, "... IN (?)", ids)
  • Placeholder rewriting for portable raw SQL: ? to the dialect form
  • Raw SQL loaded from a file: ant.RawFile[T](db, fsys, name)
  • Conditional clauses: q.When(ok, func(*Query[T]) *Query[T])
  • Join through a relation: q.Join(&Posts.User)
  • Left join through a relation: q.LeftJoin(&Posts.User)
  • Multi-table joins: Join3, Join4
  • Ad hoc join on a condition: q.JoinOn[J](conds...)
  • Join with USING: q.JoinUsing[J](&Users.ID)
  • Right, full, and cross join variants: q.RightJoinOn, q.FullJoinOn, q.CrossJoin
  • Filter by relation existence: ant.Has(&Users.Posts, conds...), ant.HasOne
  • Filter by relation absence: ant.HasNone(&Users.Posts, conds...)
  • Projection with Select: j.Select(func(*Post, *User) R)
  • Single-table projection: ant.Project[R](q, mappings...)
  • Selected columns: q.Column(&Users.ID).Column(&Users.Name)
  • Column-level projection API that prunes the SELECT list: ant.Into, ant.IntoExpr
  • Omit columns: q.Omit(&Users.Bio)
  • Distinct: q.Distinct()
  • Aggregates: q.Count(ctx), ant.SumOf(ctx, q, &Posts.Views), AvgOf, MinOf, MaxOf
  • Exists: q.Exists(ctx), q.DoesNotExist(ctx)
  • Single column values: ant.Pluck(ctx, q, &Users.Name)
  • Group by: q.GroupBy(&Posts.UserID), ant.Then(g, &Posts.Kind), q.GroupByExpr(e)
  • Having: g.Having(...)
  • Group by with typed keys and aggregates: ant.Project, ant.Count(), ant.Sum(&Posts.Views)
  • Subquery in a condition: ant.InSub(&Users.ID, ant.SubOf(q, &Posts.UserID)), ant.NotInSub
  • Exists condition: ant.Exists(q), ant.NotExists(q)
  • Scalar subquery in a projection: ant.SubExpr(q, e).Expr()
  • Subquery ordering
  • From subquery: q.From(sub)
  • Join a subquery: ant.JoinSub, ant.LeftJoinSub
  • Lateral joins: ant.JoinLateral, ant.LeftJoinLateral
  • Unions: a.Union(b), UnionAll, Intersect, Except
  • Common table expressions: q.FromCTE(name, sub)
  • Recursive common table expressions: q.Recursive(&Folders.Children), q.RecursiveOne(&Folders.Parent)
  • Window functions: ant.RowNumber().Over(w), Rank, DenseRank, Lag, Lead, ant.PartitionBy, ant.OrderedBy
  • CASE expressions: ant.Case[V]().When(c, v).Else(v)
  • VALUES lists: ant.Values
  • Multi-column IN: ant.InTuples
  • Any, all, and none across columns: ant.AnyOf, AllOf, NoneOf
  • Date part conditions: ant.DatePart, ant.Today, ant.Past, ant.Future
  • Case-insensitive match: ant.ILike
  • Explicit collation: ant.Collate(&Users.Name, "C")
  • Database function mapping: ant.Func[R](name, args...)
  • Table-valued functions: ant.FromFunc
  • Random ordering: q.OrderByRandom()
  • Clear ordering: q.ClearOrder()
  • Newest and oldest helpers: q.Latest(&Users.CreatedAt), q.Oldest
  • Raw fragments in typed queries: ant.SQL[V](sql, args...)
  • Raw where, having, order, and group fragments: ant.SQLCond, ant.SQL[V]
  • Compose typed queries over raw SQL: ant.FromRaw[T](db, sql)
  • Pessimistic locks: q.ForUpdate(), q.ForShare(), NoWait, SkipLocked
  • Optimizer and index hints: q.Hint(...)
    • PostgreSQL itself ignores hints: it needs the pg_hint_plan extension. On MySQL and MariaDB the hint goes after SELECT.
  • Query comments: q.Tag("name")
  • Column-to-column update expressions: ant.SetExpr(&Users.Age, ant.Col(&Users.Age).Plus(1))

Loading

  • Batched 1:N loading: q.Include(&Users.Posts)
  • Batched N:1 and 1:1 loading: q.IncludeOne(&Posts.User)
  • Nested loading: Include inside the shape function
  • Filtered include: q.Include(&Users.Posts, func(q) { return q.Where(...) })
  • Ordered and limited include, per parent
  • Selected columns in an include
  • Load into existing entities: db.Users.Load(ctx, &Users.Posts, users...), LoadOne
  • Load only if missing: db.Users.LoadMissing
  • Single-query loading through a join: q.IncludeJoined(&Posts.User)
  • Relation counts: q.With(&Users.PostCount, ant.CountRelated(&Users.Posts))
  • Relation aggregates: ant.SumRelated, MinRelated, MaxRelated, AvgRelated
  • Check whether a relation was loaded: a nil slice is not loaded, and an empty slice is
  • Query the related rows of one entity: ant.Related(db, user, &Users.Posts), ant.RelatedOne

Writing

  • Insert one or several: db.Users.Insert(ctx, u1, u2)
  • Generated key copied back to the struct
  • Bulk update: q.Update(ctx, ant.Set(&Posts.Published, true))
  • Bulk delete: q.Delete(ctx)
  • Rows affected returned from bulk operations
  • Block update and delete with no condition: ant.ErrNoCondition, overridden by q.Unfiltered()
  • Delete by primary key: db.Users.DeleteByID(ctx, id)
  • Refresh a loaded entity: db.Users.Reload(ctx, u)
  • Graph insert: db.Users.Insert(ctx, alice) inserts alice.Posts
  • Add related entities through a tracked navigation
  • Remove related entities through a tracked navigation
  • Cascade delete of tracked entities
  • Set-null on orphaned tracked entities
  • Saving disconnected graphs: ant.TrackGraph(ctx, db, root, fn)
  • Skip association saves: db.Users.InsertOnly(ctx, u)
  • Batched SaveChanges statements
    • Inserts only, up to 200 rows a statement. A model with insert hooks, a .Touch() relation, or a WithoutAutoTx save is written one row at a time, because each of those needs a result per row. Updates stay one statement each, since a shared statement could only apply one set of columns.
  • Batched bulk insert: db.Users.InsertMany(ctx, users, ant.BatchSize(500))
  • Insert from a query: db.Users.InsertFrom(ctx, ant.Project[T](q, mappings...)), with ant.WithConflict to skip or update rows a unique constraint holds
  • Insert ignoring conflicts: ant.OnConflict(&Users.Email).DoNothing()
  • Upsert on conflict: db.Users.Upsert(ctx, v, ant.OnConflict(&Users.Email))
  • Upsert selected columns: .DoUpdate(ant.F(&Users.Name)), .Set(...)
  • Upsert returning rows: the entity receives the stored row
  • MERGE where supported: ant.Merge
    • Needs PostgreSQL 15 or later. OnConflict does most of this on older versions.
  • Find or create: db.Users.FirstOrCreate(ctx, v, conds...)
  • Find or initialize without saving: db.Users.FirstOrNew(ctx, v, conds...)
  • Update or create: db.Users.Upsert
  • Bulk update of different values per row: db.Users.UpdateMany(ctx, users, ant.F(&Users.Age))
  • Bulk update from a query: ant.SetExpr with ant.SubExpr
  • Bulk delete with a join: ant.Has, ant.InSub, or ant.Exists in Where
  • Increment and decrement: ant.Inc(&Users.Age, 1), ant.Dec
  • Returning rows from update and delete: q.UpdateReturning, q.DeleteReturning
  • Truncate: db.Users.Truncate(ctx)
  • Bulk copy: PostgreSQL COPY through pgxext.Copy
  • Batched statements in one round trip: pgxext.Batch
    • Moved out of the root package, because the wire protocol feature needs pgx itself, and the root module must not import a driver.
  • Replicate an entity without its key: ant.Clone(user)
  • Automatic timestamps for CreatedAt and UpdatedAt
  • Skip timestamps: b.NoTimestamps()
  • Unix timestamp columns: ant.UnixTime
  • Soft deletes: ant.DeletedAt field
  • Include deleted: q.WithDeleted()
  • Only deleted: q.OnlyDeleted()
  • Restore: q.Restore(ctx)
  • Force delete: q.ForceDelete(ctx)
  • Delete flag alternative for unique indexes
    • b.Index(&Users.Email).Unique().Where("deleted_at IS NULL"), a partial index. It does what a flag does, with no extra column.
  • Pruning old rows: db.Users.Prune(ctx, cond)

Change tracking and unit of work

  • Entity states: detached, added, unchanged, modified, deleted
  • Snapshot on load
  • Property-level diffing
  • db.SaveChanges(ctx)
  • Minimal UPDATE statements
  • Unit-of-work ordering across foreign keys
  • Identity map
  • Opt out per query: q.NoTracking()
  • Default tracking setting: ant.WithTracking(false)
  • No-tracking with identity resolution: q.NoTrackingResolved()
  • Attach an existing entity: ant.Attach(ctx, db, user)
  • Detach an entity: ant.Detach(ctx, db, user)
  • Mark for update: ant.MarkModified(ctx, db, user)
  • Mark for delete: ant.Remove(ctx, db, user)
  • Clear the tracker: db.ClearTracked(ctx)
  • Query state: entry, err := ant.Entry(ctx, db, user), then entry.State()
  • Inspect dirty fields: entry.Changed(), ant.IsDirty(entry, &Users.Age)
  • Original values: ant.Original(entry, &Users.Age)
  • Has pending changes: db.HasChanges(ctx)
  • List tracked entities: ant.Tracked[User](ctx, db)
  • Change detection runs at SaveChanges, so no manual call is needed
  • Custom value comparers for slices and maps: b.Comparer
  • Relationship fixup across loaded entities
    • Skipped: It conflicts with the rule that a field that was not loaded stays empty, which is what makes a nil slice mean "not loaded". With fixup, a field would fill in or not depending on what else ran earlier, which makes bugs that come and go. Elements of a []T relation are values, so ant could not share one entity between two parents anyway. Use Include, which says what you want.
  • Change relations through navigations or foreign keys
  • Temporary keys are not needed: Go zero keys mark new entities, and parents are inserted first
  • Tracker debug output: db.DebugTracked(ctx)
  • Optimistic concurrency token: ant:"version"
  • Native tokens: rowversion on SQL Server
    • Skipped: SQL Server only. ant:"version" covers optimistic concurrency on every database.
  • Application-managed tokens: ant:"token"
  • ErrConcurrency with conflict details: ant.ConcurrencyError

Transactions and connections

  • Open a context: ant.Open[AppDB](ctx, dialect, dsn)
  • Wrap an existing pool: ant.Wrap[AppDB](dialect, sqlDB)
  • Close: db.Close()
  • context.Context on every terminal call
  • Pool settings through db.DB() access to *sql.DB
  • Closure transactions: db.Tx(ctx, func(tx *AppDB) error)
  • Implicit transaction per SaveChanges
  • Disable implicit transactions: ant.WithoutAutoTx()
  • Manual transactions: ant.Begin(ctx, db), tx.Commit(), tx.Rollback()
  • Savepoints: tx.Savepoint(ctx, name), RollbackTo, Release
  • Nested Tx as a savepoint
  • Isolation levels: ant.Isolation(sql.LevelSerializable), ant.ReadOnly()
  • Automatic savepoint in SaveChanges
  • Use an external *sql.Tx: ant.UseTx(db, tx)
  • Use an external *sql.Conn: ant.UseConn(db, conn)
  • Share a transaction across contexts: ant.CurrentTx and ant.UseTx
  • Read and write connections: ant.WithReplicas(...)
  • Replica load balancing: round robin
  • Sticky reads after writes: ant.WithStickyWrites(d)
  • Force primary: ant.OnPrimary(ctx)
  • Retries: ant.WithRetry(ant.Retry{...})
  • Deadlock and serialization retry for Tx: ant.Attempts(5)
  • Commit failure guidance: recipe
  • Multiple contexts over one pool: ant.Session(db)
  • Multi-database routing: recipe
  • Advisory locks through raw SQL or postgres helpers

Lifecycle

  • Errors accumulated in builders and returned at terminal calls
  • Sentinel errors: ErrNotFound, ErrMultipleRows, ErrNotProbe, ErrWrongModel, and others in ant.go
  • Global query filters: b.Filter(name, fn)
  • Multiple named filters
  • Disable filters: q.IgnoreFilters(names...)
  • Filters with context data for multi-tenancy
  • Scopes: q.Scope(fn)
  • Parameterized scopes: a function returning a scope
  • Pending attributes from a scope
    • Skipped: This is how Eloquent presets values on a new model. In Go it is a constructor function.
  • Model hooks: optional BeforeInsert, AfterInsert, BeforeUpdate, AfterUpdate, BeforeDelete, AfterDelete, AfterLoad
  • Hook context and error cancellation
  • Validation hook: optional Validate(ctx) error, run on every insert and update
  • Hook after eager loading: optional AfterInclude
  • Skip hooks: ant.WithoutHooks(ctx)
  • Observers: ant.Observe(db, ant.Observer[User]{...})
  • Observers after commit
  • Query interceptors: ant.WithInterceptor(i)
  • Command interceptors, through Before and After
  • SaveChanges interceptors for auditing: ant.SaveInterceptor
  • Materialization interceptors: AfterLoad
  • Identity resolution interceptors
    • Skipped: EF Core uses this to resolve conflicts when a second instance of an entity is attached. ant returns an error there, and ant.Detach handles it, so there is no decision to intercept.
  • Row-level policies through global filters
  • Context events: ant.WithEvents
  • Multi-tenancy by filter, with an example in tests/features/lifecycle
  • Plugin API: an ant.Option can install interceptors

Schema and migrations

The model is defined in decision 11. The guide is migrations. Everything here works on PostgreSQL. Other dialects implement schema.Dialect, and return schema.ErrUnsupported until then.

  • Schema model built from struct metadata
  • Schema snapshot file: migrations/versions/schema.snapshot.json
  • Diff of models against the snapshot, with no database connection
  • CLI entry point: migrate.Main[AppDB](dialect)
  • Generate a migration: go run ./cmd/migrate diff <name>
  • Generated migrations as plain, editable SQL
  • Versioned folder: migrations/versions
  • Repeatable folder: migrations/code
  • Repeatable files rerun on checksum change, after versioned files
  • Apply: go run ./cmd/migrate up
  • Status: go run ./cmd/migrate status
  • Check for pending model changes in CI: go run ./cmd/migrate check
  • Empty migration for hand-written changes: diff --empty <name>
  • History table with checksums, applied time, and success
  • Custom history table name and schema
  • Checksum validation of applied files
  • Repair stored checksums: migrate repair
  • Migration lock during apply
  • Drift detection against a live database: migrate drift, including the columns that view models read
  • Destructive change warnings in generated SQL
  • Rename warning comment in generated SQL
  • Default source from io/fs.FS, including go:embed
  • Replaceable storage: migrate.Source interface
  • Replaceable file naming: migrate.Config{Name: fn}
  • Apply at runtime: migrate.Up(ctx, db)
  • Idempotent SQL script export: migrate script
  • Per-dialect migration directories
  • Multi-schema migrations
  • Exclude a model from migrations: b.ExcludeFromMigrations()
  • Exclude foreign keys: .NoForeignKey() on a relation
  • Create or drop a schema directly in tests: db.EnsureCreated, db.EnsureDeleted
  • Squash into a baseline: migrate squash
  • Dump the current schema: migrate schema-dump
  • Team divergence detection for duplicate versions
  • Reset local database: migrate reset
  • Skip a migration through configuration
  • Online index creation options: .Concurrently()
  • Instant column and DDL locking options on MySQL
    • Skipped: MySQL only. PostgreSQL migrations are shipped, and schema.Dialect is where this goes when MySQL migrations exist.
  • Seeding: migrate.Seeder and go run ./cmd/migrate seed
  • Seed as repeatable SQL in migrations/code
  • Mute hooks while seeding
  • Data migrations in Go: migrate.Register(version, fn)
  • Export generated SQL for use with other tools: migrate script --plain
  • Rename without losing data: diff --rename users.name=title, an enum value too (status.banned=blocked), or a prompt in a terminal
  • Fill existing rows when adding a NOT NULL column
  • Start from an existing database: migrate adopt, migrate baseline
  • Accept the models with no migration: migrate snapshot
  • Replaceable SQL generation: migrate.Config{Render: fn}
  • Automatic index on foreign keys, removed with .NoIndex()

Database support

  • Dialect interface
  • PostgreSQL dialect
  • MySQL dialect
    • Queries, writes, relations, tracking, and transactions, tested on 8.4 by the conformance suite. No migrations, so it stays behind PostgreSQL. See databases.
  • MariaDB dialect
    • Queries, writes, relations, tracking, and transactions, tested on 11.8 by the conformance suite. No migrations, so it stays behind PostgreSQL. See databases.
  • SQLite dialect
    • Same scope, tested through modernc.org/sqlite.
  • SQL Server dialect
    • Same scope, tested on 2022. Upserts are refused: use ant.Merge.
  • LastInsertId key retrieval where RETURNING is missing
  • SQL Server OUTPUT key retrieval
  • Dialect-specific paging: LIMIT, OFFSET FETCH
  • Dialect type mapping
    • Skipped: Go values reach these databases through their drivers without it. Mapping Go types to column types only matters for generating DDL, which is schema.Dialect, and the owner chose to do migrations on PostgreSQL first. EnsureCreated and SchemaOf report schema.ErrUnsupported on the others.
  • Database error classification: ant.IsUniqueViolation, IsForeignKeyViolation, IsNotNullViolation, IsCheckViolation, IsRetryable
  • Dialect capability flags with clear errors: dialect.Supports, ant.ErrUnsupported
  • Third-party dialects: public Dialect and statement AST
    • The AST moved from internal/qb to the public qb package, so a dialect outside this module can render it. The compatibility policy keeps it outside the stability promise until such a dialect exists.

Performance

  • Streaming: q.Each(ctx)
  • Batched reads: q.Chunk(ctx, 500, fn)
  • Keyed batches: q.ChunkByKey(ctx, 500, fn)
  • Offset paging helper: q.Page(ctx, n, size) returning items and total
  • Simple paging without a total: q.Limit(n).Offset(m)
  • Keyset paging: q.After(ctx, cursor, size)
  • Encoded cursors: page.Next
  • Prepared statement cache: pgx caches statements per connection
  • Reuse of rendered SQL for repeated query shapes
    • Skipped: Measured, and not worth it. Rendering a typical query takes about 7 µs, against hundreds for the round trip, and a cache key built from the same AST would cost about what it saves. pgx already caches prepared statements per connection. See benchmarks.
  • Benchmarks against GORM, Bun, and database/sql: benchmarks
    • Plain database/sql stands in for sqlc, whose generated code is the same query string and Scan. Adding sqlc itself would need a code generation step in this repository to measure the same thing.
  • Allocation budget for query building and scanning
  • Probe resolution benchmark

Developer tooling

  • Multi-database test harness: internal/testdb
  • Docker Compose database matrix
  • CI with unit and integration jobs: .github/workflows/pr-ci.yml runs lint, the PostgreSQL suite under the race detector, and the other databases on every pull request
  • Logging through log/slog: ant.WithLogger(l)
  • Log levels and slow query threshold: ant.SlowThreshold(d)
  • Sensitive value redaction by default: ant.LogValues() opts in
  • Debug one query: q.Debug()
  • SQL inspection: q.ToSQL()
  • Dry run: ant.DryRun(ctx, db, fn)
    • It runs real statements in a transaction that rolls back, so sequences advance, and side effects outside the database still happen.
  • Last executed SQL through an interceptor
  • OpenTelemetry tracing: module contrib/otel
  • Metrics sub-package with a Prometheus exporter: package metrics
    • No OpenTelemetry exporter, because importing it would pull its SDK into the root module. Snapshot returns the numbers, and a few lines in your own code can publish them through any meter.
  • Cumulative query time alert: ant.WithDiagnostics with Budget
  • Warn on cartesian explosion
    • Through ant.WithDiagnostics.
  • Warn on N+1 patterns from repeated statements
    • RepeatLimit in ant.WithDiagnostics.
  • Detailed query errors with SQL context: ant.WithDetailedErrors, ant.FailedSQL
  • Execution plan helper: q.Explain(ctx)
  • go vet analyzer that flags non-probe field pointers: module tools/antvet
  • Analyzer check for probes from the wrong model
  • Analyzer check for mismatched Find key types
  • Fixtures in anttest: anttest.Load(t, db, fs)
  • Factories in anttest: anttest.Factory[T]
  • Factory states and overrides
  • Factory sequences
  • Factory relations and recycled parents: anttest.Recycle
    • No pivot attributes, for the same reason ant has none: a join table with data is a model, with a factory of its own.
  • Factory build and create
  • Factory callbacks
  • Transactional test isolation: anttest.Isolate(t, db)
  • Testing guide: testing
  • Reverse engineering structs from a database: migrate scaffold
    • Skipped: Owner decision. A database does not say which integer is an enum, what a relation should be called, or what belongs together, so the output needs reading line by line anyway. Instead, adopting a database gives an AI assistant a prompt, and drift checks the result until nothing differs.
  • Model inspection command: migrate inspect
  • Database summary command: migrate db-show, with materialized views
  • Documentation site: skudra.net, built from ant-docs
    • Docusaurus, with every Go sample type-checked against ant.
  • Runnable examples for every public API
    • Skipped: Partly done, and left open on purpose. example_test.go has runnable examples for the core calls, and tests/features/ shows every feature against a real database, but most calls need a server, which go test examples cannot assume. An example for each of the 900 lines in docs/api.txt would mostly repeat those tests.
  • Recipe guides: recipes
    • Also partitioning, several databases, and commit failures.
  • Public API freeze
    • Skipped: Left to the owner. docs/api.txt records the candidate, and tests/api fails on any change to it, so freezing is a matter of declaring it. The call should come after using it for real, since Session options, exec.Wrap, and anttest.Isolate all changed in this work.
  • Security review: security
    • Done in-house, with known limits listed on that page. An outside review is still worth having before 1.0.
  • Upgrade guide: each GitHub release lists its breaking changes
  • Compatibility policy: compatibility

Not planned

Each entry is a feature from the reference catalogs that ant does not intend to implement.

Loading and object model

  • Lazy loading through field access, proxies, or injected loaders: conflicts with no hidden I/O.
  • Automatic eager loading on access: same reason.
  • Auto-include configured on the model: every load stays visible at the call site.
  • Active record methods such as user.Save(), push, and save on models: saving goes through the context.
  • Dynamic relationship properties and runtime-registered relations: not compatible with typed structs.
  • Magic factory and relation methods: same reason.
  • Service injection and constructor binding: Go structs have no constructors.
  • Backing fields, field access modes, and indexer properties: C# and PHP language features.
  • Shadow properties and property bag entities: columns must be struct fields.
  • Change-tracking proxies and notification entities: Go has no runtime proxies, and snapshots cover the need.
  • Shared-type entity types: no equivalent need with Go generics.

Query and mapping features tied to another language

  • LINQ translation and client evaluation: Go has no expression trees.
  • Compiled query delegates and compiled models: only needed for expression-tree cost.
  • NativeAOT and precompiled queries: .NET specific. Go is already compiled.
  • Dynamic models through IModelCacheKeyFactory: .NET specific.
  • async variants of operators: Go uses goroutines.
  • Mass assignment guards: Go code assigns struct fields directly.
  • Eloquent collection helpers: use the slices and maps packages.
  • API resources, JSON:API resources, and serialization visibility helpers: HTTP concerns outside an ORM.
  • Pagination views and URL generation: HTTP concerns. Paging data is provided.
  • String-based relation names and conditions as the main API: conflicts with typed queries.
  • db.Cond-style map conditions: conflicts with typed queries.
  • Struct or map conditions that skip zero values: conflicts with no zero-value guessing.
  • Update behavior that skips zero fields, including OmitZero and boil.Infer: same reason.
  • Update behaviors that infer columns from Go zero values in Save or Updates: same reason.

Migrations

  • Down migrations, undo files, and generated rollback scripts: out of scope by owner decision. Write a forward migration.
  • migrate:rollback, refresh, and reset to a past version: same reason.
  • AutoMigrate at startup: changes are generated and reviewed instead.
  • Shadow databases: the snapshot makes them unnecessary.
  • Migration code in C#, PHP, Fizz, or HCL: migrations are plain SQL, or Go for data migrations.
  • Migration bundles: a Go binary with go:embed already covers this.
  • Atlas linting, plans, checkpoints, schema tests, and Atlas Cloud: Atlas can consume ant's SQL if wanted.
  • Declarative schema apply: ant is migration-file based.
  • Database security as code, including roles and grants: outside an ORM.
  • Terraform, Kubernetes, Argo CD, and Crossplane integrations: deployment tooling.
  • T4 scaffolding templates: .NET specific.

Code generation

  • Code generation for models, clients, or queries: conflicts with the core goal.
  • sqlc-style generation from SQL: a different approach. ant.Raw covers raw SQL.
  • Generator templates, plugins, and multiple language outputs: no generator exists.
  • GraphQL and gRPC generators: outside an ORM.
  • Generated compatibility tests: no generated code to test.

Databases

  • Azure Cosmos DB, MongoDB, and other NoSQL stores: relational only.
  • Gremlin and graph traversal APIs: relational only.
  • QL: not in wide use, and not a target database.
  • In-memory test provider: tests should use a real database, with SQLite for speed.
  • Oracle, ClickHouse, DuckDB, Spanner, GaussDB, Snowflake, Databricks, and Redshift in core: community dialects can add them through the public interface.
  • CockroachDB, TiDB, YugabyteDB, Aurora DSQL, and Vitess in core: wire-compatible use may work, but is not tested.
  • Provider packages for Azure-specific features: outside the five target databases.

Infrastructure

  • Diagnostic listeners and event counters: interceptors and metrics cover this.
  • ConfigureDbContext composition: functional options cover this.
  • Queueable listeners and event classes: Laravel queue features. Observers can start goroutines.
  • Multiple result sets from one statement: use db.DB().
  • Data dump and import, as in xorm DumpAll: use database tools.
  • Starter kits: not part of the library.
  • Stringable and anonymous cast classes: PHP specific. Value converters cover the need.
  • Connection through a framework URL configuration: a DSN is already a URL.
  • Sharding: application or proxy concern.
  • Built-in result caching, including xorm's LRU cache: stale data risk. Use a cache outside the database.
  • DbContext pooling: an ant context is cheap, and database/sql pools connections.
  • Pooled PostgreSQL connection configuration: handled by the driver or PgBouncer.
  • System.Transactions and distributed transactions: .NET specific.
  • dotnet ef, Package Manager Console, and Laravel Artisan commands: replaced by cmd/migrate.
  • Database CLI launcher: use psql and similar tools.
  • Connection monitoring events such as db:monitor: use database monitoring.
  • Windows Forms and WPF data binding through DbSet.Local: .NET UI specific.
  • Logrus and Zap integrations: use log/slog adapters.
  • Hosted services such as Uptrace, Atlas Cloud, and sqlc push: outside the project.
  • Connection string formats for specific .NET app types: .NET specific.
  • Must* panicking variants, as in sqlx: conflicts with explicit errors.