GORM officially supports the databases MySQL, PostgreSQL, SQLite, SQL Server, and TiDB

MySQL

  1. import (
  2. "gorm.io/driver/mysql"
  3. "gorm.io/gorm"
  4. )
  5. func main() {
  6. // refer https://github.com/go-sql-driver/mysql#dsn-data-source-name for details
  7. dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
  8. db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
  9. }

NOTE:
To handle time.Time correctly, you need to include parseTime as a parameter. (more parameters)
To fully support UTF-8 encoding, you need to change charset=utf8 to charset=utf8mb4. See this article for a detailed explanation

MySQL Driver provides a few advanced configurations which can be used during initialization, for example:

  1. db, err := gorm.Open(mysql.New(mysql.Config{
  2. DSN: "gorm:gorm@tcp(127.0.0.1:3306)/gorm?charset=utf8&parseTime=True&loc=Local", // data source name
  3. DefaultStringSize: 256, // default size for string fields
  4. DisableDatetimePrecision: true, // disable datetime precision, which not supported before MySQL 5.6
  5. DontSupportRenameIndex: true, // drop & create when rename index, rename index not supported before MySQL 5.7, MariaDB
  6. DontSupportRenameColumn: true, // `change` when rename column, rename column not supported before MySQL 8, MariaDB
  7. SkipInitializeWithVersion: false, // auto configure based on currently MySQL version
  8. }), &gorm.Config{})

Customize Driver

GORM allows to customize the MySQL driver with the DriverName option, for example:

  1. import (
  2. _ "example.com/my_mysql_driver"
  3. "gorm.io/driver/mysql"
  4. "gorm.io/gorm"
  5. )
  6. db, err := gorm.Open(mysql.New(mysql.Config{
  7. DriverName: "my_mysql_driver",
  8. DSN: "gorm:gorm@tcp(localhost:9910)/gorm?charset=utf8&parseTime=True&loc=Local", // data source name, refer https://github.com/go-sql-driver/mysql#dsn-data-source-name
  9. }), &gorm.Config{})

Existing database connection

GORM allows to initialize *gorm.DB with an existing database connection

  1. import (
  2. "database/sql"
  3. "gorm.io/driver/mysql"
  4. "gorm.io/gorm"
  5. )
  6. sqlDB, err := sql.Open("mysql", "mydb_dsn")
  7. gormDB, err := gorm.Open(mysql.New(mysql.Config{
  8. Conn: sqlDB,
  9. }), &gorm.Config{})

PostgreSQL

  1. import (
  2. "gorm.io/driver/postgres"
  3. "gorm.io/gorm"
  4. )
  5. dsn := "host=localhost user=gorm password=gorm dbname=gorm port=9920 sslmode=disable TimeZone=Asia/Shanghai"
  6. db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})

We are using pgx as postgres’s database/sql driver, it enables prepared statement cache by default, to disable it:

  1. // https://github.com/go-gorm/postgres
  2. db, err := gorm.Open(postgres.New(postgres.Config{
  3. DSN: "user=gorm password=gorm dbname=gorm port=9920 sslmode=disable TimeZone=Asia/Shanghai",
  4. PreferSimpleProtocol: true, // disables implicit prepared statement usage
  5. }), &gorm.Config{})

Customize Driver

GORM allows to customize the PostgreSQL driver with the DriverName option, for example:

  1. import (
  2. _ "github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/dialers/postgres"
  3. "gorm.io/gorm"
  4. )
  5. db, err := gorm.Open(postgres.New(postgres.Config{
  6. DriverName: "cloudsqlpostgres",
  7. DSN: "host=project:region:instance user=postgres dbname=postgres password=password sslmode=disable",
  8. })

Existing database connection

GORM allows to initialize *gorm.DB with an existing database connection

  1. import (
  2. "database/sql"
  3. "gorm.io/driver/postgres"
  4. "gorm.io/gorm"
  5. )
  6. sqlDB, err := sql.Open("pgx", "mydb_dsn")
  7. gormDB, err := gorm.Open(postgres.New(postgres.Config{
  8. Conn: sqlDB,
  9. }), &gorm.Config{})

SQLite

  1. import (
  2. "gorm.io/driver/sqlite" // Sqlite driver based on CGO
  3. // "github.com/glebarez/sqlite" // Pure go SQLite driver, checkout https://github.com/glebarez/sqlite for details
  4. "gorm.io/gorm"
  5. )
  6. // github.com/mattn/go-sqlite3
  7. db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{})

