Database

Connecting to a database

In order to connect to a database, you need to import the database’s driver first. For example:

  1. import _ "github.com/go-sql-driver/mysql"

GORM has wrapped some drivers, for easier to remember the import path, so you could import the mysql driver with

  1. import _ "github.com/jinzhu/gorm/dialects/mysql"
  2. // import _ "github.com/jinzhu/gorm/dialects/postgres"
  3. // import _ "github.com/jinzhu/gorm/dialects/sqlite"
  4. // import _ "github.com/jinzhu/gorm/dialects/mssql"

MySQL

NOTE: In order to handle time.Time, you need to include parseTime as a parameter. (More supported parameters)

  1. import (
  2. "github.com/jinzhu/gorm"
  3. _ "github.com/jinzhu/gorm/dialects/mysql"
  4. )
  5. func main() {
  6. db, err := gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local")
  7. defer db.Close()
  8. }

PostgreSQL

  1. import (
  2. "github.com/jinzhu/gorm"
  3. _ "github.com/jinzhu/gorm/dialects/postgres"
  4. )
  5. func main() {
  6. db, err := gorm.Open("postgres", "host=myhost user=gorm dbname=gorm sslmode=disable password=mypassword")
  7. defer db.Close()
  8. }

Sqlite3

  1. import (
  2. "github.com/jinzhu/gorm"
  3. _ "github.com/jinzhu/gorm/dialects/sqlite"
  4. )
  5. func main() {
  6. db, err := gorm.Open("sqlite3", "/tmp/gorm.db")
  7. defer db.Close()
  8. }

SQL Server

Get started with SQL Server, it can running on your Mac, Linux with Docker

  1. import (
  2. "github.com/jinzhu/gorm"
  3. _ "github.com/jinzhu/gorm/dialects/mssql"
  4. )
  5. func main() {
  6. db, err = gorm.Open("mssql", "sqlserver://username:password@localhost:1433?database=dbname")
  7. defer db.Close()
  8. }

Write Dialect for unsupported databases

GORM officially supports the above databases, but you could write a dialect for unsupported databases.

To write your own dialect, refer to: https://github.com/jinzhu/gorm/blob/master/dialect.go

Migration

Auto Migration

Automatically migrate your schema, to keep your schema update to date.

WARNING: AutoMigrate will ONLY create tables, missing columns and missing indexes, and WON’T change existing column’s type or delete unused columns to protect your data.

  1. db.AutoMigrate(&User{})
  2. db.AutoMigrate(&User{}, &Product{}, &Order{})
  3. // Add table suffix when create tables
  4. db.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(&User{})

Has Table

  1. // Check model `User`'s table exists or not
  2. db.HasTable(&User{})
  3. // Check table `users` exists or not
  4. db.HasTable("users")

Create Table

  1. // Create table for model `User`
  2. db.CreateTable(&User{})
  3. // will append "ENGINE=InnoDB" to the SQL statement when creating table `users`
  4. db.Set("gorm:table_options", "ENGINE=InnoDB").CreateTable(&User{})

Drop table

  1. // Drop model `User`'s table
  2. db.DropTable(&User{})
  3. // Drop table `users`
  4. db.DropTable("users")
  5. // Drop model's `User`'s table and table `products`
  6. db.DropTableIfExists(&User{}, "products")

ModifyColumn

Modify column’s type to given value

  1. // change column description's data type to `text` for model `User`
  2. db.Model(&User{}).ModifyColumn("description", "text")

DropColumn

  1. // Drop column description from model `User`
  2. db.Model(&User{}).DropColumn("description")

Add Foreign Key

  1. // Add foreign key
  2. // 1st param : foreignkey field
  3. // 2nd param : destination table(id)
  4. // 3rd param : ONDELETE
  5. // 4th param : ONUPDATE
  6. db.Model(&User{}).AddForeignKey("city_id", "cities(id)", "RESTRICT", "RESTRICT")

Indexes

  1. // Add index for columns `name` with given name `idx_user_name`
  2. db.Model(&User{}).AddIndex("idx_user_name", "name")
  3. // Add index for columns `name`, `age` with given name `idx_user_name_age`
  4. db.Model(&User{}).AddIndex("idx_user_name_age", "name", "age")
  5. // Add unique index
  6. db.Model(&User{}).AddUniqueIndex("idx_user_name", "name")
  7. // Add unique index for multiple columns
  8. db.Model(&User{}).AddUniqueIndex("idx_user_name_age", "name", "age")
  9. // Remove index
  10. db.Model(&User{}).RemoveIndex("idx_user_name")