Convert Figma logo to code with AI

go-gorm logogorm

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

36,742
3,925
36,742
408

Top Related Projects

6,665

Simple and Powerful ORM for Go, support mysql,postgres,tidb,sqlite3,mssql,oracle, Moved to https://gitea.com/xorm/xorm

16,124

general purpose extensions to golang's database/sql

3,535

Data Access Layer (DAL) for PostgreSQL, CockroachDB, MySQL, SQLite and MongoDB with ORM-like features.

Generate a Go ORM tailored to your database schema.

5,665

Golang ORM with focus on PostgreSQL features and performance

Quick Overview

GORM is a popular and feature-rich ORM (Object-Relational Mapping) library for Go. It provides a powerful and developer-friendly interface for interacting with databases, supporting various database systems and offering advanced features like associations, hooks, and migrations.

Pros

  • Easy to use with intuitive API and chainable methods
  • Supports multiple database systems (MySQL, PostgreSQL, SQLite, SQL Server)
  • Provides advanced features like auto migrations, associations, and hooks
  • Actively maintained with a large community and extensive documentation

Cons

  • Can be slower compared to raw SQL queries for complex operations
  • Learning curve for advanced features and best practices
  • May lead to inefficient queries if not used properly
  • Limited support for complex database-specific features

Code Examples

  1. Basic CRUD operations:
// Create
user := User{Name: "John", Age: 18, Birthday: time.Now()}
result := db.Create(&user)

// Read
var user User
db.First(&user, 1) // find user with id 1
db.First(&user, "name = ?", "John") // find user with name John

// Update
db.Model(&user).Update("name", "Jane")

// Delete
db.Delete(&user, 1)
  1. Associations:
type User struct {
  gorm.Model
  Name      string
  CompanyID int
  Company   Company
}

type Company struct {
  ID   int
  Name string
}

// Create user with associated company
db.Create(&User{
  Name: "John",
  Company: Company{Name: "Acme Corp"},
})

// Preload association
var users []User
db.Preload("Company").Find(&users)
  1. Hooks:
func (u *User) BeforeCreate(tx *gorm.DB) (err error) {
  u.UUID = uuid.New()
  if u.Role == "" {
    u.Role = "user"
  }
  return
}

// Hook will be called before creating a user
db.Create(&user)

Getting Started

To start using GORM, first install it:

go get -u gorm.io/gorm
go get -u gorm.io/driver/sqlite # For SQLite

Then, in your Go code:

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

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

  // Auto Migrate
  db.AutoMigrate(&User{})

  // Now you can use 'db' to perform database operations
}

Competitor Comparisons

6,665

Simple and Powerful ORM for Go, support mysql,postgres,tidb,sqlite3,mssql,oracle, Moved to https://gitea.com/xorm/xorm

Pros of xorm

  • More flexible query building with SQL-like syntax
  • Built-in support for database migrations
  • Better performance in some scenarios, especially for large datasets

Cons of xorm

  • Less active community and fewer third-party plugins
  • Documentation is not as comprehensive as GORM's
  • Steeper learning curve for developers new to ORM concepts

Code Comparison

xorm:

engine, _ := xorm.NewEngine("mysql", "root:password@/dbname?charset=utf8")
user := new(User)
has, _ := engine.Where("name = ?", "John").Get(user)

GORM:

db, _ := gorm.Open(mysql.Open("root:password@/dbname?charset=utf8"), &gorm.Config{})
var user User
result := db.Where("name = ?", "John").First(&user)

Both ORMs offer similar functionality, but xorm's syntax is more SQL-like, while GORM's is more method-chaining oriented. xorm requires explicit engine creation, whereas GORM uses a global DB object. GORM's API is generally considered more intuitive for Go developers, but xorm offers more fine-grained control over queries.

16,124

general purpose extensions to golang's database/sql

Pros of sqlx

  • Lightweight and closer to raw SQL, offering more control and flexibility
  • Better performance due to less abstraction and overhead
  • Supports both database-specific and generic interfaces

Cons of sqlx

  • Requires more manual work for complex queries and relationships
  • Less feature-rich compared to GORM (e.g., lacks automatic migrations)
  • Steeper learning curve for developers new to SQL

Code Comparison

GORM example:

db.Where("name = ?", "jinzhu").First(&user)

sqlx example:

db.Get(&user, "SELECT * FROM users WHERE name = $1", "jinzhu")

Key Differences

  • GORM provides an ORM with a higher level of abstraction, while sqlx is a lightweight wrapper around database/sql
  • GORM offers more built-in features like automatic migrations and hooks, whereas sqlx focuses on simplicity and performance
  • sqlx requires more explicit SQL knowledge, while GORM allows for more database-agnostic operations