NOTE: You can also use file::memory:?cache=shared instead of a path to a file. This will tell SQLite to use a temporary database in system memory. (See SQLite docs for this)

SQL Server

  1. import (
  2. "gorm.io/driver/sqlserver"
  3. "gorm.io/gorm"
  4. )
  5. // github.com/denisenkom/go-mssqldb
  6. dsn := "sqlserver://gorm:LoremIpsum86@localhost:9930?database=gorm"
  7. db, err := gorm.Open(sqlserver.Open(dsn), &gorm.Config{})

TiDB

TiDB is compatible with MySQL protocol. You can follow the MySQL part to create a connection to TiDB.

There are some points noteworthy for TiDB:

  • You can use gorm:"primaryKey;default:auto_random()" tag to use AUTO_RANDOM feature for TiDB.
  • TiDB supported SAVEPOINT from v6.2.0, please notice the version of TiDB when you use this feature.
  • TiDB supported FOREIGN KEY from v6.6.0, please notice the version of TiDB when you use this feature.
  1. import (
  2. "fmt"
  3. "gorm.io/driver/mysql"
  4. "gorm.io/gorm"
  5. )
  6. type Product struct {
  7. ID uint `gorm:"primaryKey;default:auto_random()"`
  8. Code string
  9. Price uint
  10. }
  11. func main() {
  12. db, err := gorm.Open(mysql.Open("root:@tcp(127.0.0.1:4000)/test"), &gorm.Config{})
  13. if err != nil {
  14. panic("failed to connect database")
  15. }
  16. db.AutoMigrate(&Product{})
  17. insertProduct := &Product{Code: "D42", Price: 100}
  18. db.Create(insertProduct)
  19. fmt.Printf("insert ID: %d, Code: %s, Prict: %d\n",
  20. insertProduct.ID, insertProduct.Code, insertProduct.Price)
  21. readProduct := &Product{}
  22. db.First(&readProduct, "code = ?", "D42") // find product with code D42
  23. fmt.Printf("read ID: %d, Code: %s, Prict: %d\n",
  24. readProduct.ID, readProduct.Code, readProduct.Price)
  25. }

Clickhouse

https://github.com/go-gorm/clickhouse

  1. import (
  2. "gorm.io/driver/clickhouse"
  3. "gorm.io/gorm"
  4. )
  5. func main() {
  6. dsn := "tcp://localhost:9000?database=gorm&username=gorm&password=gorm&read_timeout=10&write_timeout=20"
  7. db, err := gorm.Open(clickhouse.Open(dsn), &gorm.Config{})
  8. // Auto Migrate
  9. db.AutoMigrate(&User{})
  10. // Set table options
  11. db.Set("gorm:table_options", "ENGINE=Distributed(cluster, default, hits)").AutoMigrate(&User{})
  12. // Insert
  13. db.Create(&user)
  14. // Select
  15. db.Find(&user, "id = ?", 10)
  16. // Batch Insert
  17. var users = []User{user1, user2, user3}
  18. db.Create(&users)
  19. // ...
  20. }

Connection Pool

GORM using database/sql to maintain connection pool

  1. sqlDB, err := db.DB()
  2. // SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
  3. sqlDB.SetMaxIdleConns(10)
  4. // SetMaxOpenConns sets the maximum number of open connections to the database.
  5. sqlDB.SetMaxOpenConns(100)
  6. // SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
  7. sqlDB.SetConnMaxLifetime(time.Hour)

Refer Generic Interface for details

Unsupported Databases

Some databases may be compatible with the mysql or postgres dialect, in which case you could just use the dialect for those databases.

For others, you are encouraged to make a driver, pull request welcome!