Overview

GORM is an open-source Object-Relational Mapping (ORM) library for the Go programming language, providing a framework for developers to interact with relational databases using Go structs and methods rather than direct SQL queries. It aims to offer a balance between ease of use and flexibility, making it suitable for a range of applications from small utilities to large-scale enterprise systems. GORM abstracts away much of the boilerplate associated with database operations, allowing developers to focus on application logic rather than SQL syntax.

The library supports several popular relational database systems, including MySQL, PostgreSQL, SQLite, and SQL Server, through a unified API. This multi-database support enables developers to switch database backends with minimal code changes, enhancing application portability. GORM handles common database tasks such as connection management, transaction handling, and schema migrations, which are crucial for maintaining database integrity and evolving application schemas over time.

GORM is particularly well-suited for Go developers engaged in rapid application development where quick iteration and efficient database interaction are priorities. Its fluent API allows for expressive query construction, including complex joins, subqueries, and aggregations. The ORM also provides features for defining model associations (one-to-one, one-to-many, many-to-many), which automatically manage relationships between different data entities. This simplifies data retrieval and manipulation across related tables.

Beyond basic CRUD operations, GORM includes advanced capabilities such as hooks for executing code before or after database events, a plugin system for extending functionality, and support for soft deletes, which mark records as deleted without physically removing them from the database. This comprehensive feature set contributes to a developer-friendly experience, as noted by its strong community adoption and extensive documentation on the GORM official documentation site. The library's approach aligns with Go's philosophy of simplicity and efficiency, providing a robust tool for data persistence layers in Go applications.

Key features

  • Full-featured ORM: Supports CRUD operations, associations (has one, has many, belongs to, many to many), preloading, transactions, and hooks.
  • Multiple Database Support: Compatible with MySQL, PostgreSQL, SQLite, SQL Server, and other databases via custom drivers.
  • Migrations: Provides tools for automatic and manual database schema migrations, helping to manage database evolution alongside application development.
  • Customizable Logger: Allows integration with custom logging solutions for better debugging and monitoring of database interactions.
  • Extensible Plugin System: Enables developers to extend GORM's functionality by writing custom plugins for specific use cases.
  • Context, Prepared Statement & DryRun Mode: Offers advanced control over queries, including context cancellation, prepared statement usage for performance, and a dry-run mode to inspect generated SQL without execution.
  • Soft Delete: Facilitates marking records as deleted without physically removing them, useful for auditing or recovery purposes.
  • Composite Primary Keys: Supports defining tables with multiple columns forming a primary key.
  • Auto Migrations: Automatically creates and updates database schemas based on Go struct definitions.
  • Database Hooks: Allows execution of custom logic before or after create, update, query, delete operations.

Pricing

GORM is an open-source project released under the MIT License. It is free to use for both personal and commercial projects.

Offering Description Cost As Of Date Source
GORM Library Full-featured Go ORM library for relational databases. Free 2026-05-06 GORM GitHub Repository

Common integrations

  • MySQL: Integrate with MySQL databases using the GORM MySQL driver.
  • PostgreSQL: Connect to PostgreSQL databases with the GORM PostgreSQL driver.
  • SQLite: Utilize SQLite for file-based databases, often used for local development or embedded applications, with the GORM SQLite driver.
  • SQL Server: Support for Microsoft SQL Server databases through the GORM SQL Server driver.
  • Context Package: Integrates with Go's context package for request-scoped values, cancellation, and timeouts, as detailed in the GORM Context documentation.

Alternatives

  • sqlx: A Go library that provides a set of extensions over Go's standard database/sql package, offering improved ergonomics for common database tasks without being a full ORM.
  • bun: A modern Go ORM and SQL builder with a focus on performance and type safety, offering a more declarative API than some other ORMs.
  • ent: An entity framework for Go, generating type-safe and performant API for your database schema using code generation.
  • Pop/Soda: An ORM and migration tool often used with the Buffalo web framework, providing a more opinionated approach to database interactions in Go.
  • go-pg: A PostgreSQL ORM with a focus on PostgreSQL-specific features and a SQL-like API, offering a balance between raw SQL and ORM abstraction.

Getting started

To begin using GORM, you'll first need to install the library and a database driver for your chosen database. This example demonstrates connecting to a SQLite database, defining a simple model, and performing a basic create and query operation. For more detailed instructions on connecting to other databases like MySQL or PostgreSQL, refer to the GORM connecting to the database guide.

package main

import (
	"fmt"
	"log"

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

// Define a simple User model
type User struct {
	ID   uint   `gorm:"primaryKey"`
	Name string
	Email string `gorm:"uniqueIndex"`
}

func main() {
	// Connect to SQLite database
	// gorm.Open returns a *gorm.DB instance and an error
	db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
	if err != nil {
		log.Fatalf("Failed to connect to database: %v", err)
	}

	// AutoMigrate will create/update the table based on the User struct
	err = db.AutoMigrate(&User{})
	if err != nil {
		log.Fatalf("Failed to auto migrate database: %v", err)
	}

	fmt.Println("Database migrated successfully!")

	// Create a new user
	newUser := User{Name: "Alice", Email: "[email protected]"}
	result := db.Create(&newUser)
	if result.Error != nil {
		log.Fatalf("Failed to create user: %v", result.Error)
	}

	fmt.Printf("Created user with ID: %d\n", newUser.ID)

	// Query a user by ID
	var foundUser User
	result = db.First(&foundUser, newUser.ID) // Find user with ID 1
	if result.Error != nil {
		log.Fatalf("Failed to find user: %v", result.Error)
	}

	fmt.Printf("Found user: %s (Email: %s)\n", foundUser.Name, foundUser.Email)

	// Update a user's name
	db.Model(&foundUser).Update("Name", "Alicia")
	fmt.Printf("Updated user %d's name to %s\n", foundUser.ID, foundUser.Name)

	// Delete a user (soft delete if GORM's gorm.DeletedAt field is present)
	// For a hard delete, use db.Unscoped().Delete(&foundUser)
	// db.Delete(&foundUser)
	// fmt.Printf("Deleted user with ID: %d\n", foundUser.ID)
}

This example demonstrates the core steps:

  1. Installation: Although not shown in the code block, you would typically run go get gorm.io/gorm and go get gorm.io/driver/sqlite to install GORM and its SQLite driver.
  2. Connection: Establishing a connection to your database using gorm.Open.
  3. Model Definition: Defining Go structs that represent your database tables. GORM uses tags (like gorm:"primaryKey") for configuration.
  4. Auto Migration: Using db.AutoMigrate to automatically create or update database tables based on your defined structs.
  5. CRUD Operations: Performing common database operations like Create, First (for reading), and Update.

For more advanced features, such as associations, preloading, and custom queries, consult the GORM API reference.