Databases
Databases Overview
Choose where database code lives and how migrations, services, and PostgreSQL fit together.
Database work in a GoLazy app has two layers:
- Application services own product behavior such as creating posts, finding users, or storing imports.
- Framework packages provide reusable building blocks for migrations, jobs, file catalogs, media variants, and object storage.
Keep request handlers out of the database details. Controllers should call application services; services can use a pool, transaction, repository, or framework backend behind their own package API.
Start with services
Open database connections during application startup, usually from
init/dependencies.go, and put shared handles into the application context:
_, err := lazydeps.Service(deps, "postgres", func(ctx context.Context) (
context.Context,
*pgxpool.Pool,
error,
context.CancelFunc,
) {
pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
return ctx, nil, err, nil
}
return pg.WithPool(ctx, pool), pool, nil, func() { pool.Close() }
})
Application services then read the handle from context and expose operations that match the domain:
func New(ctx context.Context) (*Service, error) {
pool, ok := pg.FromContext(ctx)
if !ok {
return nil, fmt.Errorf("postgres pool missing")
}
return &Service{pool: pool}, nil
}
Read Context And Services for the application dependency pattern.
Add migrations before data
Use Migrations when schema changes need to be
tracked and replayed. Migration sources live in embedded files. Backends record
which migration IDs have run and execute up, down, or redo steps.
For PostgreSQL, package migrations use -- +lazy Up and -- +lazy Down
sections so package-owned schema can travel with package-owned code.
Choose PostgreSQL backends when needed
Use PostgreSQL when the app needs durable implementations for GoLazy packages:
pgmigratefor migration state.pgjobsfor durable background jobs.pgstoragefor object bytes.pgfilesfor stored file metadata.pgmediafor generated media variants.
Read Background Jobs and Storage, Assets, And Media when those higher-level features are the reason the database is being added.