Drivers and dialects
To connect to a database, you need a database/sql driver and a corrensponding SQL dialect that comes with bun.
PostgreSQL
See PostgreSQL section for information about using Bun with PostgreSQL.
MySQL
Bun supports MySQL 5+ and MariaDB using MySQL driver
open in new window and mysqldialect:
1. import (
2. "github.com/uptrace/bun"
3. "github.com/uptrace/bun/dialect/mysqldialect"
4. _ "github.com/go-sql-driver/mysql"
5. )
7. sqldb, err := sql.Open("mysql", "root:pass@/test")
8. if err != nil {
9. panic(err)
10. }
12. db := bun.NewDB(sqldb, mysqldialect.New())
MSSQL
Bun supports SQL Server v2019.CU4 starting from v1.1.x. To connect to a SQL Server, use go-mssqldb
open in new window driver and mssqldialect:
1. import (
2. "github.com/uptrace/bun"
3. "github.com/uptrace/bun/dialect/mssqldialect"
4. _ "github.com/denisenkom/go-mssqldb"
5. )
7. sqldb, err := sql.Open("sqlserver", "sqlserver://sa:passWORD1@localhost:1433?database=test")
8. if err != nil {
9. panic(err)
10. }
12. db := bun.NewDB(sqldb, mssqldialect.New())
SQLite
To connect to a SQLite database, use sqliteshim
open in new window driver which automatically imports modernc.org/sqlite
open in new window or mattn/go-sqlite3
open in new window depending on your platform.
1. import (
2. "github.com/uptrace/bun"
3. "github.com/uptrace/bun/dialect/sqlitedialect"
4. "github.com/uptrace/bun/driver/sqliteshim"
5. )
7. sqldb, err := sql.Open(sqliteshim.ShimName, "file::memory:?cache=shared")
8. if err != nil {
9. panic(err)
10. }
12. db := bun.NewDB(sqldb, sqlitedialect.New())
If you are using an in-memory database, you need to configure *sql.DB to NOT close active connections. Otherwise, the database is deleted when the connection is closed.
1. sqldb.SetMaxIdleConns(1000)
2. sqldb.SetConnMaxLifetime(0)
Writing DMBS specific code
Bun comes with feature
open in new window package that allows you to discover features supported by your DBMS:
1. import "github.com/uptrace/bun/dialect/feature"
3. if db.HasFeature(feature.InsertOnConflict) {
4. // DBMS supports `ON CONFLICT DO UPDATE` (PostgreSQL, SQLite)
5. }
7. if db.HasFeature(feature.InsertOnDuplicateKey) {
8. // DBMS supports `ON DUPLICATE KEY UPDATE` (MySQL, MariaDB)
9. }
You can also directly check the database dialect name:
1. import "github.com/uptrace/bun/dialect"
3. switch db.Dialect().Name() {
4. case dialect.SQLite:
5. case dialect.PG:
6. case dialect.MySQL:
7. case dialect.MSSQL:
8. default:
9. panic("not reached")
10. }
