gen

package module
v0.3.28 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 4, 2026 License: MIT Imports: 37 Imported by: 1,062

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

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)
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,
})

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

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	FieldModify = func(opt func(Field) Field) model.ModifyFieldOpt {
		return func(f *model.Field) *model.Field {
			return opt(f)
		}
	}

	FieldFilter = func(opt func(Field) Field) model.FilterFieldOpt {
		return func(f *model.Field) *model.Field {
			return opt(f)
		}
	}

	// WithDataTypesNullType configures the types of fields to use their datatypes nullable counterparts.
	/**
	 *
	 * @param {boolean} all - If true, all basic types of fields will be replaced with their `datatypes.Null[T]` types.
	 *                        If false, only fields that are allowed to be null will be replaced with `datatypes.Null[T]` types.
	 *
	 * Examples:
	 *
	 * When `all` is true:
	 * - `int64` will be replaced with `datatypes.NullInt64`
	 * - `string` will be replaced with `datatypes.NullString`
	 *
	 * When `all` is false:
	 * - Only fields that can be null (e.g., `*string` or `*int`) will be replaced with `datatypes.Null[T]` types.
	 *
	 * Note:
	 * Ensure that proper error handling is implemented when converting
	 * fields to their `datatypes.Null[T]` types to avoid runtime issues.
	 */
	WithDataTypesNullType = func(all bool) model.ModifyFieldOpt {
		return func(f *model.Field) *model.Field {
			ft := f.Type
			nullable := false
			if strings.HasPrefix(ft, "*") {
				nullable = true
				ft = strings.TrimLeft(ft, "*")
			}
			if !all && !nullable {
				return f
			}
			switch ft {
			case "time.Time", "string", "int", "int8", "int16",
				"int32", "int64", "uint", "uint8", "uint16", "uint32",
				"uint64", "float64", "float32", "byte", "bool":
				ft = fmt.Sprintf("datatypes.Null[%s]", ft)
			default:
				return f
			}
			f.CustomGenType = f.GenType()
			f.Type = ft
			return f
		}
	}

	// FieldNew add new field (any type your want)
	FieldNew = func(fieldName, fieldType string, fieldTag field.Tag) model.CreateFieldOpt {
		return func(*model.Field) *model.Field {
			return &model.Field{
				Name: fieldName,
				Type: fieldType,
				Tag:  fieldTag,
			}
		}
	}
	// FieldIgnore ignore some columns by name
	FieldIgnore = func(columnNames ...string) model.FilterFieldOpt {
		return func(m *model.Field) *model.Field {
			for _, name := range columnNames {
				if m.ColumnName == name {
					return nil
				}
			}
			return m
		}
	}
	// FieldIgnoreReg ignore some columns by RegExp
	FieldIgnoreReg = func(columnNameRegs ...string) model.FilterFieldOpt {
		regs := make([]regexp.Regexp, len(columnNameRegs))
		for i, reg := range columnNameRegs {
			regs[i] = *regexp.MustCompile(reg)
		}
		return func(m *model.Field) *model.Field {
			for _, reg := range regs {
				if reg.MatchString(m.ColumnName) {
					return nil
				}
			}
			return m
		}
	}
	// FieldRename specify field name in generated struct
	FieldRename = func(columnName string, newName string) model.ModifyFieldOpt {
		return func(m *model.Field) *model.Field {
			if m.ColumnName == columnName {
				m.Name = newName
			}
			return m
		}
	}
	// FieldComment specify field comment in generated struct
	FieldComment = func(columnName string, comment string) model.ModifyFieldOpt {
		return func(m *model.Field) *model.Field {
			if m.ColumnName == columnName {
				m.ColumnComment = comment
				m.MultilineComment = strings.Contains(comment, "\n")
			}
			return m
		}
	}
	// FieldType specify field type in generated struct
	FieldType = func(columnName string, newType string) model.ModifyFieldOpt {
		return func(m *model.Field) *model.Field {
			if m.ColumnName == columnName {
				m.Type = newType
			}
			return m
		}
	}
	// FieldTypeReg specify field type in generated struct by RegExp
	FieldTypeReg = func(columnNameReg string, newType string) model.ModifyFieldOpt {
		reg := regexp.MustCompile(columnNameReg)
		return func(m *model.Field) *model.Field {
			if reg.MatchString(m.ColumnName) {
				m.Type = newType
			}
			return m
		}
	}
	// FieldGenType specify field gen type in generated dao
	FieldGenType = func(columnName string, newType string) model.ModifyFieldOpt {
		return func(m *model.Field) *model.Field {
			if m.ColumnName == columnName {
				m.CustomGenType = newType
			}
			return m
		}
	}
	// FieldGenTypeReg specify field gen type in generated dao  by RegExp
	FieldGenTypeReg = func(columnNameReg string, newType string) model.ModifyFieldOpt {
		reg := regexp.MustCompile(columnNameReg)
		return func(m *model.Field) *model.Field {
			if reg.MatchString(m.ColumnName) {
				m.CustomGenType = newType
			}
			return m
		}
	}
	// FieldTag specify GORM tag and JSON tag
	FieldTag = func(columnName string, tagFunc func(tag field.Tag) field.Tag) model.ModifyFieldOpt {
		return func(m *model.Field) *model.Field {
			if m.ColumnName == columnName {
				m.Tag = tagFunc(m.Tag)
			}
			return m
		}
	}
	// FieldJSONTag specify JSON tag
	FieldJSONTag = func(columnName string, jsonTag string) model.ModifyFieldOpt {
		return func(m *model.Field) *model.Field {
			if m.ColumnName == columnName {
				m.Tag.Set(field.TagKeyJson, jsonTag)
			}
			return m
		}
	}
	// FieldJSONTagWithNS specify JSON tag with name strategy
	FieldJSONTagWithNS = func(schemaName func(columnName string) (tagContent string)) model.ModifyFieldOpt {
		return func(m *model.Field) *model.Field {
			if schemaName != nil {
				m.Tag.Set(field.TagKeyJson, schemaName(m.ColumnName))

			}
			return m
		}
	}
	// FieldGORMTag specify GORM tag
	FieldGORMTag = func(columnName string, gormTag func(tag field.GormTag) field.GormTag) model.ModifyFieldOpt {
		return func(m *model.Field) *model.Field {
			if m.ColumnName == columnName {
				m.GORMTag = gormTag(m.GORMTag)
			}
			return m
		}
	}
	// FieldGORMTagReg specify GORM tag by RegExp
	FieldGORMTagReg = func(columnNameReg string, gormTag func(tag field.GormTag) field.GormTag) model.ModifyFieldOpt {
		reg := regexp.MustCompile(columnNameReg)
		return func(m *model.Field) *model.Field {
			if reg.MatchString(m.ColumnName) {
				m.GORMTag = gormTag(m.GORMTag)
			}
			return m
		}
	}
	// FieldNewTag add new tag
	FieldNewTag = func(columnName string, newTag field.Tag) model.ModifyFieldOpt {
		return func(m *model.Field) *model.Field {
			if m.ColumnName == columnName {
				for k, v := range newTag {
					m.Tag.Set(k, v)
				}
			}
			return m
		}
	}
	// FieldNewTagWithNS add new tag with name strategy
	FieldNewTagWithNS = func(tagName string, schemaName func(columnName string) string) model.ModifyFieldOpt {
		return func(m *model.Field) *model.Field {
			if schemaName == nil {
				schemaName = func(name string) string { return name }
			}
			m.Tag.Set(tagName, schemaName(m.ColumnName))
			return m
		}
	}
	// FieldTrimPrefix trim column name's prefix
	FieldTrimPrefix = func(prefix string) model.ModifyFieldOpt {
		return func(m *model.Field) *model.Field {
			m.Name = strings.TrimPrefix(m.Name, prefix)
			return m
		}
	}
	// FieldTrimSuffix trim column name's suffix
	FieldTrimSuffix = func(suffix string) model.ModifyFieldOpt {
		return func(m *model.Field) *model.Field {
			m.Name = strings.TrimSuffix(m.Name, suffix)
			return m
		}
	}
	// FieldAddPrefix add prefix to struct's memeber name
	FieldAddPrefix = func(prefix string) model.ModifyFieldOpt {
		return func(m *model.Field) *model.Field {
			m.Name = prefix + m.Name
			return m
		}
	}
	// FieldAddSuffix add suffix to struct's memeber name
	FieldAddSuffix = func(suffix string) model.ModifyFieldOpt {
		return func(m *model.Field) *model.Field {
			m.Name += suffix
			return m
		}
	}
	// FieldRelate relate to table in database
	FieldRelate = func(relationship field.RelationshipType, fieldName string, table *generate.QueryStructMeta, config *field.RelateConfig) model.CreateFieldOpt {
		if config == nil {
			config = &field.RelateConfig{}
		}

		return func(*model.Field) *model.Field {
			return &model.Field{
				Name:    fieldName,
				Type:    config.RelateFieldPrefix(relationship) + table.StructInfo.Type,
				Tag:     config.GetTag(fieldName),
				GORMTag: config.GORMTag,
				Relation: field.NewRelationWithType(
					relationship, fieldName, table.StructInfo.Package+"."+table.StructInfo.Type,
					table.Relations()...),
			}
		}
	}
	// FieldRelateModel relate to exist table model
	FieldRelateModel = func(relationship field.RelationshipType, fieldName string, relModel interface{}, config *field.RelateConfig) model.CreateFieldOpt {
		st := reflect.TypeOf(relModel)
		if st.Kind() == reflect.Ptr {
			st = st.Elem()
		}
		fieldType := st.String()

		if config == nil {
			config = &field.RelateConfig{}
		}

		return func(*model.Field) *model.Field {
			return &model.Field{
				Name:     fieldName,
				Type:     config.RelateFieldPrefix(relationship) + fieldType,
				GORMTag:  config.GORMTag,
				Tag:      config.GetTag(fieldName),
				Relation: field.NewRelationWithModel(relationship, fieldName, fieldType, relModel),
			}
		}
	}

	// WithMethod add custom method for table model
	WithMethod = func(methods ...interface{}) model.AddMethodOpt {
		return func() []interface{} { return methods }
	}
)
View Source
var (
	// Debug use DB in debug mode
	Debug doOptions = func(db *gorm.DB) *gorm.DB { return db.Debug() }
)
View Source
var (
	DefaultMethodTableWithNamer = (&defaultModel{}).TableName
)
View Source
var ErrClauseNotHandled = errors.New("clause not handled")
View Source
var (
	// ErrEmptyCondition empty condition
	ErrEmptyCondition = errors.New("empty condition")
)

