Connecting to a Database

GORMは公式にMySQL、PostgreSQL、SQLite、SQL Server をサポートしています

MySQL

import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
)

func main() {
// 詳細は https://github.com/go-sql-driver/mysql#dsn-data-source-name を参照
dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
}

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 few advanced configurations can be used during initialization, for example:

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

Customize Driver

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

import (
_ "example.com/my_mysql_driver"
"gorm.io/gorm"
)

db, err := gorm.Open(mysql.New(mysql.Config{
DriverName: "my_mysql_driver",
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
}), &gorm.Config{})

Existing database connection

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

import (
"database/sql"
"gorm.io/gorm"
)

sqlDB, err := sql.Open("mysql", "mydb_dsn")
gormDB, err := gorm.Open(mysql.New(mysql.Config{
Conn: sqlDB,
}), &gorm.Config{})

PostgreSQL

import (
"gorm.io/driver/postgres"
"gorm.io/gorm"
)

dsn := "user=gorm password=gorm dbname=gorm port=9920 sslmode=disable TimeZone=Asia/shanghai"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})

Postgresのdatabase/sqlドライバとして pgx を使用しています。これはデフォルトでprepared statement cacheを有効にしています。無効にするには:

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

ドライバーのカスタマイズ

GORMでは、 DriverName オプションを使用してPostgreSQLドライバをカスタマイズできます。例:

import (
_ "github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/dialers/postgres"
"gorm.io/gorm"
)

db, err := gorm.Open(postgres.New(postgres.Config{
DriverName: "cloudsqlpostgres",
DSN: "host=project:region:instance user=postgres dbname=postgres password=password sslmode=disable",
})

既存のデータベース接続

GORMでは、既存のデータベース接続で *gorm.DB を初期化することができます

import (
"database/sql"
"gorm.io/gorm"
)

sqlDB, err := sql.Open("postgres", "mydb_dsn")
gormDB, err := gorm.Open(postgres.New(postgres.Config{
Conn: sqlDB,
}), &gorm.Config{})

SQLite

import (
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)

// github.com/mattn/go-sqlite3
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

import (
"gorm.io/driver/sqlserver"
"gorm.io/gorm"
)

// github.com/denisenkom/go-mssqldb
dsn := "sqlserver://gorm:LoremIpsum86@localhost:9930?database=gorm"
db, err := gorm.Open(sqlserver.Open(dsn), &gorm.Config{})

Connection Pool

GORM using database/sql to maintain connection pool

sqlDB, err := db.DB()

// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
sqlDB.SetMaxIdleConns(10)

// SetMaxOpenConns sets the maximum number of open connections to the database.
sqlDB.SetMaxOpenConns(100)

// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
sqlDB.SetConnMaxLifetime(time.Hour)

Refer Generic Interface for details

サポートされていないデータベース

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!