Advanced Usage

Error Handling

After perform any operations, if there are any error happened, GORM will set it to *DB‘s Error field

  1. if err := db.Where("name = ?", "jinzhu").First(&user).Error; err != nil {
  2. // error handling...
  3. }
  4. // If there are more than one error happened, get all of them with `GetErrors`, it returns `[]error`
  5. db.First(&user).Limit(10).Find(&users).GetErrors()
  6. // Check if returns RecordNotFound error
  7. db.Where("name = ?", "hello world").First(&user).RecordNotFound()
  8. if db.Model(&user).Related(&credit_card).RecordNotFound() {
  9. // no credit card found handling
  10. }

Transactions

To perform a set of operations within a transaction, the general flow is as below.

  1. // begin a transaction
  2. tx := db.Begin()
  3. // do some database operations in the transaction (use 'tx' from this point, not 'db')
  4. tx.Create(...)
  5. // ...
  6. // rollback the transaction in case of error
  7. tx.Rollback()
  8. // Or commit the transaction
  9. tx.Commit()

A Specific Example

  1. func CreateAnimals(db *gorm.DB) err {
  2. tx := db.Begin()
  3. // Note the use of tx as the database handle once you are within a transaction
  4. if err := tx.Create(&Animal{Name: "Giraffe"}).Error; err != nil {
  5. tx.Rollback()
  6. return err
  7. }
  8. if err := tx.Create(&Animal{Name: "Lion"}).Error; err != nil {
  9. tx.Rollback()
  10. return err
  11. }
  12. tx.Commit()
  13. return nil
  14. }

SQL Builder

Run Raw SQL

Run Raw SQL

  1. db.Exec("DROP TABLE users;")
  2. db.Exec("UPDATE orders SET shipped_at=? WHERE id IN (?)", time.Now(), []int64{11,22,33})
  3. // Scan
  4. type Result struct {
  5. Name string
  6. Age int
  7. }
  8. var result Result
  9. db.Raw("SELECT name, age FROM users WHERE name = ?", 3).Scan(&result)

sql.Row & sql.Rows

Get query result as *sql.Row or *sql.Rows

  1. row := db.Table("users").Where("name = ?", "jinzhu").Select("name, age").Row() // (*sql.Row)
  2. row.Scan(&name, &age)
  3. rows, err := db.Model(&User{}).Where("name = ?", "jinzhu").Select("name, age, email").Rows() // (*sql.Rows, error)
  4. defer rows.Close()
  5. for rows.Next() {
  6. ...
  7. rows.Scan(&name, &age, &email)
  8. ...
  9. }
  10. // Raw SQL
  11. rows, err := db.Raw("select name, age, email from users where name = ?", "jinzhu").Rows() // (*sql.Rows, error)
  12. defer rows.Close()
  13. for rows.Next() {
  14. ...
  15. rows.Scan(&name, &age, &email)
  16. ...
  17. }

Scan sql.Rows In Iteration

  1. rows, err := db.Model(&User{}).Where("name = ?", "jinzhu").Select("name, age, email").Rows() // (*sql.Rows, error)
  2. defer rows.Close()
  3. for rows.Next() {
  4. var user User
  5. db.ScanRows(rows, &user)
  6. // do something
  7. }

Generic database interface sql.DB

Get generic database interface *sql.DB from *gorm.DB connection

  1. // Get generic database object `*sql.DB` to use its functions
  2. db.DB()
  3. // Ping
  4. db.DB().Ping()

Connection Pool

  1. db.DB().SetMaxIdleConns(10)
  2. db.DB().SetMaxOpenConns(100)

Composite Primary Key

Set multiple fields as primary key to enable composite primary key

  1. type Product struct {
  2. ID string `gorm:"primary_key"`
  3. LanguageCode string `gorm:"primary_key"`
  4. }

Logger

Gorm has built-in logger support, by default, it will print happened errors

  1. // Enable Logger, show detailed log
  2. db.LogMode(true)
  3. // Disable Logger, don't show any log
  4. db.LogMode(false)
  5. // Debug a single operation, show detailed log for this operation
  6. db.Debug().Where("name = ?", "jinzhu").First(&User{})

Customize Logger

Refer GORM’s default logger for how to customize it https://github.com/jinzhu/gorm/blob/master/logger.go

  1. db.SetLogger(gorm.Logger{revel.TRACE})
  2. db.SetLogger(log.New(os.Stdout, "\r\n", 0))