Functions

func CheckClause added in v0.1.28

func CheckClause(cond clause.Expression) error

CheckClause check security of Expression

func WriteDiagnosticJSON added in v0.3.28

func WriteDiagnosticJSON(w io.Writer, err error) error

Types

type ClauseChecker added in v0.3.28

type ClauseChecker func(clause.Expression) error

type Columns added in v0.3.9

type Columns []field.Expr

Columns columns array

func (Columns) Eq added in v0.3.9

func (cs Columns) Eq(query SubQuery) field.Expr

Eq ...

func (Columns) Gt added in v0.3.9

func (cs Columns) Gt(query SubQuery) field.Expr

Gt ...

func (Columns) Gte added in v0.3.9

func (cs Columns) Gte(query SubQuery) field.Expr

Gte ...

func (Columns) In added in v0.3.9

func (cs Columns) In(queryOrValue Condition) field.Expr

In accept query or value

func (Columns) Lt added in v0.3.9

func (cs Columns) Lt(query SubQuery) field.Expr

Lt ...

func (Columns) Lte added in v0.3.9

func (cs Columns) Lte(query SubQuery) field.Expr

Lte ...

func (Columns) Neq added in v0.3.9

func (cs Columns) Neq(query SubQuery) field.Expr

Neq ...

func (Columns) NotIn added in v0.3.9

