Skip to main content

Several databases

For read replicas of a single database, see read replicas.

Use one context per database​

Each context has its own models, migrations, cmd/migrate and connection pool.

type Invoice struct {
ID int64
}

type MainDB struct {
ant.Context
Users ant.Table[User]
}

type BillingDB struct {
ant.Context
Invoices ant.Table[Invoice]
}

A relation can't cross databases. Keep the key and load the other side in a second query. Mark such a relation .NoForeignKey().

Open each with its own dialect and DSN:

mainDB, err := ant.Open[MainDB](ctx, postgres.Dialect, "postgres://localhost/main")
billingDB, err := ant.Open[BillingDB](ctx, mysql.Dialect, "app:app@tcp(localhost:3306)/billing?parseTime=true")

Route requests to a database per tenant​

Keep a map of open contexts and pick one per request. Open each once, since a context owns a connection pool.

A tracking context serves one operation at a time, so two requests sharing one get ErrConcurrentUse. Give each request an ant.Session, which shares the pool and has its own tracker.

type Router struct {
mu sync.RWMutex
dbs map[string]*AppDB
}

func (r *Router) For(ctx context.Context, tenant string) (*AppDB, error) {
shared, err := r.pool(ctx, tenant)
if err != nil {
return nil, err
}

return ant.Session(shared), nil
}

func (r *Router) pool(ctx context.Context, tenant string) (*AppDB, error) {
r.mu.RLock()
db := r.dbs[tenant]
r.mu.RUnlock()

if db != nil {
return db, nil
}

r.mu.Lock()
defer r.mu.Unlock()

if db := r.dbs[tenant]; db != nil {
return db, nil
}

db, err := ant.Open[AppDB](ctx, postgres.Dialect, dsnFor(tenant))
if err != nil {
return nil, err
}

r.dbs[tenant] = db

return db, nil
}

func dsnFor(tenant string) string {
return "postgres://localhost/" + tenant
}
func (r *Router) Close() error {
r.mu.Lock()
defer r.mu.Unlock()

var errs []error

for _, db := range r.dbs {
errs = append(errs, db.Close())
}

return errors.Join(errs...)
}

Apply migrations to each with migrate.Up, which is safe to call from several processes at once.

No cross-database transactions

A transaction can't span databases, and ant has no two-phase commit. Use an outbox to carry a change from one to the other.