Skip to content

dbx examples

dbx Examples

This page collects the runnable examples/dbx programs and maps them to the API surface they demonstrate.

Run Locally

Run from the examples/dbx module:

cd examples/dbx
go run ./basic
go run ./codec
go run ./mutation
go run ./query_advanced
go run ./relations
go run ./migration
go run ./pure_sql
go run ./id_generation

You can also run directly from the repository root:

go run ./examples/dbx/basic
go run ./examples/dbx/codec
go run ./examples/dbx/mutation
go run ./examples/dbx/query_advanced
go run ./examples/dbx/relations
go run ./examples/dbx/migration
go run ./examples/dbx/pure_sql
go run ./examples/dbx/id_generation

Example Matrix

ExampleFocusDirectory
basicschema-first modeling, mapper scan, projection, tx, debug SQL, hooksexamples/dbx/basic
codecbuilt-in codecs, scoped custom codecs, struct mapper reads, mapper write assignmentsexamples/dbx/codec
mutationaggregate queries, subqueries, batch insert, insert-select, upsert, returningexamples/dbx/mutation
query_advancedWITH, UNION ALL, CASE WHEN, named tables, result columnsexamples/dbx/query_advanced
relationsalias + relation metadata + JoinRelation, plus LoadBelongsTo and LoadManyToManyexamples/dbx/relations
migrationPlanSchemaChanges, SQLPreview, AutoMigrate, ValidateSchemas, migrate.NewRunner(core.SQLDB(), core.Dialect(), ...).UpGo/UpSQLexamples/dbx/migration
pure_sqlsqltmplx registry, dbx.SQLList/SQLGet/SQLFind/SQLScalar, statement-name logging, tx.SQL().Exec(...)examples/dbx/pure_sql
id_generationtyped ID strategy markers: IDAuto, IDSnowflake, IDUUIDv7, and IDColumnexamples/dbx/id_generation

Example: Codec and StructMapper

mapper := dbx.MustStructMapperWithOptions[shared.Account](
    dbx.WithMapperCodecs(csvCodec),
)

items, err := dbx.QueryAll(
    ctx,
    core,
    dbx.Select(catalog.Accounts.AllColumns()...).From(catalog.Accounts),
    mapper,
)
if err != nil {
    panic(err)
}

Example: Advanced Query DSL

statusLabel := dbx.CaseWhen[string](catalog.Users.Status.Eq(1), "active").
    Else("inactive").
    As("status_label")

activeUsers := dbx.NamedTable("active_users")
activeID := dbx.NamedColumn[int64](activeUsers, "id")
activeName := dbx.NamedColumn[string](activeUsers, "username")

query := dbx.Select(activeID, activeName, statusLabel).
    With("active_users",
        dbx.Select(catalog.Users.ID, catalog.Users.Username).
            From(catalog.Users).
            Where(catalog.Users.Status.Eq(1)),
    ).
    From(activeUsers)

Example: Relation Loading

if err := dbx.LoadBelongsTo(
    ctx,
    core,
    users,
    catalog.Users,
    userMapper,
    catalog.Users.Role,
    catalog.Roles,
    roleMapper,
    func(index int, user *shared.User, role mo.Option[shared.Role]) {
        // attach role
    },
); err != nil {
    panic(err)
}

Example: Schema Plan Preview and Runner

plan, err := core.PlanSchemaChanges(ctx, catalog.Roles, catalog.Users, catalog.UserRoles)
if err != nil {
    panic(err)
}

for _, sqlText := range plan.SQLPreview() {
    fmt.Println(sqlText)
}

runner := core.Migrator(migrate.RunnerOptions{ValidateHash: true})
_, err = runner.UpSQL(ctx, source)
if err != nil {
    panic(err)
}

Example: Pure SQL With sqltmplx

registry := sqltmplx.NewRegistry(sqlFS, core.Dialect())

items, err := dbx.SQLList(
    ctx,
    core,
    registry.MustStatement("sql/user/find_active.sql"),
    struct {
        Status int `dbx:"status"`
    }{Status: 1},
    dbx.MustStructMapper[shared.UserSummary](),
)
if err != nil {
    panic(err)
}