func (cs Columns) NotIn(queryOrValue Condition) field.Expr

NotIn ...

func (Columns) Set added in v0.3.9

func (cs Columns) Set(query SubQuery) field.AssignExpr

Set assign value by subquery

type Condition

type Condition interface {
	BeCond() interface{}
	CondError() error
}

Condition query condition field.Expr and subquery are expect value

func Cond added in v0.0.17

func Cond(exprs ...clause.Expression) []Condition

Cond convert expression array to condition array

func Exists added in v0.3.23

func Exists(subQuery SubQuery) Condition

Exists EXISTS expression SELECT * FROM table WHERE EXISTS (SELECT NAME FROM users WHERE id = 1)

type Config

type Config struct {
	OutPath      string // query code path
	OutFile      string // query code file name, default: gen.go
	ModelPkgPath string // generated model code's package name
	WithUnitTest bool   // generate unit test for query code
	Incremental  bool   // skip writing unchanged generated files (based on manifest hash)
	MergeQuery   bool   // keep previously generated query entries (A+B) when generating subsets

	// generate model global configuration
	FieldNullable       bool // generate pointer when field is nullable
	FieldCoverable      bool // generate pointer when field has default value, to fix problem zero value cannot be assign: https://gorm.io/docs/create.html#Default-Values
	FieldSignable       bool // detect integer field's unsigned type, adjust generated data type
	FieldWithIndexTag   bool // generate with gorm index tag
	FieldWithTypeTag    bool // generate with gorm column type tag
	FieldWithDefaultTag bool

	Mode GenerateMode // generate mode

	UnitTestTemplate string
	// contains filtered or unexported fields
}

Config generator's basic configuration

func (*Config) Revise added in v0.0.16

func (cfg *Config) Revise() (err error)

Revise format path and db

func (*Config) WithDataTypeMap added in v0.1.20

func (cfg *Config) WithDataTypeMap(newMap map[string]func(columnType gorm.ColumnType) (dataType string))

WithDataTypeMap specify data type mapping relationship, only work when syncing table from db

func (*Config) WithDataTypesNullType added in v0.3.27

func (cfg *Config) WithDataTypesNullType(all bool)

WithDataTypesNullType configures the types of fields to use their datatypes nullable counterparts. *

*
* @param {boolean} all - If true, all basic types of fields will be replaced with their `datatypes.Null[T]` types.
*                        If false, only fields that are allowed to be null will be replaced with `datatypes.Null[T]` types.
*
* Examples:
*
* When `all` is true:
* - `int64` will be replaced with `datatypes.NullInt64`
* - `string` will be replaced with `datatypes.NullString`
*
* When `all` is false:
* - Only fields that can be null (e.g., `*string` or `*int`) will be replaced with `datatypes.Null[T]` types.
*
* Note:
* Ensure that proper error handling is implemented when converting
* fields to their `datatypes.Null[T]` types to avoid runtime issues.

func (*Config) WithDbNameOpts

func (cfg *Config) WithDbNameOpts(opts ...model.SchemaNameOpt)

WithDbNameOpts set get database name function

func (*Config) WithFileNameStrategy added in v0.2.27

func (cfg *Config) WithFileNameStrategy(ns func(tableName string) (fileName string))

WithFileNameStrategy specify file name naming strategy, only work when syncing table from db

func (*Config) WithImportPkgPath added in v0.2.31

func (cfg *Config) WithImportPkgPath(paths ...string)

WithImportPkgPath specify import package path

func (*Config) WithJSONTagNameStrategy added in v0.1.26

func (cfg *Config) WithJSONTagNameStrategy(ns func(columnName string) (tagContent string))

WithJSONTagNameStrategy specify json tag naming strategy

func (*Config) WithModelNameStrategy added in v0.2.27

func (cfg *Config) WithModelNameStrategy(ns func(tableName string) (modelName string))

WithModelNameStrategy specify model struct name naming strategy, only work when syncing table from db

