bun

repository·master·Indexed 26 days ago

https://github.com/uptrace/bun

A lightweight, SQL-first Golang ORM designed for PostgreSQL, MySQL, MSSQL, SQLite, and Oracle. Bun focuses on type-safe, elegant query construction that embraces SQL. It includes drivers such as pgdriver for PostgreSQL and sqliteshim for SQLite, as well as a database CLI for managing migrations (init, migrate, rollback, unlock, create_go, create_sql). Additional features include support for big.Int and big.Float via the bunbig package and OpenTelemetry instrumentation for monitoring with Uptrace.

Tokens
27.7K
Snippets
62
Records
255
Agent score
89%

What's inside bun

  1. Use bunbig for big.Int and big.Float support in Bun

    master

    Since the standard math/big package does not implement database/sql scan/value methods, it cannot be used directly with Bun. bunbig provides a wrapper around math/big that allows you to use big.Int and big.Float types within your Bun models and database operations (including PostgreSQL).

    type TableWithBigint struct {
    	ID      uint64
    	Name    string
    	Deposit *bunbig.Int
    	Residue *bunbig.Float
    }
  2. Configure bunslog QueryHook

    master

    To log SQL queries executed by Bun using slog, create a new QueryHook using bunslog.NewQueryHook and register it with your *bun.DB instance using AddQueryHook. You can pass several options to control log levels for general queries, slow queries, and error queries.

    import (
    	"github.com/uptrace/bun"
    	"github.com/uptrace/bun/extra/bunslog"
    	"log/slog"
    	"time"
    )
    
    // ... setup sqldb and dialect ...
    
    db := bun.NewDB(sqldb, dialect)
    
    hook := bunslog.NewQueryHook(
    	bunslog.WithQueryLogLevel(slog.LevelDebug),
    	bunslog.WithSlowQueryLogLevel(slog.LevelWarn),
    	bunslog.WithErrorQueryLogLevel(slog.LevelError),
    	bunslog.WithSlowQueryThreshold(3 * time.Second),
    )
    
    db.AddQueryHook(hook)
  3. Manage database migrations

    master

    Use the github.com/uptrace/bun/migrate package to version your database schema. You register migration functions (Up and Down) and use a Migrator to execute them.

    import "github.com/uptrace/bun/migrate"
    
    migrations := migrate.NewMigrations()
    
    migrations.MustRegister(func(ctx context.Context, db *bun.DB) error {
        _, err := db.NewCreateTable().Model((*User)(nil)).Exec(ctx)
        return err
    }, func(ctx context.Context, db *bun.DB) error {
        _, err := db.NewDropTable().Model((*User)(nil)).Exec(ctx)
        return err
    })
    
    migrator := migrate.NewMigrator(db, migrations)
    err := migrator.Init(ctx)
    err = migrator.Up(ctx)
  4. Use OpenTelemetry instrumentation for Bun

    master
    Bun provides OpenTelemetry (OTel) instrumentation to enable observability for your database operations. For a complete implementation guide and code examples, refer to the official example repository located at example/opentelemetry within the project.