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:

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:


Let's keep in touch!

Stay updated with my latest posts and news. I share insights, updates, and exclusive content.

By subscribing, you share your email with @uptrace and accept our Terms & Privacy. Unsubscribe anytime.

Give a Pawfive to this post!


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.dev account now!

Developer Influence
57

Influence

6k

Total Hits

2

Posts