func (*Config) WithOpts added in v0.3.18

func (cfg *Config) WithOpts(opts ...ModelOpt)

WithOpts set global model options

func (*Config) WithTableNameStrategy added in v0.2.27

func (cfg *Config) WithTableNameStrategy(ns func(tableName string) (targetTableName string))

WithTableNameStrategy specify table name naming strategy, only work when syncing table from db

type DO

type DO struct {
	*DOConfig
	// contains filtered or unexported fields
}

DO (data object): implement basic query methods the structure embedded with a *gorm.DB, and has a element item "alias" will be used when used as a sub query

func (*DO) AddError added in v0.3.23

func (d *DO) AddError(err error) error

func (*DO) Alias added in v0.2.44

func (d *DO) Alias() string

Alias return alias name

func (DO) As

func (d DO) As(alias string) Dao

As alias cannot be heired, As must used on tail

func (*DO) Assign added in v0.0.21

func (d *DO) Assign(attrs ...field.AssignExpr) Dao

Assign ...

func (*DO) Attrs added in v0.0.21

func (d *DO) Attrs(attrs ...field.AssignExpr) Dao

Attrs ...

func (*DO) BeCond added in v0.0.17

func (d *DO) BeCond() interface{}

BeCond implements Condition

func (*DO) Build

func (d *DO) Build(builder clause.Builder)

Build implement the interface of claues.Expression only call WHERE clause's Build

func (*DO) Clauses added in v0.0.16

func (d *DO) Clauses(conds ...clause.Expression) Dao

Clauses specify Clauses

func (*DO) Columns added in v0.0.11

func (*DO) Columns(cols ...field.Expr) Columns

Columns return columns for Subquery

func (*DO) CondError added in v0.0.17

func (d *DO) CondError() error

CondError implements Condition

func (*DO) Count

func (d *DO) Count() (count int64, err error)

Count ...

func (*DO) Create

func (d *DO) Create(value interface{}) error

Create ...

func (*DO) CreateInBatches

func (d *DO) CreateInBatches(value interface{}, batchSize int) error

CreateInBatches ...

func (*DO) Debug

func (d *DO) Debug() Dao

Debug return a DO with db in debug mode

func (*DO) Delete

func (d *DO) Delete(models ...interface{}) (info ResultInfo, err error)

Delete ...

func (*DO) Distinct

func (d *DO) Distinct(columns ...field.Expr) Dao

Distinct ...

func (*DO) Find

func (d *DO) Find() (results interface{}, err error)

Find ...

func (*DO) FindInBatches

func (d *DO) FindInBatches(dest interface{}, batchSize int, fc func(tx Dao, batch int) error) error

FindInBatches ...

func (*DO) First

func (d *DO) First() (result interface{}, err error)

First ...

func (*DO) FirstOrCreate

func (d *DO) FirstOrCreate() (result interface{}, err error)

FirstOrCreate ...

func (*DO) FirstOrInit

func (d *DO) FirstOrInit() (result interface{}, err error)

FirstOrInit ...

func (*DO) Group

func (d *DO) Group(columns ...field.Expr) Dao

Group ...

func (*DO) Having

func (d *DO) Having(conds ...Condition) Dao

Having ...

func (*DO) Join

func (d *DO) Join(table schema.Tabler, conds ...field.Expr) Dao

Join ...

func (*DO) Joins added in v0.0.24

func (d *DO) Joins(field field.RelationField) Dao

Joins ...

func (*DO) Last

func (d *DO) Last() (result interface{}, err error)

Last ...

func (*DO) LeftJoin

func (d *DO) LeftJoin(table schema.Tabler, conds ...field.Expr) Dao

LeftJoin ...

func (*DO) Limit

func (d *DO) Limit(limit int) Dao

Limit ...

func (*DO) Not

func (d *DO) Not(conds ...Condition) Dao

Not ...

func (*DO) Offset

func (d *DO) Offset(offset int) Dao

Offset ...

func (*DO) Omit

func (d *DO) Omit(columns ...field.Expr) Dao

Omit ...

func (*DO) Or

func (d *DO) Or(conds ...Condition) Dao

Or ...

func (*DO) Order

func (d *DO) Order(columns ...field.Expr) Dao

Order ...

func (*DO) Pluck

func (d *DO) Pluck(column field.Expr, dest interface{}) error

Pluck ...

func (*DO) Preload added in v0.0.24

func (d *DO) Preload(field field.RelationField) Dao

Preload ...

func (*DO) Quote

func (d *DO) Quote(raw string) string

Quote return qutoed data

func (*DO) ReplaceConnPool added in v0.3.18

func (d *DO) ReplaceConnPool(pool gorm.ConnPool)

ReplaceConnPool replace db connection pool

func (*DO) ReplaceDB added in v0.0.19

func (d *DO) ReplaceDB(db *gorm.DB)

ReplaceDB replace db connection

func (DO) Returning added in v0.2.42

func (d DO) Returning(value interface{}, columns ...string) Dao

Returning backfill data

func (*DO) RightJoin

func (d *DO) RightJoin(table schema.Tabler, conds ...field.Expr) Dao

RightJoin ...

func (*DO) Row

func (d *DO) Row() *sql.Row

Row ...

func (*DO) Rows

func (d *DO) Rows() (*sql.Rows, error)

Rows ...

func (*DO) Save

