Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
B

bun

> 数据库
Open source

SQL-first Golang ORM

97.1K stars0 likes13 views
WebsiteGitHub

About

SQL-first Golang ORM

Bun: SQL-first Golang ORM

Lightweight, SQL-first Golang ORM for PostgreSQL, MySQL, MSSQL, SQLite, and Oracle

Bun is a modern ORM that embraces SQL rather than hiding it. Write complex queries in Go with type safety, powerful scanning capabilities, and database-agnostic code that works across multiple SQL databases.

✨ Key Features

  • SQL-first approach - Write elegant, readable queries that feel like SQL
  • Multi-database support - PostgreSQL, MySQL/MariaDB, MSSQL, SQLite, and Oracle
  • Type-safe operations - Leverage Go's static typing for compile-time safety
  • Flexible scanning - Query results into structs, maps, scalars, or slices
  • Performance optimized - Built on database/sql with minimal overhead
  • Rich relationships - Define complex table relationships with struct tags
  • Production ready - Migrations, fixtures, soft deletes, and OpenTelemetry support

Quick Start

bash
go get github.com/uptrace/bun

Basic Example

…

Why Choose Bun?

Elegant Complex Queries

Write sophisticated queries that remain readable and maintainable:

…

Flexible Result Scanning

Scan query results into various Go types:

go
// Into structs
var users []User
db.NewSelect().Model(&users).Scan(ctx)

// Into maps
var userMaps []map[string]interface{}
db.NewSelect().Table("users").Scan(ctx, &userMaps)

// Into scalars
var count int
db.NewSelect().Table("users").ColumnExpr("COUNT(*)").Scan(ctx, &count)

// Into individual variables
var id int64
var name string
db.NewSelect().Table("users").Column("id", "name").Limit(1).Scan(ctx, &id, &name)

Database Support

Database Driver Dialect
PostgreSQL github.com/uptrace/bun/driver/pgdriver pgdialect.New()
MySQL/MariaDB github.com/go-sql-driver/mysql mysqldialect.New()
SQLite github.com/uptrace/bun/driver/sqliteshim sqlitedialect.New()
SQL Server github.com/denisenkom/go-mssqldb mssqldialect.New()
Oracle github.com/sijms/go-ora/v2 oracledialect.New()

Advanced Features

Table Relationships

Define complex relationships with struct tags:

go
type User struct {
    ID      int64   `bun:",pk,autoincrement"`
    Name    string  `bun:",notnull"`
    Posts   []Post  `bun:"rel:has-many,join:id=user_id"`
    Profile Profile `bun:"rel:has-one,join:id=user_id"`
}

type Post struct {
    ID     int64 `bun:",pk,autoincrement"`
    Title  string
    UserID int64
    User   *User `bun:"rel:belongs-to,join:user_id=id"`
}

// Load users with their posts
var users []User
err := db.NewSelect().
    Model(&users).
    Relation("Posts").
    Scan(ctx)

Bulk Operations

Efficient bulk operations for large datasets:

go
// Bulk insert
users := []User{{Name: "John"}, {Name: "Jane"}, {Name: "Bob"}}
_, err := db.NewInsert().Model(&users).Exec(ctx)

// Bulk update with CTE
_, err = db.NewUpdate().
    Model(&users).
    Set("updated_at = NOW()").
    Where("active = ?", true).
    Exec(ctx)

// Bulk delete
_, err = db.NewDelete().
    Model((*User)(nil)).
    Where("created_at < ?", time.Now().AddDate(-1, 0, 0)).
    Exec(ctx)

Migrations

Version your database schema:

go
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)

Monitoring & Observability

Debug Queries

Enable query logging for development:

go
import "github.com/uptrace/bun/extra/bundebug"

db.AddQueryHook(bundebug.NewQueryHook(
    bundebug.WithVerbose(true),
))

OpenTelemetry Integration

Production-ready observability with distributed tracing:

go
import "github.com/uptrace/bun/extra/bunotel"

db.AddQueryHook(bunotel.NewQueryHook(
    bunotel.WithDBName("myapp"),
))

Monitoring made easy: Bun is brought to you by ⭐ uptrace/uptrace. Uptrace is an open-source APM tool that supports distributed tracing, metrics, and logs. You can use it to monitor applications and set up automatic alerts to receive notifications via email, Slack, Telegram, and others.

See OpenTelemetry example which demonstrates how you can use Uptrace to monitor Bun.

Documentation & Resources

  • Getting Started Guide - Comprehensive tutorial
  • API Reference - Complete package documentation
  • Examples - Working code samples
  • Starter Kit - Production-ready template
  • Community Discussions - Get help and share ideas

Contributing

We welcome contributions! Please see our Contributing Guide for details on how to get started.

Thanks to all our contributors:

Related Projects

  • Golang HTTP router - Fast and flexible HTTP router
  • Golang msgpack - High-performance MessagePack serialization

Issues· 37 open

View all issuesOpen on GitHub
  • #1394

    Dropped field value(s) on slice model insert

    help wantedno stalebotUpdated Sep 26, 2026
  • #1434

    Scanning into map[string]any deadlocks forever on Go 1.27 with pgx v5.11

    Updated Sep 21, 2026
  • #1431

    newArrayParser indexes b[0] without length check, panicking on empty scan input

    Updated Sep 10, 2026
  • #1427

    Go 1.27 uuid.UUID not supported: "bun: Scan(unsupported uuid.UUID)"

    enhancementUpdated Aug 31, 2026
  • #1363

    Important Notes on Releasing the Next Version

    staleno stalebotreleaseUpdated Jul 22, 2026
  • #1321

    Adding a query with a WHERE OR on a soft-delete model ignores soft-delete condition

    no stalebotUpdated Apr 8, 2026
  • #1288

    Raw queries should allow scanning row by row

    staleno stalebotUpdated Apr 4, 2026
  • #1339

    Panic from Column-Scan mismatch causes deadlock

    staleno stalebotUpdated Apr 4, 2026
  • #1128

    [Question] Does Bun support optimistic locking?

    enhancementhelp wantedUpdated Apr 3, 2026
  • #1297

    Migration Add API Broken

    staleno stalebotUpdated Mar 24, 2026

> Tags

Godatabasegogolangmssql

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedDec 1, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库