Skip to content

Databases & caches ​

Resources are typed wrappers that embed a framework manager. nexus manages their lifecycle (start on boot, stop on shutdown), provides them to the DI graph, and shows them on the dashboard, in red when they are down.

Databases ​

go
import (
    "github.com/paulmanoni/nexus/v2/db"
    _ "github.com/paulmanoni/nexus/v2/db/postgres" // the driver(s) you use
)

type DB struct{ *db.Manager }

nexus.Boot(
    db.BindFromConfig[DB]("main"),   // reads [databases.main]
    usersModule,
)
toml
[databases.main]
driver   = "postgres"
host     = "localhost"
port     = "5432"
user     = "postgres"
password = "${DB_PASSWORD}"
name     = "shop"
sslmode  = "disable"
default  = true
# log    = "warn"   # SQL logging: on in dev, silent in prod unless forced

# pool (optional; a key left out keeps the default: 100 open, 10 idle,
# recycled after 1h and after 30m idle; a negative value lifts the limit)
max_open           = 50
max_idle           = 10
conn_max_lifetime  = "1h"
conn_max_idle_time = "30m"

[databases.main.session]   # optional: set on every connection the pool opens
statement_timeout = 5000

Handlers and services take *DB as a parameter. db.GetDB() returns the *gorm.DB.

  • Drivers are opt-in blank imports, as with database/sql: db/postgres (pgx), db/mysql or db/sqlite (pure Go). A config naming a driver that isn't linked fails at boot and names the import to add.
  • File-backed SQLite gets a small read pool. Add a busy_timeout pragma to the DSN.
  • MySQL sends each query in one round trip: the driver escapes the arguments into the statement (interpolateParams), as Django's MySQL backend does, instead of preparing it on the server first (two round trips). It's safe because nexus always connects with charset=utf8mb4, never a charset whose escaping can be bypassed. interpolate_params = false in [databases.<name>] (or db.Config.InterpolateParams) goes back to server-side prepared statements. With MySQL's general or slow query log on, logged statements then contain the values.
  • Session settings ([databases.<name>.session], db.Config.Session) apply to every pooled connection, not just the first: MySQL system variables (foreign_key_checks = 0, sql_mode = "NO_ENGINE_SUBSTITUTION"), Postgres run-time parameters (search_path, statement_timeout), SQLite pragmas (foreign_keys = true). Write values plainly — nexus quotes them for the driver; true/false become on/off. A name the driver keeps as its own option (parseTime, sslmode, …) fails boot; the zone stays timezone.
  • Inline config with no TOML: db.Bind[DB]("main", func() db.Config { ... }).
  • Options: db.WithDefault(), db.WithDescription(...), db.WithDetails(...).

Caches ​

go
import (
    "github.com/paulmanoni/nexus/v2/extension/cache"
    _ "github.com/paulmanoni/nexus/extension/cache/redis/v2" // optional: Redis
)

type Cache struct{ *cache.Manager }

cache.Bind[Cache]("session",
    func() *cache.Config { return &cache.Config{} },
    cache.WithDefault(),
)

The default cache is in-memory only and pulls in no heavy dependencies. Blank-import extension/cache/redis to use Redis with transparent in-memory failover. Without that import, go-redis is never linked. cache.BindFromConfig[Cache]("session") reads a [cache.session] table.

Choosing the store per cache ​

With the Redis backend imported, a cache uses Redis in production and memory elsewhere. driver overrides that for one cache:

toml
[cache.session]
driver = "redis"     # Redis in every environment; boot fails without the backend import

[cache.lookups]
driver = "memory"    # never Redis, even in production with the backend imported
  • Default. driver = "auto", or leaving it out, keeps the environment rule.
  • In code set cache.Config{Driver: cache.DriverMemory}.
  • From the environment, CACHE_DRIVER sets the default for every cache built from NewConfig. A per-cache key such as CACHE_SESSION_DRIVER=memory overrides it through config.Get.
  • On the dashboard, the cache resource shows its driver, for example memory (redis disabled).
  • An unknown driver fails the boot. So does redis without the backend import.

Pay for what you import ​

The binders live in db and extension/cache, not the nexus root package. Importing nexus alone does not pull GORM, SQL drivers, Redis or Prometheus into your build.

The same rule applies to background jobs. extension/jobs itself has no heavy dependencies. jobsdb pulls in GORM, which a database app links anyway. jobsredis and jobsamqp are separate modules, so their Redis and AMQP clients reach your build only when you import them.

Other resources ​

Register anything else, such as a queue, by hand:

go
q := resource.NewQueue("jobs", "Background jobs", details, healthy, resource.DependsOn("main"))
app.Register(q)

Or implement NexusResources() []resource.Resource on a type your constructors return, and nexus picks the resources up automatically.

Released under the MIT License.