func (d *DO) Save(value interface{}) error

Save ...

func (*DO) Scan

func (d *DO) Scan(dest interface{}) error

Scan ...

func (*DO) ScanRows

func (d *DO) ScanRows(rows *sql.Rows, dest interface{}) error

ScanRows ...

func (*DO) Scopes

func (d *DO) Scopes(funcs ...func(Dao) Dao) Dao

Scopes ...

func (*DO) Select

func (d *DO) Select(columns ...field.Expr) Dao

Select ...

func (*DO) Session added in v0.0.24

func (d *DO) Session(config *gorm.Session) Dao

Session replace db with new session

func (DO) TableName

func (d DO) TableName() string

TableName return table name

func (*DO) Take

func (d *DO) Take() (result interface{}, err error)

Take ...

func (*DO) UnderlyingDB

func (d *DO) UnderlyingDB() *gorm.DB

UnderlyingDB return the underlying database connection

func (*DO) Unscoped

func (d *DO) Unscoped() Dao

Unscoped ...

func (*DO) Update

func (d *DO) Update(column field.Expr, value interface{}) (info ResultInfo, err error)

Update ...

func (*DO) UpdateColumn

func (d *DO) UpdateColumn(column field.Expr, value interface{}) (info ResultInfo, err error)

UpdateColumn ...

func (*DO) UpdateColumnSimple added in v0.0.15

func (d *DO) UpdateColumnSimple(columns ...field.AssignExpr) (info ResultInfo, err error)

UpdateColumnSimple ...

func (*DO) UpdateColumns

func (d *DO) UpdateColumns(value interface{}) (info ResultInfo, err error)

UpdateColumns ...

func (*DO) UpdateFrom added in v0.1.18

func (d *DO) UpdateFrom(q SubQuery) Dao

UpdateFrom specify update sub query

func (*DO) UpdateSimple added in v0.0.15

func (d *DO) UpdateSimple(columns ...field.AssignExpr) (info ResultInfo, err error)

UpdateSimple ...

func (*DO) Updates

func (d *DO) Updates(value interface{}) (info ResultInfo, err error)

Updates ...

func (*DO) UseDB

func (d *DO) UseDB(db *gorm.DB, opts ...DOOption)

UseDB specify a db connection(*gorm.DB)

func (*DO) UseModel

func (d *DO) UseModel(model interface{})

UseModel specify a data model structure as a source for table name

func (*DO) UseTable

func (d *DO) UseTable(tableName string)

UseTable specify table name

func (*DO) Where

func (d *DO) Where(conds ...Condition) Dao

Where ...

func (*DO) WithContext added in v0.0.16

func (d *DO) WithContext(ctx context.Context) Dao

WithContext return a DO with db with context

func (DO) WithResult added in v0.2.39

func (d DO) WithResult(fc func(tx Dao)) ResultInfo

WithResult ...

type DOConfig added in v0.3.18

type DOConfig struct {
	ClauseChecker ClauseChecker
}

func (*DOConfig) AfterInitialize added in v0.3.18

func (c *DOConfig) AfterInitialize(db *DO) error

AfterInitialize initialize plugins after db connected

func (*DOConfig) Apply added in v0.3.18

func (c *DOConfig) Apply(config *DOConfig) error

Apply update config to new config

type DOOption added in v0.3.18

type DOOption interface {
	Apply(*DOConfig) error
	AfterInitialize(*DO) error
}

DOOption gorm option interface

func WithClauseChecker added in v0.3.28

func WithClauseChecker(checker ClauseChecker) DOOption

type Dao

type Dao interface {
	SubQuery
	schema.Tabler
	As(alias string) Dao

	Not(conds ...Condition) Dao
	Or(conds ...Condition) Dao

	Select(columns ...field.Expr) Dao
	Where(conds ...Condition) Dao
	Order(columns ...field.Expr) Dao
	Distinct(columns ...field.Expr) Dao
	Omit(columns ...field.Expr) Dao
	Join(table schema.Tabler, conds ...field.Expr) Dao
	LeftJoin(table schema.Tabler, conds ...field.Expr) Dao
	RightJoin(table schema.Tabler, conds ...field.Expr) Dao
	Group(columns ...field.Expr) Dao
	Having(conds ...Condition) Dao
	Limit(limit int) Dao
	Offset(offset int) Dao
	Scopes(funcs ...func(Dao) Dao) Dao
	Unscoped() Dao
	Attrs(attrs ...field.AssignExpr) Dao
	Assign(attrs ...field.AssignExpr) Dao
	Joins(field field.RelationField) Dao
	Preload(field field.RelationField) Dao
	Clauses(conds ...clause.Expression) Dao

	Create(value interface{}) error
	CreateInBatches(value interface{}, batchSize int) error
	Save(value interface{}) error
	First() (result interface{}, err error)
	Take() (result interface{}, err error)
	Last() (result interface{}, err error)
	Find() (results interface{}, err error)
	FindInBatches(dest interface{}, batchSize int, fc func(tx Dao, batch int) error) error
	FirstOrInit() (result interface{}, err error)
	FirstOrCreate() (result interface{}, err error)
	Update(column field.Expr, value interface{}) (info ResultInfo, err error)
	UpdateSimple(columns ...field.AssignExpr) (info ResultInfo, err error)
	Updates(values interface{}) (info ResultInfo, err error)
	UpdateColumn(column field.Expr, value interface{}) (info ResultInfo, err error)
	UpdateColumns(values interface{}) (info ResultInfo, err error)
	UpdateColumnSimple(columns ...field.AssignExpr) (info ResultInfo, err error)
	Delete(...interface{}) (info ResultInfo, err error)
	Count() (int64, error)
	Row() *sql.Row
	Rows() (*sql.Rows, error)
	Scan(dest interface{}) error
	Pluck(column field.Expr, dest interface{}) error
	ScanRows(rows *sql.Rows, dest interface{}) error

	AddError(err error) error
}

