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 driverDrivers and dialects - 图1open 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. )
  6. sqldb, err := sql.Open("mysql", "root:pass@/test")
  7. if err != nil {
  8. panic(err)
  9. }
  10. 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-mssqldbDrivers and dialects - 图2open 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. )
  6. sqldb, err := sql.Open("sqlserver", "sqlserver://sa:passWORD1@localhost:1433?database=test")
  7. if err != nil {
  8. panic(err)
  9. }
  10. db := bun.NewDB(sqldb, mssqldialect.New())

SQLite

To connect to a SQLite database, use sqliteshimDrivers and dialects - 图3open in new window driver which automatically imports modernc.org/sqliteDrivers and dialects - 图4open in new window or mattn/go-sqlite3Drivers and dialects - 图5open 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. )
  6. sqldb, err := sql.Open(sqliteshim.ShimName, "file::memory:?cache=shared")
  7. if err != nil {
  8. panic(err)
  9. }
  10. 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 featureDrivers and dialects - 图6open in new window package that allows you to discover features supported by your DBMS:

  1. import "github.com/uptrace/bun/dialect/feature"
  2. if db.HasFeature(feature.InsertOnConflict) {
  3. // DBMS supports `ON CONFLICT DO UPDATE` (PostgreSQL, SQLite)
  4. }
  5. if db.HasFeature(feature.InsertOnDuplicateKey) {
  6. // DBMS supports `ON DUPLICATE KEY UPDATE` (MySQL, MariaDB)
  7. }

You can also directly check the database dialect name:

  1. import "github.com/uptrace/bun/dialect"
  2. switch db.Dialect().Name() {
  3. case dialect.SQLite:
  4. case dialect.PG:
  5. case dialect.MySQL:
  6. case dialect.MSSQL:
  7. default:
  8. panic("not reached")
  9. }