GORM

website·Indexed 38 days ago

https://gorm.io/docs

A Go ORM library featuring a core framework and specialized tools like GORM GEN and a CLI for type-safe DAO generation, automated schema migration, and raw SQL to Go interface conversion.

Tokens
71.3K
Snippets
454
Records
481
Agent score
73%

What's inside GORM

  1. Overview of GORM CLI

    GORM CLI is a code generation tool that reads interfaces and structs in a Go project to produce type-safe query methods and model operation helpers. It converts raw SQL comments into typed methods and generates field helpers for predicates, updates, and associations. The output is plain Go code compatible with gorm.io/gorm, ensuring that if the code compiles, it is likely to work correctly.
  2. Overview of GORM Sharding Plugin

    The GORM sharding plugin uses a SQL parser and replace mechanism to split large tables into smaller sharded tables, redirecting queries to the appropriate shard to provide high-performance database access. It supports multiple databases (PostgreSQL, MySQL) and includes an integrated primary key generator (e.g., Snowflake, PostgreSQL Sequence, Custom).
  3. Overview of GORM CLI

    GORM CLI is a code generation tool that reads Go interfaces and structs to produce type-safe query methods and model helpers. It converts raw SQL comments into typed methods and generates helpers for predicates, updates, and associations. The output is plain Go code compatible with gorm.io/gorm, ensuring that if the code compiles, the queries are structurally valid.
  4. Overview of GORM GEN

    GORM GEN is a code generation tool that provides a friendly and safer way to use GORM. It enables 100% type-safe DAO APIs (eliminating the need for interface{}), generates idiomatic and reusable APIs from dynamic raw SQL, and follows GORM conventions for Database-to-Struct mapping. It supports all features, plugins, and DBMS supported by GORM.
  5. Overview of GORM GEN

    GORM GEN is a code generation tool that provides a friendly and safer way to use GORM. It generates a 100% type-safe DAO API, eliminating the need for interface{}. It follows GORM conventions for Database-to-Struct mapping and supports all features, plugins, and DBMS supported by GORM.
  6. GORM Feature Overview

    GORM is a full-featured ORM for Golang providing the following capabilities:

    • Associations: Has One, Has Many, Belongs To, Many To Many, Polymorphism, and Single-table inheritance.
    • Hooks: Before/After Create, Save, Update, Delete, and Find.
    • Loading: Eager loading via Preload and Joins.
    • Transactions: Supports Nested Transactions, Save Points, and RollbackTo.
    • Execution Modes: Context support, Prepared Statement Mode, and DryRun Mode.
    • Batch Operations: Batch Insert, FindInBatches, and CRUD using Maps or SQL Expressions.
    • Schema & Querying: SQL Builder, Upsert, Locking, Optimizer/Index/Comment Hints, Named Arguments, SubQueries, Composite Primary Keys, and Auto Migrations.
  7. GORM Feature Overview

    GORM is a developer-friendly, full-featured ORM providing the following capabilities:

    • Associations: Supports has one, has many, belongs to, many to many, polymorphism, and single-table inheritance.
    • Hooks: Provides before/after hooks for create, save, update, delete, and find operations.
    • Loading & Querying: Eager loading via Preload and Joins; SQL Builder, Upsert, Locking, Optimizer/Index/Comment Hints, Named Arguments, and SubQueries.
    • Transaction Management: Supports Transactions, Nested Transactions, Save Points, and RollbackTo Saved Point.
    • Execution Modes: Context support, Prepared Statement Mode, and DryRun Mode.
    • Data Operations: Batch Insert, FindInBatches, Find/Create with Map, and CRUD using SQL Expr and Context Valuer.
    • Schema & Database: Composite Primary Keys, Indexes, Constraints, and Auto Migrations.
    • Extensibility: Includes a Logger and a flexible plugin API for features like Database Resolver (multiple databases, read/write splitting) and Prometheus integration.
  8. Generate Query APIs and Field Helpers using gorm gen

    gorm gen is a CLI tool that produces two types of code in the same package:

    1. Query API Generator: Converts interfaces annotated with SQL template comments into plain Go implementations. It handles parameter binding and ensures context.Context is present. It supports default generics or the --typed=false flag.
    2. Field Helper Generator: Scans model structs to create predicate builders (e.g., .Eq()), update helpers (Set, Incr), and association helpers (Create, Unlink, Delete).
    gorm gen -i ./internal/models -o ./internal/generated
  9. GORM Feature Overview

    GORM is a full-featured ORM for Golang providing the following capabilities:

    • Associations: Has One, Has Many, Belongs To, Many To Many, Polymorphism, and Single-table inheritance.
    • Hooks: Before/After Create, Save, Update, Delete, and Find.
    • Loading: Eager loading via Preload and Joins.
    • Transactions: Support for Nested Transactions, Save Points, and RollbackTo.
    • Execution Modes: Context support, Prepared Statement Mode, and DryRun Mode.
    • Batch Operations: Batch Insert, FindInBatches, and CRUD using Maps or SQL Expressions.
    • Schema Management: Auto Migrations, Composite Primary Keys, Indexes, and Constraints.
    • Advanced SQL: SQL Builder, Upsert, Locking, Optimizer/Index/Comment Hints, Named Arguments, and SubQueries.
    • Extensibility: Plugin API for features like Database Resolver (read/write splitting) and Prometheus integration.
  10. Apply Index hints in GORM Gen

    Index hints can be used to force the database to use specific indexes when the query planner is not choosing the optimal one. This is achieved using hints.UseIndex or hints.ForceIndex from the gorm.io/hints package.
    import "gorm.io/hints"
    
    u := query.Use(db).User
    
    // Use a specific index
    users, err := u.WithContext(ctx).Clauses(hints.UseIndex("idx_user_name")).Find()
    // SQL: SELECT * FROM `users` USE INDEX (`idx_user_name`)
    
    // Force specific indexes for join
    users, err := u.WithContext(ctx).Clauses(hints.ForceIndex("idx_user_name", "idx_user_id").ForJoin()).Find()
    // SQL: SELECT * FROM `users` FORCE INDEX FOR JOIN (`idx_user_name`,`idx_user_id`)
  11. Inject custom methods into generated structs

    You can use gen.WithMethod to add custom logic or helper methods to the generated structs. You can pass a specific method from a template struct or the entire template struct to copy all its methods.
    type CommonMethod struct {
        ID   int32
        Name *string
    }
    
    func (m *CommonMethod) IsEmpty() bool {
        if m == nil { return true }
        return m.ID == 0
    }
    
    func (m *CommonMethod) GetName() string {
        if m == nil || m.Name == nil { return "" }
        return *m.Name
    }
    
    // Add only the IsEmpty method to the generated `People` struct
    g.GenerateModel("people", gen.WithMethod(CommonMethod{}.IsEmpty))
    
    // Add all methods defined on `CommonMethod` to the generated `User` struct
    g.GenerateModel("user", gen.WithMethod(CommonMethod{}))
  12. Connect GORM to MySQL

    To connect GORM to a MySQL database, use the mysql.Open function with a Data Source Name (DSN).

    Important DSN Parameters:

    • parseTime=True: Required to handle time.Time correctly.
    • charset=utf8mb4: Required for full UTF-8 encoding support (instead of charset=utf8).
    import (
      "gorm.io/driver/mysql"
      "gorm.io/gorm"
    )
    
    func main() {
      // DSN format: user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local
      dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
      db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
    }