The fantastic ORM library for Golang aims to be developer friendly.

Overview

  • Full-Featured ORM
  • Associations (Has One, Has Many, Belongs To, Many To Many, Polymorphism, Single-table inheritance)
  • Hooks (Before/After Create/Save/Update/Delete/Find)
  • Eager loading with Preload, Joins
  • Transactions, Nested Transactions, Save Point, RollbackTo to Saved Point
  • Context, Prepared Statement Mode, DryRun Mode
  • Batch Insert, FindInBatches, Find/Create with Map, CRUD with SQL Expr and Context Valuer
  • SQL Builder, Upsert, Locking, Optimizer/Index/Comment Hints, Named Argument, SubQuery
  • Composite Primary Key, Indexes, Constraints
  • Auto Migrations
  • Logger
  • Extendable, flexible plugin API: Database Resolver (Multiple Databases, Read/Write Splitting) / Prometheus…
  • Every feature comes with tests
  • Developer Friendly

Install

1. go get -u gorm.io/gorm
2. go get -u gorm.io/driver/sqlite

Quick Start

1. package main

3. import (
4. "gorm.io/gorm"
5. "gorm.io/driver/sqlite"
6. )

8. type Product struct {
9. gorm.Model
10. Code  string
11. Price uint
12. }

14. func main() {
15. db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
16. if err != nil {
17. panic("failed to connect database")
18. }

20. // Migrate the schema
21. db.AutoMigrate(&Product{})

23. // Create
24. db.Create(&Product{Code: "D42", Price: 100})

26. // Read
27. var product Product
28. db.First(&product, 1) // find product with integer primary key
29. db.First(&product, "code = ?", "D42") // find product with code D42

31. // Update - update product's price to 200
32. db.Model(&product).Update("Price", 200)
33. // Update - update multiple fields
34. db.Model(&product).Updates(Product{Price: 200, Code: "F42"}) // non-zero fields
35. db.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"})

37. // Delete - delete product
38. db.Delete(&product, 1)
39. }