MCPcopy Index your code
hub / github.com/go-gorm/gen

github.com/go-gorm/gen @v0.3.28 sqlite

repository ↗ · DeepWiki ↗ · release v0.3.28 ↗
1,304 symbols 3,445 edges 101 files 653 documented · 50% 8 cross-repo links
README

GORM Gen

Friendly & Safer GORM powered by Code Generation.

Release Go Report Card MIT license OpenIssue ClosedIssue TODOs Go.Dev reference

Overview

  • Generate idiomatic, reusable DAO APIs from database schema and/or interface-based SQL templates
  • Type-safe query DSL (fields, conditions, assignments) with strong static typing (including generics mode)
  • Database-to-struct follows GORM conventions (tags, nullable/default/unsigned/index/type, etc.)
  • Built on top of GORM: use the same plugins, dialectors, and ecosystem you already have

Documentation

  • Gen Guides (official site): https://gorm.io/gen/index.html
  • GORM Guides: https://gorm.io/docs

Quick Start

Install as a library:

go get gorm.io/gen@latest

1) Generate code

Create a generator entry (recommended: cmd/gen/main.go):

package main

import (
    "gorm.io/driver/mysql"
    "gorm.io/gen"
    "gorm.io/gorm"
)

func main() {
    db, err := gorm.Open(mysql.Open("dsn"), &gorm.Config{})
    if err != nil {
        panic(err)
    }

    g := gen.NewGenerator(gen.Config{
        OutPath: "internal/dal/query",
        Mode:    gen.WithDefaultQuery | gen.WithQueryInterface, // enable query.SetDefault(db)
    })

    g.UseDB(db)
    g.ApplyBasic(g.GenerateAllTable()...)
    g.Execute()
}

Run generation:

go run ./cmd/gen

2) Use generated code

If you enabled WithDefaultQuery, initialize once at startup:

package main

import (
    "context"

    "gorm.io/driver/mysql"
    "gorm.io/gorm"

    "your/module/internal/dal/query"
)

func main() {
    db, err := gorm.Open(mysql.Open("dsn"), &gorm.Config{})
    if err != nil {
        panic(err)
    }

    query.SetDefault(db)

    u := query.User
    _, _ = u.WithContext(context.Background()).
        Where(u.Age.Gt(18)).
        Find()
}

query.SetDefault(db) only needs to run once (e.g. during service startup). After that, use query.<Table> directly.

If you don’t want a global default, skip WithDefaultQuery and use:

q := query.Use(db)
_, _ = q.User.WithContext(ctx).Where(q.User.Age.Gt(18)).Find()

More runnable examples: examples

Common Setups

Gen has one generator entry point (gen.NewGenerator(gen.Config{...})). The main knobs you typically use are:

  • What to generate: DB schema → models/query; plus optional interface-SQL methods
  • How the query API looks: Config.Mode flags (WithDefaultQuery, WithoutContext, WithQueryInterface, WithGeneric)

Setup A: DB schema → model + query (recommended baseline)

g := gen.NewGenerator(gen.Config{
    OutPath: "internal/dal/query",
    Mode:    gen.WithDefaultQuery | gen.WithQueryInterface,

    FieldNullable:     true,
    FieldCoverable:    true,
    FieldWithIndexTag: true,
})
g.UseDB(db)
g.ApplyBasic(g.GenerateAllTable()...)
g.Execute()

Setup B: Interface SQL templates → reusable typed methods

Define an interface with SQL comments/templates:

package dal

import "gorm.io/gen"

type UserMethods interface {
    // FindByID
    //
    // SELECT * FROM users WHERE id=@id
    FindByID(id int) gen.T

    // FindByOptionalName
    //
    // SELECT * FROM users
    // {{where}}
    // {{if name != ""}}
    // name=@name
    // {{end}}
    // {{end}}
    FindByOptionalName(name string) []gen.T
}

Bind the interface to a generated model/table:

g.ApplyInterface(func(m UserMethods) {}, g.GenerateModel("users"))

Template syntax reference exists in the test corpus: method.go.

Setup C: Generics query API

Generics is not a separate “workflow”; it changes the generated query API surface for stronger typing.

g := gen.NewGenerator(gen.Config{
    OutPath: "internal/dal/query",
    Mode:    gen.WithDefaultQuery | gen.WithGeneric,
})

Recommended Project Layout

Keep code generation isolated and reproducible (works well with go:generate and CI).

your-repo/
  internal/
    dal/
      model/        # generated model structs (optional)
      query/        # generated query (+ DIY methods)
  cmd/
    gen/
      main.go       # generator entry (checked in)

CLI Tool

If you prefer a CLI workflow, use GenTool:

Maintainers

@riverchu @iDer @qqxhb @dino-ma

@jinzhu

Contributing

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

License

Released under the MIT License

Extension points exported contracts — how you extend this code

Clause (Interface)
Clause a symbol of clause, it can be sql condition clause, if clause, where clause, set clause and else clause [7 implementers]
internal/generate/clause.go
Condition (Interface)
Condition query condition field.Expr and subquery are expect value [3 implementers]
interface.go
DOOption (Interface)
DOOption gorm option interface [2 implementers]
do_options.go
AssignExpr (Interface)
AssignExpr assign expression [2 implementers]
field/expr.go
Pool (Interface)
Pool goroutine pool [1 implementers]
internal/utils/pools/pool.go
Object (Interface)
Object an object interface [1 implementers]
helper/object.go
TagBuilder (Interface)
(no doc) [3 implementers]
field/tag.go
RelationField (Interface)
RelationField interface for relation field [1 implementers]
field/association.go

Core symbols most depended-on inside this repo

Where
called by 68
interface.go
String
called by 66
internal/generate/clause.go
RawExpr
called by 65
field/expr.go
setE
called by 64
field/expr.go
Select
called by 61
interface.go
appendTmpl
called by 43
internal/generate/section.go
RawExpr
called by 39
field/expr.go
Name
called by 34
helper/object.go

Shape

Method 924
Function 220
Struct 95
Interface 34
TypeAlias 21
FuncType 10

Languages

Go100%

Modules by API surface

generics.go109 symbols
do.go108 symbols
field/expr.go91 symbols
field/association.go57 symbols
interface.go53 symbols
field/export.go49 symbols
examples/dal/query/mytables.gen.go46 symbols
tests/diy_method/method.go45 symbols
generator_test.go42 symbols
generator.go40 symbols
internal/generate/clause.go32 symbols
internal/parser/parser.go29 symbols

Dependencies from manifests, versioned

filippo.io/edwards25519v1.1.0 · 1×
github.com/ClickHouse/ch-gov0.58.2 · 1×
github.com/andybalholm/brotliv1.0.6 · 1×
github.com/go-faster/cityv1.0.1 · 1×
github.com/go-faster/errorsv0.6.1 · 1×
github.com/golang-sql/civilv0.0.0-2022022313231 · 1×
github.com/golang-sql/sqlexpv0.1.0 · 1×
github.com/jackc/pgpassfilev1.0.0 · 1×

Datastores touched

(mysql)Database · 1 repos

For agents

$ claude mcp add gen \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact