Join us

Bun: SQL-first Golang ORM

Bun is a SQL-first Golang ORM for PostgreSQL, MySQL/MariaDB, MSSQL, and SQLite.

SQL-first means you can write SQL queries in Go, for example, the following Bun query:

Generates the following SQL:

SQL is still there, but Bun helps you generate long queries while protecting against SQL injections thanks to ? placeholders:

Using Bun, you can write really complex queries, for example, the following Bun query:

Generates the following SQL:

Structs and tables

Bun allows you to map Go structs to database tables using struct-based models, for example, the following code:

Generates the following table:

You can then select/insert/update/delete rows using Go structs:

See Bun documentation for details.

Golang ORM

So what about Golang ORM part? Bun allows you to define common table relations using Go structs, for example, here is how you can define Author belongs to Book relation:

And then use Relation method to join tables:

See ORM: Table relationships for details.

Connecting to a database

Bun works on top of database/sql and supports PostgreSQL, MySQL/MariaDB, MSSQL, and SQLite.

To connect to a PostgreSQL database:

To connect to a MySQL database:

To log all executed queries, you can install bundebug plugin:

Executing queries

Once you have a model, you can start executing queries:

When it comes to scanning query results, Bun is very flexible and allows scanning into structs:

Into scalars:

Into a map[string]interface{}:

And into slices of the types above:

You can also return results from insert/update/delete queries and scan them too:

What's next?

To get started, see the Bun Golang ORM docs and run examples.

Bun comes with many plugins including OpenTelemetry instrumentation that enables OpenTelemetry tracing and OpenTelemetry metrics.

Using tracing, you can monitor performance using one of the distributed tracing tools that work with OpenTelemetry. Many DataDog competitors also support OpenTelemetry.

Besides, you can export metrics to Prometheus and visualize them using Grafana or a popular alternative.


Only registered users can post comments. Please, login or signup.

Start blogging about your favorite technologies, reach more readers and earn rewards!

Join other developers and claim your FAUN account now!

User Popularity
35

Influence

3k

Total Hits

2

Posts