Dao CRUD methods

func Table

func Table(subQueries ...SubQuery) Dao

Table return a new table produced by subquery, the return value has to be used as root node

Table(u.Select(u.ID, u.Name).Where(u.Age.Gt(18))).Select()

the above usage is equivalent to SQL statement:

SELECT * FROM (SELECT `id`, `name` FROM `users_info` WHERE `age` > ?)"

type Field added in v0.3.23

type Field = *model.Field

Field exported model.Field

type GenerateMode added in v0.0.16

type GenerateMode uint

GenerateMode generate mode

const (
	// WithDefaultQuery create default query in generated code
	WithDefaultQuery GenerateMode = 1 << iota

	// WithoutContext generate code without context constrain
	WithoutContext

	// WithQueryInterface generate code with exported interface object
	WithQueryInterface

	// WithGeneric generate code with generic
	WithGeneric
)

type Generator

type Generator struct {
	Config
	Data map[string]*genInfo //gen query data
	// contains filtered or unexported fields
}

Generator code generator

func NewGenerator

func NewGenerator(cfg Config) *Generator

NewGenerator create a new generator

func (*Generator) ApplyBasic

func (g *Generator) ApplyBasic(models ...interface{})

ApplyBasic specify models which will implement basic .diy_method

func (*Generator) ApplyInterface

func (g *Generator) ApplyInterface(fc interface{}, models ...interface{})

ApplyInterface specifies .diy_method interfaces on structures, implement codes will be generated after calling g.Execute() eg: g.ApplyInterface(func(model.Method){}, model.User{}, model.Company{})

func (*Generator) Execute

func (g *Generator) Execute()

Execute generate code to output path

func (*Generator) GenerateAllTable added in v0.1.20

func (g *Generator) GenerateAllTable(opts ...ModelOpt) (tableModels []interface{})

GenerateAllTable generate all tables in db

func (*Generator) GenerateModel

func (g *Generator) GenerateModel(tableName string, opts ...ModelOpt) *generate.QueryStructMeta

GenerateModel catch table info from db, return a BaseStruct

func (*Generator) GenerateModelAs

func (g *Generator) GenerateModelAs(tableName string, modelName string, opts ...ModelOpt) *generate.QueryStructMeta

GenerateModelAs catch table info from db, return a BaseStruct

func (*Generator) GenerateModelFrom added in v0.3.0

func (g *Generator) GenerateModelFrom(obj helper.Object) *generate.QueryStructMeta

GenerateModelFrom generate model from object

func (*Generator) SetLogger added in v0.3.27

func (g *Generator) SetLogger(logger Logger)

SetLogger set gen logger

func (*Generator) UseDB

func (g *Generator) UseDB(db *gorm.DB)

UseDB set db connection

type GenericsDo added in v0.3.28

type GenericsDo[T IGenericsDo[T, E], E any] struct {
	DO
	IWithDO[T]
}

GenericsDo base impl of IGenericsDo

func (GenericsDo[T, E]) Assign added in v0.3.28

func (b GenericsDo[T, E]) Assign(attrs ...field.AssignExpr) T

Assign ...

func (GenericsDo[T, E]) Attrs added in v0.3.28

func (b GenericsDo[T, E]) Attrs(attrs ...field.AssignExpr) T

Attrs ...

func (GenericsDo[T, E]) Clauses added in v0.3.28

func (b GenericsDo[T, E]) Clauses(conds ...clause.Expression) T

Clauses ...

func (GenericsDo[T, E]) Create added in v0.3.28

func (b GenericsDo[T, E]) Create(values ...E) error

Create ...

func (GenericsDo[T, E]) CreateInBatches added in v0.3.28

func (b GenericsDo[T, E]) CreateInBatches(values []E, batchSize int) error

CreateInBatches ...

func (GenericsDo[T, E]) Debug added in v0.3.28

func (b GenericsDo[T, E]) Debug() T

Debug ...

func (GenericsDo[T, E]) Delete added in v0.3.28

func (b GenericsDo[T, E]) Delete(models ...E) (result ResultInfo, err error)

Delete ...

func (GenericsDo[T, E]) Distinct added in v0.3.28

func (b GenericsDo[T, E]) Distinct(cols ...field.Expr) T

Distinct ...

func (GenericsDo[T, E]) Find added in v0.3.28

func (b GenericsDo[T, E]) Find() ([]E, error)

Find ...

func (GenericsDo[T, E]) FindByPage added in v0.3.28

func (b GenericsDo[T, E]) FindByPage(offset int, limit int) (result []E, count int64, err error)

FindByPage ...

func (GenericsDo[T, E]) FindInBatch added in v0.3.28

func (b GenericsDo[T, E]) FindInBatch(batchSize int, fc func(tx Dao, batch int) error) (results []E, err error)