Both libraries have their strengths and are suitable for different use cases. GORM is ideal for rapid development and complex applications, while sqlx is better for performance-critical systems and developers who prefer working closer to raw SQL.

3,535

Data Access Layer (DAL) for PostgreSQL, CockroachDB, MySQL, SQLite and MongoDB with ORM-like features.

Pros of upper/db

  • More flexible and database-agnostic, supporting multiple database types
  • Simpler API with a more intuitive query builder
  • Better support for raw SQL queries and custom data types

Cons of upper/db

  • Smaller community and fewer resources compared to GORM
  • Less feature-rich, lacking some advanced ORM functionalities
  • Not as actively maintained, with fewer updates and releases

Code Comparison

upper/db:

res := db.Collection("users").Find(db.Cond{"age >": 18})
var users []User
err := res.All(&users)

GORM:

var users []User
result := db.Where("age > ?", 18).Find(&users)

Both libraries offer concise ways to query databases, but upper/db's syntax is more SQL-like, while GORM follows a more method-chaining approach. upper/db's db.Cond allows for more flexible condition building, whereas GORM's syntax is closer to raw SQL with placeholders.

upper/db provides a more database-agnostic approach, making it easier to switch between different database types. However, GORM offers more advanced ORM features and has a larger community, which can be beneficial for complex projects and long-term support.

Generate a Go ORM tailored to your database schema.

Pros of sqlboiler

  • Generates type-safe, database-specific code, reducing runtime errors
  • Offers better performance due to its code generation approach
  • Provides more fine-grained control over SQL queries

Cons of sqlboiler

  • Requires code regeneration when database schema changes
  • Steeper learning curve compared to GORM's simpler API
  • Less flexibility for dynamic queries at runtime

Code Comparison

GORM example:

db.Where("name = ?", "john").First(&user)

sqlboiler example:

users, err := models.Users(
    qm.Where("name = ?", "john"),
).One(ctx, db)

Both GORM and sqlboiler are popular Go ORMs, but they take different approaches. GORM is a runtime ORM that offers a more traditional, ActiveRecord-style API, while sqlboiler is a code generation tool that produces type-safe, database-specific code.

GORM is generally easier to get started with and offers more flexibility for dynamic queries. It's a good choice for rapid development and projects with changing requirements. sqlboiler, on the other hand, provides better performance and type safety at the cost of requiring code regeneration when the database schema changes.

The choice between the two depends on project requirements, team preferences, and the specific use case. GORM might be preferable for smaller projects or those requiring more flexibility, while sqlboiler could be a better fit for larger, more stable projects where performance and type safety are critical.

5,665

Golang ORM with focus on PostgreSQL features and performance

Pros of pg

  • Better performance, especially for complex queries and large datasets
  • Native support for PostgreSQL-specific features like JSONB and array types
  • More lightweight and focused specifically on PostgreSQL

Cons of pg

  • Limited to PostgreSQL, unlike GORM's multi-database support
  • Smaller community and ecosystem compared to GORM
  • Steeper learning curve for developers new to PostgreSQL

Code Comparison

pg:

type User struct {
    ID   int64
    Name string
}

err := db.Model(&user).Where("id = ?", 1).Select()

GORM:

type User struct {
    ID   uint
    Name string
}

result := db.Where("id = ?", 1).First(&user)

Both libraries offer similar query syntax, but pg tends to be more explicit in its method naming (e.g., Select() instead of First()). GORM's API is generally more intuitive for beginners, while pg's API closely mirrors PostgreSQL's native query structure.

pg excels in performance-critical applications and projects heavily reliant on PostgreSQL features. GORM is more versatile and user-friendly, making it suitable for a wider range of projects and developers. The choice between the two often depends on specific project requirements and the development team's expertise.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

GORM

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

go report card test status MIT license Go.Dev reference

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 To Map
  • SQL Builder, Upsert, Locking, Optimizer/Index/Comment Hints, NamedArg, Search/Update/Create with SQL Expr
  • Composite Primary Key
  • Auto Migrations
  • Logger
  • Extendable, flexible plugin API: Database Resolver (Multiple Databases, Read/Write Splitting) / Prometheus…
  • Every feature comes with tests
  • Developer Friendly

Getting Started

Contributing

You can help to deliver a better GORM, check out things you can do

Contributors

Thank you for contributing to the GORM framework!

License

© Jinzhu, 2013~time.Now

Released under the MIT License