FindInBatch ...

func (GenericsDo[T, E]) FindInBatches added in v0.3.28

func (b GenericsDo[T, E]) FindInBatches(result *[]E, batchSize int, fc func(tx Dao, batch int) error) error

FindInBatches ...

func (GenericsDo[T, E]) First added in v0.3.28

func (b GenericsDo[T, E]) First() (E, error)

First ...

func (GenericsDo[T, E]) FirstOrCreate added in v0.3.28

func (b GenericsDo[T, E]) FirstOrCreate() (E, error)

FirstOrCreate ...

func (GenericsDo[T, E]) FirstOrInit added in v0.3.28

func (b GenericsDo[T, E]) FirstOrInit() (E, error)

FirstOrInit ...

func (GenericsDo[T, E]) Group added in v0.3.28

func (b GenericsDo[T, E]) Group(cols ...field.Expr) T

Group ...

func (GenericsDo[T, E]) Having added in v0.3.28

func (b GenericsDo[T, E]) Having(conds ...Condition) T

Having ...

func (GenericsDo[T, E]) Join added in v0.3.28

func (b GenericsDo[T, E]) Join(table schema.Tabler, on ...field.Expr) T

Join ...

func (GenericsDo[T, E]) Joins added in v0.3.28

func (b GenericsDo[T, E]) Joins(fields ...field.RelationField) T

Joins ...

func (GenericsDo[T, E]) Last added in v0.3.28

func (b GenericsDo[T, E]) Last() (E, error)

Last ...

func (GenericsDo[T, E]) LeftJoin added in v0.3.28

func (b GenericsDo[T, E]) LeftJoin(table schema.Tabler, on ...field.Expr) T

LeftJoin ...

func (GenericsDo[T, E]) Limit added in v0.3.28

func (b GenericsDo[T, E]) Limit(limit int) T

Limit ...

func (GenericsDo[T, E]) Not added in v0.3.28

func (b GenericsDo[T, E]) Not(conds ...Condition) T

Not ...

func (GenericsDo[T, E]) Offset added in v0.3.28

func (b GenericsDo[T, E]) Offset(offset int) T

Offset ...

func (GenericsDo[T, E]) Omit added in v0.3.28

func (b GenericsDo[T, E]) Omit(cols ...field.Expr) T

Omit ...

func (GenericsDo[T, E]) Or added in v0.3.28

func (b GenericsDo[T, E]) Or(conds ...Condition) T

Or ...

func (GenericsDo[T, E]) Order added in v0.3.28

func (b GenericsDo[T, E]) Order(conds ...field.Expr) T

Order ...

func (GenericsDo[T, E]) Preload added in v0.3.28

func (b GenericsDo[T, E]) Preload(fields ...field.RelationField) T

Preload ...

func (GenericsDo[T, E]) ReadDB added in v0.3.28

func (b GenericsDo[T, E]) ReadDB() T

ReadDB ...

func (GenericsDo[T, E]) Returning added in v0.3.28

func (b GenericsDo[T, E]) Returning(value interface{}, columns ...string) T

Returning ...

func (GenericsDo[T, E]) RightJoin added in v0.3.28

func (b GenericsDo[T, E]) RightJoin(table schema.Tabler, on ...field.Expr) T

RightJoin ...

func (GenericsDo[T, E]) Save added in v0.3.28

func (b GenericsDo[T, E]) Save(values ...E) error

Save : !!! underlying implementation is different with GORM The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values)

func (GenericsDo[T, E]) Scan added in v0.3.28

func (b GenericsDo[T, E]) Scan(result interface{}) (err error)

Scan ...

func (GenericsDo[T, E]) ScanByPage added in v0.3.28

func (b GenericsDo[T, E]) ScanByPage(result interface{}, offset int, limit int) (count int64, err error)

ScanByPage ...

func (GenericsDo[T, E]) Scopes added in v0.3.28

func (b GenericsDo[T, E]) Scopes(funcs ...func(Dao) Dao) T

Scopes ...

func (GenericsDo[T, E]) Select added in v0.3.28

func (b GenericsDo[T, E]) Select(conds ...field.Expr) T

Select ...

func (GenericsDo[T, E]) Session added in v0.3.28

func (b GenericsDo[T, E]) Session(config *gorm.Session) T

Session ...

func (GenericsDo[T, E]) Take added in v0.3.28

func (b GenericsDo[T, E]) Take() (E, error)

Take ...

func (GenericsDo[T, E]) ToSQL added in v0.3.28

func (b GenericsDo[T, E]) ToSQL(queryFn func(T)) string

ToSQL ...

func (GenericsDo[T, E]) Unscoped added in v0.3.28

func (b GenericsDo[T, E]) Unscoped() T

Unscoped ...

func (GenericsDo[T, E]) Where added in v0.3.28

func (b GenericsDo[T, E]) Where(conds ...Condition) T

Where ...

func (GenericsDo[T, E]) WithContext added in v0.3.28

func (b GenericsDo[T, E]) WithContext(ctx context.Context) T

WithContext ...

func (GenericsDo[T, E]) WriteDB added in v0.3.28

func (b GenericsDo[T, E]) WriteDB() T

WriteDB ...

type IGenericsDo added in v0.3.28

type IGenericsDo[T any, E any] interface {
	SubQuery
	Debug() T
	WithContext(ctx context.Context) T
	WithResult(fc func(tx Dao)) ResultInfo
	ReplaceDB(db *gorm.DB)
	ReadDB() T
	WriteDB() T
	As(alias string) Dao
	Session(config *gorm.Session) T
	Columns(cols ...field.Expr) Columns
	Clauses(conds ...clause.Expression) T
	Not(conds ...Condition) T
	Or(conds ...Condition) T
	Select(conds ...field.Expr) T
	Where(conds ...Condition) T
	Order(conds ...field.Expr) T
	Distinct(cols ...field.Expr) T
	Omit(cols ...field.Expr) T
	Join(table schema.Tabler, on ...field.Expr) T
	LeftJoin(table schema.Tabler, on ...field.Expr) T
	RightJoin(table schema.Tabler, on ...field.Expr) T
	Group(cols ...field.Expr) T
	Having(conds ...Condition) T
	Limit(limit int) T
	Offset(offset int) T
	Count() (count int64, err error)
	Scopes(funcs ...func(Dao) Dao) T
	Unscoped() T
	Create(values ...E) error
	CreateInBatches(values []E, batchSize int) error
	Save(values ...E) error
	First() (E, error)
	Take() (E, error)
	Last() (E, error)
	Find() ([]E, error)
	FindInBatch(batchSize int, fc func(tx Dao, batch int) error) (results []E, err error)
	FindInBatches(result *[]E, batchSize int, fc func(tx Dao, batch int) error) error
	Pluck(column field.Expr, dest interface{}) error
	Delete(...E) (info ResultInfo, err error)
	Update(column field.Expr, value interface{}) (info ResultInfo, err error)
	UpdateSimple(columns ...field.AssignExpr) (info ResultInfo, err error)
	Updates(value interface{}) (info ResultInfo, err error)
	UpdateColumn(column field.Expr, value interface{}) (info ResultInfo, err error)
	UpdateColumnSimple(columns ...field.AssignExpr) (info ResultInfo, err error)
	UpdateColumns(value interface{}) (info ResultInfo, err error)
	UpdateFrom(q SubQuery) Dao
	Attrs(attrs ...field.AssignExpr) T
	Assign(attrs ...field.AssignExpr) T
	Joins(fields ...field.RelationField) T
	Preload(fields ...field.RelationField) T
	FirstOrInit() (E, error)
	FirstOrCreate() (E, error)
	FindByPage(offset int, limit int) (result []E, count int64, err error)
	ScanByPage(result interface{}, offset int, limit int) (count int64, err error)
	Rows() (*sql.Rows, error)
	Row() *sql.Row
	Scan(result interface{}) (err error)
	Returning(value interface{}, columns ...string) T
	UnderlyingDB() *gorm.DB
	schema.Tabler
	ToSQL(queryFn func(T)) string
}

IGenericsDo generic query interface

type IWithDO added in v0.3.28

type IWithDO[T any] interface {
	// WithDO associates a DAO instance with the implementing type
	//   - do: The DAO (Data Access Object) to be used for data operations
	// Returns a new instance of the implementing type with the DAO set
	// This enables fluent-style method chaining while maintaining type safety
	WithDO(do Dao) T
}

IWithDO is a generic interface for types that can be associated with a DAO (Data Access Object) It enables method chaining by returning the concrete implementation type

type Logger added in v0.3.27

type Logger interface {
	Println(v ...any)
}

Logger gen logger interface

type M added in v0.0.9

type M map[string]interface{}

M map[string]interface{}

type ModelOpt added in v0.3.14

type ModelOpt = model.Option

ModelOpt field option

type ResultInfo added in v0.1.21

type ResultInfo struct {
	RowsAffected int64
	Error        error
}

ResultInfo query/execute info

type RowsAffected added in v0.1.1

type RowsAffected int64

RowsAffected execute affected raws

type SQLResult added in v0.3.21

type SQLResult sql.Result

SQLResult sql.result

type SQLRow added in v0.3.21

type SQLRow sql.Row

SQLRow sql.Row

type SQLRows added in v0.3.21

type SQLRows sql.Rows

SQLRows sql.Rows

type SubQuery added in v0.3.9

type SubQuery interface {
	Condition
	// contains filtered or unexported methods
}

SubQuery sub query interface

type T

type T interface{}

T generic type

type WithDOFunc added in v0.3.28

type WithDOFunc[T any] func(do Dao) T

WithDOFunc is a function type that implements the IWithDO interface through functional options. It provides a mechanism to inject DAO dependencies while maintaining type safety with generics.

The generic type T should be constrained to pointer receivers of concrete types to ensure proper value semantics and immutability.

func (WithDOFunc[T]) WithDO added in v0.3.28

func (b WithDOFunc[T]) WithDO(do Dao) T

WithDO executes the receiver function with the provided DAO instance, returning a new instance of type T. This method enables fluent chaining while preserving immutability by design.

Parameters:

do - Data Access Object instance (non-nil) to be injected

Returns:

New instance of type T initialized with the DAO dependency

Example:

constructor := func(do Dao) *UserService {
    return &UserService{dao: do}
}
service := WithDOFunc[*UserService](constructor).WithDO(db)

Directories

Path Synopsis
Package field implement all type field and method
Package field implement all type field and method
internal
utils/pools
Package pools : goroutine pools
Package pools : goroutine pools
tools
gentool module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL