gorm

package module
v1.31.1 Latest Latest
Warning

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

Go to latest
Published: Jul 20, 2026 License: MIT Imports: 0 Imported by: 0

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

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

View Source
var (
	// ErrRecordNotFound record not found error
	ErrRecordNotFound = logger.ErrRecordNotFound
	// ErrInvalidTransaction invalid transaction when you are trying to `Commit` or `Rollback`
	ErrInvalidTransaction = errors.New("invalid transaction")
	// ErrNotImplemented not implemented
	ErrNotImplemented = errors.New("not implemented")
	// ErrMissingWhereClause missing where clause
	ErrMissingWhereClause = errors.New("WHERE conditions required")
	// ErrUnsupportedRelation unsupported relations
	ErrUnsupportedRelation = errors.New("unsupported relations")
	// ErrPrimaryKeyRequired primary keys required
	ErrPrimaryKeyRequired = errors.New("primary key required")
	// ErrModelValueRequired model value required
	ErrModelValueRequired = errors.New("model value required")
	// ErrModelAccessibleFieldsRequired model accessible fields required
	ErrModelAccessibleFieldsRequired = errors.New("model accessible fields required")
	// ErrSubQueryRequired sub query required
	ErrSubQueryRequired = errors.New("sub query required")
	// ErrInvalidData unsupported data
	ErrInvalidData = errors.New("unsupported data")
	// ErrUnsupportedDriver unsupported driver
	ErrUnsupportedDriver = errors.New("unsupported driver")
	// ErrRegistered registered
	ErrRegistered = errors.New("registered")
	// ErrInvalidField invalid field
	ErrInvalidField = errors.New("invalid field")
	// ErrEmptySlice empty slice found
	ErrEmptySlice = errors.New("empty slice found")
	// ErrDryRunModeUnsupported dry run mode unsupported
	ErrDryRunModeUnsupported = errors.New("dry run mode unsupported")
	// ErrInvalidDB invalid db
	ErrInvalidDB = errors.New("invalid db")
	// ErrInvalidValue invalid value
	ErrInvalidValue = errors.New("invalid value, should be pointer to struct or slice")
	// ErrInvalidValueOfLength invalid values do not match length
	ErrInvalidValueOfLength = errors.New("invalid association values, length doesn't match")
	// ErrPreloadNotAllowed preload is not allowed when count is used
	ErrPreloadNotAllowed = errors.New("preload is not allowed when count is used")
	// ErrDuplicatedKey occurs when there is a unique key constraint violation
	ErrDuplicatedKey = errors.New("duplicated key not allowed")
	// ErrForeignKeyViolated occurs when there is a foreign key constraint violation
	ErrForeignKeyViolated = errors.New("violates foreign key constraint")
	// ErrCheckConstraintViolated occurs when there is a check constraint violation
	ErrCheckConstraintViolated = errors.New("violates check constraint")
)

Functions ΒΆ

func Expr ΒΆ

func Expr(expr string, args ...interface{}) clause.Expr

Expr returns clause.Expr, which can be used to pass SQL expression as params

func Scan ΒΆ

func Scan(rows Rows, db *DB, mode ScanMode)

Scan scan rows into db statement

func WithResult ΒΆ

func WithResult() *result

Types ΒΆ

type Association ΒΆ

type Association struct {
	DB           *DB
	Relationship *schema.Relationship
	Unscope      bool
	Error        error
}

Association Mode contains some helper methods to handle relationship things easily.

func (*Association) Append ΒΆ

func (association *Association) Append(values ...interface{}) error

func (*Association) Clear ΒΆ

func (association *Association) Clear() error

func (*Association) Count ΒΆ

func (association *Association) Count() (count int64)

func (*Association) Delete ΒΆ

func (association *Association) Delete(values ...interface{}) error

func (*Association) Find ΒΆ

func (association *Association) Find(out interface{}, conds ...interface{}) error

func (*Association) Replace ΒΆ

func (association *Association) Replace(values ...interface{}) error

func (*Association) Unscoped ΒΆ

func (association *Association) Unscoped() *Association

type ChainInterface ΒΆ

type ChainInterface[T any] interface {
	ExecInterface[T]
	Scopes(scopes ...func(db *Statement)) ChainInterface[T]
	Where(query interface{}, args ...interface{}) ChainInterface[T]
	Not(query interface{}, args ...interface{}) ChainInterface[T]
	Or(query interface{}, args ...interface{}) ChainInterface[T]
	Limit(offset int) ChainInterface[T]
	Offset(offset int) ChainInterface[T]
	Joins(query clause.JoinTarget, on func(db JoinBuilder, joinTable clause.Table, curTable clause.Table) error) ChainInterface[T]
	Preload(association string, query func(db PreloadBuilder) error) ChainInterface[T]
	Select(query string, args ...interface{}) ChainInterface[T]
	Omit(columns ...string) ChainInterface[T]
	MapColumns(m map[string]string) ChainInterface[T]
	Distinct(args ...interface{}) ChainInterface[T]
	Group(name string) ChainInterface[T]
	Having(query interface{}, args ...interface{}) ChainInterface[T]
	Order(value interface{}) ChainInterface[T]
	Set(assignments ...clause.Assigner) SetUpdateOnlyInterface[T]

	Build(builder clause.Builder)

	Table(name string, args ...interface{}) ChainInterface[T]
	Delete(ctx context.Context) (rowsAffected int, err error)
	Update(ctx context.Context, name string, value any) (rowsAffected int, err error)
	Updates(ctx context.Context, t T) (rowsAffected int, err error)
	Count(ctx context.Context, column string) (result int64, err error)
}

type ColumnType ΒΆ

type ColumnType interface {
	Name() string
	DatabaseTypeName() string                 // varchar
	ColumnType() (columnType string, ok bool) // varchar(64)
	PrimaryKey() (isPrimaryKey bool, ok bool)
	AutoIncrement() (isAutoIncrement bool, ok bool)
	Length() (length int64, ok bool)
	DecimalSize() (precision int64, scale int64, ok bool)
	Nullable() (nullable bool, ok bool)
	Unique() (unique bool, ok bool)
	ScanType() reflect.Type
	Comment() (value string, ok bool)
	DefaultValue() (value string, ok bool)
}

ColumnType column type interface

type Config ΒΆ

type Config struct {
	// GORM perform single create, update, delete operations in transactions by default to ensure database data integrity
	// You can disable it by setting `SkipDefaultTransaction` to true
	SkipDefaultTransaction    bool
	DefaultTransactionTimeout time.Duration
	DefaultContextTimeout     time.Duration

	// NamingStrategy tables, columns naming strategy
	NamingStrategy schema.Namer
	// FullSaveAssociations full save associations
	FullSaveAssociations bool
	// Logger
	Logger logger.Interface
	// NowFunc the function to be used when creating a new timestamp
	NowFunc func() time.Time
	// DryRun generate sql without execute
	DryRun bool
	// PrepareStmt executes the given query in cached statement
	PrepareStmt bool
	// PrepareStmt cache support LRU expired,
	// default maxsize=int64 Max value and ttl=1h
	PrepareStmtMaxSize int
	PrepareStmtTTL     time.Duration

	// DisableAutomaticPing
	DisableAutomaticPing bool
	// DisableForeignKeyConstraintWhenMigrating
	DisableForeignKeyConstraintWhenMigrating bool
	// IgnoreRelationshipsWhenMigrating
	IgnoreRelationshipsWhenMigrating bool
	// DisableNestedTransaction disable nested transaction
	DisableNestedTransaction bool
	// AllowGlobalUpdate allow global update
	AllowGlobalUpdate bool
	// QueryFields executes the SQL query with all fields of the table
	QueryFields bool
	// CreateBatchSize default create batch size
	CreateBatchSize int
	// TranslateError enabling error translation
	TranslateError bool
	// PropagateUnscoped propagate Unscoped to every other nested statement
	PropagateUnscoped bool

	// ClauseBuilders clause builder
	ClauseBuilders map[string]clause.ClauseBuilder
	// ConnPool db conn pool
	ConnPool ConnPool
	// Dialector database dialector
	Dialector
	// Plugins registered plugins
	Plugins map[string]Plugin
	// contains filtered or unexported fields
}

Config GORM config

func (*Config) AfterInitialize ΒΆ

func (c *Config) AfterInitialize(db *DB) error

AfterInitialize initialize plugins after db connected

func (*Config) Apply ΒΆ

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

Apply update config to new config

type ConnPool ΒΆ

type ConnPool interface {
	PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
	ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
}

ConnPool db conns pool interface

type ConnPoolBeginner ΒΆ

type ConnPoolBeginner interface {
	BeginTx(ctx context.Context, opts *sql.TxOptions) (ConnPool, error)
}

ConnPoolBeginner conn pool beginner

type CreateInterface ΒΆ

type CreateInterface[T any] interface {
	ExecInterface[T]
	// chain methods available at start; Select/Omit keep CreateInterface to allow Create chaining
	Scopes(scopes ...func(db *Statement)) ChainInterface[T]
	Where(query interface{}, args ...interface{}) ChainInterface[T]
	Not(query interface{}, args ...interface{}) ChainInterface[T]
	Or(query interface{}, args ...interface{}) ChainInterface[T]
	Limit(offset int) ChainInterface[T]
	Offset(offset int) ChainInterface[T]
	Joins(query clause.JoinTarget, on func(db JoinBuilder, joinTable clause.Table, curTable clause.Table) error) ChainInterface[T]
	Preload(association string, query func(db PreloadBuilder) error) ChainInterface[T]
	Select(query string, args ...interface{}) CreateInterface[T]
	Omit(columns ...string) CreateInterface[T]
	MapColumns(m map[string]string) ChainInterface[T]
	Distinct(args ...interface{}) ChainInterface[T]
	Group(name string) ChainInterface[T]
	Having(query interface{}, args ...interface{}) ChainInterface[T]
	Order(value interface{}) ChainInterface[T]
	Build(builder clause.Builder)

	Delete(ctx context.Context) (rowsAffected int, err error)
	Update(ctx context.Context, name string, value any) (rowsAffected int, err error)
	Updates(ctx context.Context, t T) (rowsAffected int, err error)
	Count(ctx context.Context, column string) (result int64, err error)

	Table(name string, args ...interface{}) CreateInterface[T]
	Create(ctx context.Context, r *T) error
	CreateInBatches(ctx context.Context, r *[]T, batchSize int) error
	Set(assignments ...clause.Assigner) SetCreateOrUpdateInterface[T]
}

type DB ΒΆ

type DB struct {
	*Config
	Error        error
	RowsAffected int64
	Statement    *Statement
	// contains filtered or unexported fields
}

DB GORM DB definition

func Open ΒΆ

func Open(dialector Dialector, opts ...Option) (db *DB, err error)

Open initialize db session based on dialector

func (*DB) AddError ΒΆ

func (db *DB) AddError(err error) error

AddError add error to db

func (*DB) Assign ΒΆ

func (db *DB) Assign(attrs ...interface{}) (tx *DB)

Assign provide attributes used in FirstOrCreate or FirstOrInit

Assign adds attributes even if the record is found. If using FirstOrCreate, this means that records will be updated even if they are found.

// assign an email regardless of if the record is not found
db.Where(User{Name: "non_existing"}).Assign(User{Email: "fake@fake.org"}).FirstOrInit(&user)
// user -> User{Name: "non_existing", Email: "fake@fake.org"}

// assign email regardless of if record is found
db.Where(User{Name: "jinzhu"}).Assign(User{Email: "fake@fake.org"}).FirstOrInit(&user)
// user -> User{Name: "jinzhu", Age: 20, Email: "fake@fake.org"}

func (*DB) Association ΒΆ

func (db *DB) Association(column string) *Association

func (*DB) Attrs ΒΆ

func (db *DB) Attrs(attrs ...interface{}) (tx *DB)

Attrs provide attributes used in FirstOrCreate or FirstOrInit

Attrs only adds attributes if the record is not found.

// assign an email if the record is not found
db.Where(User{Name: "non_existing"}).Attrs(User{Email: "fake@fake.org"}).FirstOrInit(&user)
// user -> User{Name: "non_existing", Email: "fake@fake.org"}

// assign an email if the record is not found, otherwise ignore provided email
db.Where(User{Name: "jinzhu"}).Attrs(User{Email: "fake@fake.org"}).FirstOrInit(&user)
// user -> User{Name: "jinzhu", Age: 20}

func (*DB) AutoMigrate ΒΆ

func (db *DB) AutoMigrate(dst ...interface{}) error

AutoMigrate run auto migration for given models

func (*DB) Begin ΒΆ

func (db *DB) Begin(opts ...*sql.TxOptions) *DB

Begin begins a transaction with any transaction options opts

func (*DB) Callback ΒΆ

func (db *DB) Callback() *callbacks

Callback returns callback manager

func (*DB) Clauses ΒΆ

func (db *DB) Clauses(conds ...clause.Expression) (tx *DB)

Clauses Add clauses

This supports both standard clauses (clause.OrderBy, clause.Limit, clause.Where) and more advanced techniques like specifying lock strength and optimizer hints. See the docs for more depth.

// add a simple limit clause
db.Clauses(clause.Limit{Limit: 1}).Find(&User{})
// tell the optimizer to use the `idx_user_name` index
db.Clauses(hints.UseIndex("idx_user_name")).Find(&User{})
// specify the lock strength to UPDATE
db.Clauses(clause.Locking{Strength: "UPDATE"}).Find(&users)

func (*DB) Commit ΒΆ

func (db *DB) Commit() *DB

Commit commits the changes in a transaction

func (*DB) Connection ΒΆ

func (db *DB) Connection(fc func(tx *DB) error) (err error)

Connection uses a db connection to execute an arbitrary number of commands in fc. When finished, the connection is returned to the connection pool.

func (*DB) Count ΒΆ

func (db *DB) Count(count *int64) (tx *DB)

func (*DB) Create ΒΆ

func (db *DB) Create(value interface{}) (tx *DB)

Create inserts value, returning the inserted data's primary key in value's id

func (*DB) CreateInBatches ΒΆ

func (db *DB) CreateInBatches(value interface{}, batchSize int) (tx *DB)

CreateInBatches inserts value in batches of batchSize

func (*DB) DB ΒΆ

func (db *DB) DB() (*sql.DB, error)

DB returns `*sql.DB`

func (*DB) Debug ΒΆ

func (db *DB) Debug() (tx *DB)

Debug start debug mode

func (*DB) Delete ΒΆ

func (db *DB) Delete(value interface{}, conds ...interface{}) (tx *DB)

Delete deletes value matching given conditions. If value contains primary key it is included in the conditions. If value includes a deleted_at field, then Delete performs a soft delete instead by setting deleted_at with the current time if null.

func (*DB) Distinct ΒΆ

func (db *DB) Distinct(args ...interface{}) (tx *DB)

Distinct specify distinct fields that you want querying

// Select distinct names of users
db.Distinct("name").Find(&results)
// Select distinct name/age pairs from users
db.Distinct("name", "age").Find(&results)

func (*DB) Exec ΒΆ

func (db *DB) Exec(sql string, values ...interface{}) (tx *DB)

Exec executes raw sql

func (*DB) Find ΒΆ

func (db *DB) Find(dest interface{}, conds ...interface{}) (tx *DB)

Find finds all records matching given conditions conds

func (*DB) FindInBatches ΒΆ

func (db *DB) FindInBatches(dest interface{}, batchSize int, fc func(tx *DB, batch int) error) *DB

FindInBatches finds all records in batches of batchSize

func (*DB) First ΒΆ

func (db *DB) First(dest interface{}, conds ...interface{}) (tx *DB)

First finds the first record ordered by primary key, matching given conditions conds

func (*DB) FirstOrCreate ΒΆ

func (db *DB) FirstOrCreate(dest interface{}, conds ...interface{}) (tx *DB)

FirstOrCreate finds the first matching record, otherwise if not found creates a new instance with given conds. Each conds must be a struct or map.

Using FirstOrCreate in conjunction with Assign will result in an update to the database even if the record exists.

// assign an email if the record is not found
result := db.Where(User{Name: "non_existing"}).Attrs(User{Email: "fake@fake.org"}).FirstOrCreate(&user)
// user -> User{Name: "non_existing", Email: "fake@fake.org"}
// result.RowsAffected -> 1

// assign email regardless of if record is found
result := db.Where(User{Name: "jinzhu"}).Assign(User{Email: "fake@fake.org"}).FirstOrCreate(&user)
// user -> User{Name: "jinzhu", Age: 20, Email: "fake@fake.org"}
// result.RowsAffected -> 1

func (*DB) FirstOrInit ΒΆ

func (db *DB) FirstOrInit(dest interface{}, conds ...interface{}) (tx *DB)

FirstOrInit finds the first matching record, otherwise if not found initializes a new instance with given conds. Each conds must be a struct or map.

FirstOrInit never modifies the database. It is often used with Assign and Attrs.

// assign an email if the record is not found
db.Where(User{Name: "non_existing"}).Attrs(User{Email: "fake@fake.org"}).FirstOrInit(&user)
// user -> User{Name: "non_existing", Email: "fake@fake.org"}

// assign email regardless of if record is found
db.Where(User{Name: "jinzhu"}).Assign(User{Email: "fake@fake.org"}).FirstOrInit(&user)
// user -> User{Name: "jinzhu", Age: 20, Email: "fake@fake.org"}

func (*DB) Get ΒΆ

func (db *DB) Get(key string) (interface{}, bool)

Get get value with key from current db instance's context

func (*DB) Group ΒΆ

func (db *DB) Group(name string) (tx *DB)

Group specify the group method on the find

// Select the sum age of users with given names
db.Model(&User{}).Select("name, sum(age) as total").Group("name").Find(&results)

func (*DB) Having ΒΆ

func (db *DB) Having(query interface{}, args ...interface{}) (tx *DB)

Having specify HAVING conditions for GROUP BY

// Select the sum age of users with name jinzhu
db.Model(&User{}).Select("name, sum(age) as total").Group("name").Having("name = ?", "jinzhu").Find(&result)

func (*DB) InnerJoins ΒΆ

func (db *DB) InnerJoins(query string, args ...interface{}) (tx *DB)

InnerJoins specify inner joins conditions db.InnerJoins("Account").Find(&user)

func (*DB) InstanceGet ΒΆ

func (db *DB) InstanceGet(key string) (interface{}, bool)

InstanceGet get value with key from current db instance's context

func (*DB) InstanceSet ΒΆ

func (db *DB) InstanceSet(key string, value interface{}) *DB

InstanceSet store value with key into current db instance's context

func (*DB) Joins ΒΆ

func (db *DB) Joins(query string, args ...interface{}) (tx *DB)

Joins specify Joins conditions

db.Joins("Account").Find(&user)
db.Joins("JOIN emails ON emails.user_id = users.id AND emails.email = ?", "jinzhu@example.org").Find(&user)
db.Joins("Account", DB.Select("id").Where("user_id = users.id AND name = ?", "someName").Model(&Account{}))

func (*DB) Last ΒΆ

func (db *DB) Last(dest interface{}, conds ...interface{}) (tx *DB)

Last finds the last record ordered by primary key, matching given conditions conds

func (*DB) Limit ΒΆ

func (db *DB) Limit(limit int) (tx *DB)

Limit specify the number of records to be retrieved

Limit conditions can be cancelled by using `Limit(-1)`.

// retrieve 3 users
db.Limit(3).Find(&users)
// retrieve 3 users into users1, and all users into users2
db.Limit(3).Find(&users1).Limit(-1).Find(&users2)

func (*DB) MapColumns ΒΆ

func (db *DB) MapColumns(m map[string]string) (tx *DB)

MapColumns modify the column names in the query results to facilitate align to the corresponding structural fields

func (*DB) Migrator ΒΆ

func (db *DB) Migrator() Migrator

Migrator returns migrator

func (*DB) Model ΒΆ

func (db *DB) Model(value interface{}) (tx *DB)

Model specify the model you would like to run db operations

// update all users's name to `hello`
db.Model(&User{}).Update("name", "hello")
// if user's primary key is non-blank, will use it as condition, then will only update that user's name to `hello`
db.Model(&user).Update("name", "hello")

func (*DB) Not ΒΆ

func (db *DB) Not(query interface{}, args ...interface{}) (tx *DB)

Not add NOT conditions

Not works similarly to where, and has the same syntax.

// Find the first user with name not equal to jinzhu
db.Not("name = ?", "jinzhu").First(&user)

func (*DB) Offset ΒΆ

func (db *DB) Offset(offset int) (tx *DB)

Offset specify the number of records to skip before starting to return the records

Offset conditions can be cancelled by using `Offset(-1)`.

// select the third user
db.Offset(2).First(&user)
// select the first user by cancelling an earlier chained offset
db.Offset(5).Offset(-1).First(&user)

func (*DB) Omit ΒΆ

func (db *DB) Omit(columns ...string) (tx *DB)

Omit specify fields that you want to ignore when creating, updating and querying

func (*DB) Or ΒΆ

func (db *DB) Or(query interface{}, args ...interface{}) (tx *DB)

Or add OR conditions

Or is used to chain together queries with an OR.

// Find the first user with name equal to jinzhu or john
db.Where("name = ?", "jinzhu").Or("name = ?", "john").First(&user)

func (*DB) Order ΒΆ

func (db *DB) Order(value interface{}) (tx *DB)

Order specify order when retrieving records from database

db.Order("name DESC")
db.Order(clause.OrderByColumn{Column: clause.Column{Name: "name"}, Desc: true})
db.Order(clause.OrderBy{Columns: []clause.OrderByColumn{
	{Column: clause.Column{Name: "name"}, Desc: true},
	{Column: clause.Column{Name: "age"}, Desc: true},
}})

func (*DB) Pluck ΒΆ

func (db *DB) Pluck(column string, dest interface{}) (tx *DB)

Pluck queries a single column from a model, returning in the slice dest. E.g.:

var ages []int64
db.Model(&users).Pluck("age", &ages)

func (*DB) Preload ΒΆ

func (db *DB) Preload(query string, args ...interface{}) (tx *DB)

Preload preload associations with given conditions

// get all users, and preload all non-cancelled orders
db.Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users)

func (*DB) Raw ΒΆ

func (db *DB) Raw(sql string, values ...interface{}) (tx *DB)

func (*DB) Rollback ΒΆ

func (db *DB) Rollback() *DB

Rollback rollbacks the changes in a transaction

func (*DB) RollbackTo ΒΆ

func (db *DB) RollbackTo(name string) *DB

func (*DB) Row ΒΆ

func (db *DB) Row() *sql.Row

func (*DB) Rows ΒΆ

func (db *DB) Rows() (*sql.Rows, error)

func (*DB) Save ΒΆ

func (db *DB) Save(value interface{}) (tx *DB)

Save updates value in database. If value doesn't contain a matching primary key, value is inserted.

func (*DB) SavePoint ΒΆ

func (db *DB) SavePoint(name string) *DB

func (*DB) Scan ΒΆ

func (db *DB) Scan(dest interface{}) (tx *DB)

Scan scans selected value to the struct dest

func (*DB) ScanRows ΒΆ

func (db *DB) ScanRows(rows *sql.Rows, dest interface{}) error

func (*DB) Scopes ΒΆ

func (db *DB) Scopes(funcs ...func(*DB) *DB) (tx *DB)

Scopes pass current database connection to arguments `func(DB) DB`, which could be used to add conditions dynamically

func AmountGreaterThan1000(db *gorm.DB) *gorm.DB {
    return db.Where("amount > ?", 1000)
}

func OrderStatus(status []string) func (db *gorm.DB) *gorm.DB {
    return func (db *gorm.DB) *gorm.DB {
        return db.Scopes(AmountGreaterThan1000).Where("status in (?)", status)
    }
}

db.Scopes(AmountGreaterThan1000, OrderStatus([]string{"paid", "shipped"})).Find(&orders)

func (*DB) Select ΒΆ

func (db *DB) Select(query interface{}, args ...interface{}) (tx *DB)

Select specify fields that you want when querying, creating, updating

Use Select when you only want a subset of the fields. By default, GORM will select all fields. Select accepts both string arguments and arrays.

// Select name and age of user using multiple arguments
db.Select("name", "age").Find(&users)
// Select name and age of user using an array
db.Select([]string{"name", "age"}).Find(&users)

func (*DB) Session ΒΆ

func (db *DB) Session(config *Session) *DB

Session create new db session

func (*DB) Set ΒΆ

func (db *DB) Set(key string, value interface{}) *DB

Set store value with key into current db instance's context

func (*DB) SetupJoinTable ΒΆ

func (db *DB) SetupJoinTable(model interface{}, field string, joinTable interface{}) error

SetupJoinTable setup join table schema

func (*DB) Table ΒΆ

func (db *DB) Table(name string, args ...interface{}) (tx *DB)

Table specify the table you would like to run db operations

// Get a user
db.Table("users").Take(&result)

func (*DB) Take ΒΆ

func (db *DB) Take(dest interface{}, conds ...interface{}) (tx *DB)

Take finds the first record returned by the database in no specified order, matching given conditions conds

func (*DB) ToSQL ΒΆ

func (db *DB) ToSQL(queryFn func(tx *DB) *DB) string

ToSQL for generate SQL string.

db.ToSQL(func(tx *gorm.DB) *gorm.DB {
		return tx.Model(&User{}).Where(&User{Name: "foo", Age: 20})
			.Limit(10).Offset(5)
			.Order("name ASC")
			.First(&User{})
})

func (*DB) Transaction ΒΆ

func (db *DB) Transaction(fc func(tx *DB) error, opts ...*sql.TxOptions) (err error)

Transaction start a transaction as a block, return error will rollback, otherwise to commit. Transaction executes an arbitrary number of commands in fc within a transaction. On success the changes are committed; if an error occurs they are rolled back.

func (*DB) Unscoped ΒΆ

func (db *DB) Unscoped() (tx *DB)

Unscoped disables the global scope of soft deletion in a query. By default, GORM uses soft deletion, marking records as "deleted" by setting a timestamp on a specific field (e.g., `deleted_at`). Unscoped allows queries to include records marked as deleted, overriding the soft deletion behavior. Example:

var users []User
db.Unscoped().Find(&users)
// Retrieves all users, including deleted ones.

func (*DB) Update ΒΆ

func (db *DB) Update(column string, value interface{}) (tx *DB)

Update updates column with value using callbacks. Reference: https://gorm.io/docs/update.html#Update-Changed-Fields

func (*DB) UpdateColumn ΒΆ

func (db *DB) UpdateColumn(column string, value interface{}) (tx *DB)

func (*DB) UpdateColumns ΒΆ

func (db *DB) UpdateColumns(values interface{}) (tx *DB)

func (*DB) Updates ΒΆ

func (db *DB) Updates(values interface{}) (tx *DB)

Updates updates attributes using callbacks. values must be a struct or map. Reference: https://gorm.io/docs/update.html#Update-Changed-Fields

func (*DB) Use ΒΆ

func (db *DB) Use(plugin Plugin) error

Use use plugin

func (*DB) Where ΒΆ

func (db *DB) Where(query interface{}, args ...interface{}) (tx *DB)

Where add conditions

See the docs for details on the various formats that where clauses can take. By default, where clauses chain with AND.

// Find the first user with name jinzhu
db.Where("name = ?", "jinzhu").First(&user)
// Find the first user with name jinzhu and age 20
db.Where(&User{Name: "jinzhu", Age: 20}).First(&user)
// Find the first user with name jinzhu and age not equal to 20
db.Where("name = ?", "jinzhu").Where("age <> ?", "20").First(&user)

func (*DB) WithContext ΒΆ

func (db *DB) WithContext(ctx context.Context) *DB

WithContext change current instance db's context to ctx

type DeletedAt ΒΆ

type DeletedAt sql.NullTime

func (DeletedAt) DeleteClauses ΒΆ

func (DeletedAt) DeleteClauses(f *schema.Field) []clause.Interface

func (DeletedAt) MarshalJSON ΒΆ

func (n DeletedAt) MarshalJSON() ([]byte, error)

func (DeletedAt) QueryClauses ΒΆ

func (DeletedAt) QueryClauses(f *schema.Field) []clause.Interface

func (*DeletedAt) Scan ΒΆ

func (n *DeletedAt) Scan(value interface{}) error

Scan implements the Scanner interface.

func (*DeletedAt) UnmarshalJSON ΒΆ

func (n *DeletedAt) UnmarshalJSON(b []byte) error

func (DeletedAt) UpdateClauses ΒΆ

func (DeletedAt) UpdateClauses(f *schema.Field) []clause.Interface

func (DeletedAt) Value ΒΆ

func (n DeletedAt) Value() (driver.Value, error)

Value implements the driver Valuer interface.

type Dialector ΒΆ

type Dialector interface {
	Name() string
	Initialize(*DB) error
	Migrator(db *DB) Migrator
	DataTypeOf(*schema.Field) string
	DefaultValueOf(*schema.Field) clause.Expression
	BindVarTo(writer clause.Writer, stmt *Statement, v interface{})
	QuoteTo(clause.Writer, string)
	Explain(sql string, vars ...interface{}) string
}

Dialector GORM database dialector

type ErrorTranslator ΒΆ

type ErrorTranslator interface {
	Translate(err error) error
}

type ExecInterface ΒΆ

type ExecInterface[T any] interface {
	Scan(ctx context.Context, r interface{}) error
	First(context.Context) (T, error)
	Last(ctx context.Context) (T, error)
	Take(context.Context) (T, error)
	Find(ctx context.Context) ([]T, error)
	FindInBatches(ctx context.Context, batchSize int, fc func(data []T, batch int) error) error
	Row(ctx context.Context) *sql.Row
	Rows(ctx context.Context) (*sql.Rows, error)
}

type GetDBConnector ΒΆ

type GetDBConnector interface {
	GetDBConn() (*sql.DB, error)
}

GetDBConnector SQL db connector

type Index ΒΆ

type Index interface {
	Table() string
	Name() string
	Columns() []string
	PrimaryKey() (isPrimaryKey bool, ok bool)
	Unique() (unique bool, ok bool)
	Option() string
}

type Interface ΒΆ

type Interface[T any] interface {
	Raw(sql string, values ...interface{}) ExecInterface[T]
	Exec(ctx context.Context, sql string, values ...interface{}) error
	CreateInterface[T]
}

func G ΒΆ

func G[T any](db *DB, opts ...clause.Expression) Interface[T]

type JoinBuilder ΒΆ

type JoinBuilder interface {
	Select(...string) JoinBuilder
	Omit(...string) JoinBuilder
	Where(query interface{}, args ...interface{}) JoinBuilder
	Not(query interface{}, args ...interface{}) JoinBuilder
	Or(query interface{}, args ...interface{}) JoinBuilder
}

type Migrator ΒΆ

type Migrator interface {
	// AutoMigrate
	AutoMigrate(dst ...interface{}) error

	// Database
	CurrentDatabase() string
	FullDataTypeOf(*schema.Field) clause.Expr
	GetTypeAliases(databaseTypeName string) []string

	// Tables
	CreateTable(dst ...interface{}) error
	DropTable(dst ...interface{}) error
	HasTable(dst interface{}) bool
	RenameTable(oldName, newName interface{}) error
	GetTables() (tableList []string, err error)
	TableType(dst interface{}) (TableType, error)

	// Columns
	AddColumn(dst interface{}, field string) error
	DropColumn(dst interface{}, field string) error
	AlterColumn(dst interface{}, field string) error
	MigrateColumn(dst interface{}, field *schema.Field, columnType ColumnType) error
	// MigrateColumnUnique migrate column's UNIQUE constraint, it's part of MigrateColumn.
	MigrateColumnUnique(dst interface{}, field *schema.Field, columnType ColumnType) error
	HasColumn(dst interface{}, field string) bool
	RenameColumn(dst interface{}, oldName, field string) error
	ColumnTypes(dst interface{}) ([]ColumnType, error)

	// Views
	CreateView(name string, option ViewOption) error
	DropView(name string) error

	// Constraints
	CreateConstraint(dst interface{}, name string) error
	DropConstraint(dst interface{}, name string) error
	HasConstraint(dst interface{}, name string) bool

	// Indexes
	CreateIndex(dst interface{}, name string) error
	DropIndex(dst interface{}, name string) error
	HasIndex(dst interface{}, name string) bool
	RenameIndex(dst interface{}, oldName, newName string) error
	GetIndexes(dst interface{}) ([]Index, error)
}

Migrator migrator interface

type Model ΒΆ

type Model struct {
	ID        uint `gorm:"primarykey"`
	CreatedAt time.Time
	UpdatedAt time.Time
	DeletedAt DeletedAt `gorm:"index"`
}

Model a basic GoLang struct which includes the following fields: ID, CreatedAt, UpdatedAt, DeletedAt It may be embedded into your model or you may build your own model without it

type User struct {
  gorm.Model
}

type Option ΒΆ

type Option interface {
	Apply(*Config) error
	AfterInitialize(*DB) error
}

Option gorm option interface

type ParamsFilter ΒΆ

type ParamsFilter interface {
	ParamsFilter(ctx context.Context, sql string, params ...interface{}) (string, []interface{})
}

type Plugin ΒΆ

type Plugin interface {
	Name() string
	Initialize(*DB) error
}

Plugin GORM plugin interface

type PreloadBuilder ΒΆ

type PreloadBuilder interface {
	Select(...string) PreloadBuilder
	Omit(...string) PreloadBuilder
	Where(query interface{}, args ...interface{}) PreloadBuilder
	Not(query interface{}, args ...interface{}) PreloadBuilder
	Or(query interface{}, args ...interface{}) PreloadBuilder
	Limit(offset int) PreloadBuilder
	Offset(offset int) PreloadBuilder
	Order(value interface{}) PreloadBuilder
	LimitPerRecord(num int) PreloadBuilder
}

type PreparedStmtDB ΒΆ

type PreparedStmtDB struct {
	Stmts stmt_store.Store
	Mux   *sync.RWMutex
	ConnPool
}

func NewPreparedStmtDB ΒΆ

func NewPreparedStmtDB(connPool ConnPool, maxSize int, ttl time.Duration) *PreparedStmtDB

NewPreparedStmtDB creates and initializes a new instance of PreparedStmtDB.

Parameters: - connPool: A connection pool that implements the ConnPool interface, used for managing database connections. - maxSize: The maximum number of prepared statements that can be stored in the statement store. - ttl: The time-to-live duration for each prepared statement in the store. Statements older than this duration will be automatically removed.

Returns: - A pointer to a PreparedStmtDB instance, which manages prepared statements using the provided connection pool and configuration.

func (*PreparedStmtDB) BeginTx ΒΆ

func (db *PreparedStmtDB) BeginTx(ctx context.Context, opt *sql.TxOptions) (ConnPool, error)

func (*PreparedStmtDB) Close ΒΆ

func (db *PreparedStmtDB) Close()

Close closes all prepared statements in the store

func (*PreparedStmtDB) ExecContext ΒΆ

func (db *PreparedStmtDB) ExecContext(ctx context.Context, query string, args ...interface{}) (result sql.Result, err error)

func (*PreparedStmtDB) GetDBConn ΒΆ

func (db *PreparedStmtDB) GetDBConn() (*sql.DB, error)

GetDBConn returns the underlying *sql.DB connection

func (*PreparedStmtDB) Ping ΒΆ

func (db *PreparedStmtDB) Ping() error

func (*PreparedStmtDB) QueryContext ΒΆ

func (db *PreparedStmtDB) QueryContext(ctx context.Context, query string, args ...interface{}) (rows *sql.Rows, err error)

func (*PreparedStmtDB) QueryRowContext ΒΆ

func (db *PreparedStmtDB) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row

func (*PreparedStmtDB) Reset ΒΆ

func (db *PreparedStmtDB) Reset()

Reset Deprecated use Close instead

type PreparedStmtTX ΒΆ

type PreparedStmtTX struct {
	Tx
	PreparedStmtDB *PreparedStmtDB
}

func (*PreparedStmtTX) Commit ΒΆ

func (tx *PreparedStmtTX) Commit() error

func (*PreparedStmtTX) ExecContext ΒΆ

func (tx *PreparedStmtTX) ExecContext(ctx context.Context, query string, args ...interface{}) (result sql.Result, err error)

func (*PreparedStmtTX) GetDBConn ΒΆ

func (db *PreparedStmtTX) GetDBConn() (*sql.DB, error)

func (*PreparedStmtTX) Ping ΒΆ

func (tx *PreparedStmtTX) Ping() error

func (*PreparedStmtTX) QueryContext ΒΆ

func (tx *PreparedStmtTX) QueryContext(ctx context.Context, query string, args ...interface{}) (rows *sql.Rows, err error)

func (*PreparedStmtTX) QueryRowContext ΒΆ

func (tx *PreparedStmtTX) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row

func (*PreparedStmtTX) Rollback ΒΆ

func (tx *PreparedStmtTX) Rollback() error

type Rows ΒΆ

type Rows interface {
	Columns() ([]string, error)
	ColumnTypes() ([]*sql.ColumnType, error)
	Next() bool
	Scan(dest ...interface{}) error
	Err() error
	Close() error
}

Rows rows interface

type SavePointerDialectorInterface ΒΆ

type SavePointerDialectorInterface interface {
	SavePoint(tx *DB, name string) error
	RollbackTo(tx *DB, name string) error
}

SavePointerDialectorInterface save pointer interface

type ScanMode ΒΆ

type ScanMode uint8

ScanMode scan data mode

const (
	ScanInitialized         ScanMode = 1 << 0 // 1
	ScanUpdate              ScanMode = 1 << 1 // 2
	ScanOnConflictDoNothing ScanMode = 1 << 2 // 4
)

scan modes

type Session ΒΆ

type Session struct {
	DryRun                   bool
	PrepareStmt              bool
	NewDB                    bool
	Initialized              bool
	SkipHooks                bool
	SkipDefaultTransaction   bool
	DisableNestedTransaction bool
	AllowGlobalUpdate        bool
	FullSaveAssociations     bool
	PropagateUnscoped        bool
	QueryFields              bool
	Context                  context.Context
	Logger                   logger.Interface
	NowFunc                  func() time.Time
	CreateBatchSize          int
}

Session session config when create session with Session() method

type SetCreateOrUpdateInterface ΒΆ

type SetCreateOrUpdateInterface[T any] interface {
	Create(ctx context.Context) error
	Update(ctx context.Context) (rowsAffected int, err error)
}

SetCreateOrUpdateInterface is returned by Set at start; Create or Update are allowed

type SetUpdateOnlyInterface ΒΆ

type SetUpdateOnlyInterface[T any] interface {
	Update(ctx context.Context) (rowsAffected int, err error)
}

SetUpdateOnlyInterface is returned by Set after chaining; only Update is allowed

type SoftDeleteDeleteClause ΒΆ

type SoftDeleteDeleteClause struct {
	ZeroValue sql.NullString
	Field     *schema.Field
}

func (SoftDeleteDeleteClause) Build ΒΆ

func (SoftDeleteDeleteClause) MergeClause ΒΆ

func (sd SoftDeleteDeleteClause) MergeClause(*clause.Clause)

func (SoftDeleteDeleteClause) ModifyStatement ΒΆ

func (sd SoftDeleteDeleteClause) ModifyStatement(stmt *Statement)

func (SoftDeleteDeleteClause) Name ΒΆ

func (sd SoftDeleteDeleteClause) Name() string

type SoftDeleteQueryClause ΒΆ

type SoftDeleteQueryClause struct {
	ZeroValue sql.NullString
	Field     *schema.Field
}

func (SoftDeleteQueryClause) Build ΒΆ

func (SoftDeleteQueryClause) MergeClause ΒΆ

func (sd SoftDeleteQueryClause) MergeClause(*clause.Clause)

func (SoftDeleteQueryClause) ModifyStatement ΒΆ

func (sd SoftDeleteQueryClause) ModifyStatement(stmt *Statement)

func (SoftDeleteQueryClause) Name ΒΆ

func (sd SoftDeleteQueryClause) Name() string

type SoftDeleteUpdateClause ΒΆ

type SoftDeleteUpdateClause struct {
	ZeroValue sql.NullString
	Field     *schema.Field
}

func (SoftDeleteUpdateClause) Build ΒΆ

func (SoftDeleteUpdateClause) MergeClause ΒΆ

func (sd SoftDeleteUpdateClause) MergeClause(*clause.Clause)

func (SoftDeleteUpdateClause) ModifyStatement ΒΆ

func (sd SoftDeleteUpdateClause) ModifyStatement(stmt *Statement)

func (SoftDeleteUpdateClause) Name ΒΆ

func (sd SoftDeleteUpdateClause) Name() string

type Statement ΒΆ

type Statement struct {
	*DB
	TableExpr            *clause.Expr
	Table                string
	Model                interface{}
	Unscoped             bool
	Dest                 interface{}
	ReflectValue         reflect.Value
	Clauses              map[string]clause.Clause
	BuildClauses         []string
	Distinct             bool
	Selects              []string          // selected columns
	Omits                []string          // omit columns
	ColumnMapping        map[string]string // map columns
	Joins                []join
	Preloads             map[string][]interface{}
	Settings             sync.Map
	ConnPool             ConnPool
	Schema               *schema.Schema
	Context              context.Context
	RaiseErrorOnNotFound bool
	SkipHooks            bool
	SQL                  strings.Builder
	Vars                 []interface{}
	CurDestIndex         int

	Result *result
	// contains filtered or unexported fields
}

Statement statement

func (*Statement) AddClause ΒΆ

func (stmt *Statement) AddClause(v clause.Interface)

AddClause add clause

func (*Statement) AddClauseIfNotExists ΒΆ

func (stmt *Statement) AddClauseIfNotExists(v clause.Interface)

AddClauseIfNotExists add clause if not exists

func (*Statement) AddVar ΒΆ

func (stmt *Statement) AddVar(writer clause.Writer, vars ...interface{})

AddVar add var

func (*Statement) Build ΒΆ

func (stmt *Statement) Build(clauses ...string)

Build build sql with clauses names

func (*Statement) BuildCondition ΒΆ

func (stmt *Statement) BuildCondition(query interface{}, args ...interface{}) []clause.Expression

BuildCondition build condition

func (*Statement) Changed ΒΆ

func (stmt *Statement) Changed(fields ...string) bool

Changed check model changed or not when updating

func (*Statement) Parse ΒΆ

func (stmt *Statement) Parse(value interface{}) (err error)

func (*Statement) ParseWithSpecialTableName ΒΆ

func (stmt *Statement) ParseWithSpecialTableName(value interface{}, specialTableName string) (err error)

func (*Statement) Quote ΒΆ

func (stmt *Statement) Quote(field interface{}) string

Quote returns quoted value

func (*Statement) QuoteTo ΒΆ

func (stmt *Statement) QuoteTo(writer clause.Writer, field interface{})

QuoteTo write quoted value to writer

func (*Statement) SelectAndOmitColumns ΒΆ

func (stmt *Statement) SelectAndOmitColumns(requireCreate, requireUpdate bool) (map[string]bool, bool)

SelectAndOmitColumns get select and omit columns, select -> true, omit -> false

func (*Statement) SetColumn ΒΆ

func (stmt *Statement) SetColumn(name string, value interface{}, fromCallbacks ...bool)

SetColumn set column's value

stmt.SetColumn("Name", "jinzhu") // Hooks Method
stmt.SetColumn("Name", "jinzhu", true) // Callbacks Method

func (*Statement) WriteByte ΒΆ

func (stmt *Statement) WriteByte(c byte) error

WriteByte write byte

func (*Statement) WriteQuoted ΒΆ

func (stmt *Statement) WriteQuoted(value interface{})

WriteQuoted write quoted value

func (*Statement) WriteString ΒΆ

func (stmt *Statement) WriteString(str string) (int, error)

WriteString write string

type StatementModifier ΒΆ

type StatementModifier interface {
	ModifyStatement(*Statement)
}

StatementModifier statement modifier interface

type TableType ΒΆ

type TableType interface {
	Schema() string
	Name() string
	Type() string
	Comment() (comment string, ok bool)
}

TableType table type interface

type Tx ΒΆ

type Tx interface {
	ConnPool
	TxCommitter
	StmtContext(ctx context.Context, stmt *sql.Stmt) *sql.Stmt
}

Tx sql.Tx interface

type TxBeginner ΒΆ

type TxBeginner interface {
	BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
}

TxBeginner tx beginner

type TxCommitter ΒΆ

type TxCommitter interface {
	Commit() error
	Rollback() error
}

TxCommitter tx committer

type Valuer ΒΆ

type Valuer interface {
	GormValue(context.Context, *DB) clause.Expr
}

Valuer gorm valuer interface

type ViewOption ΒΆ

type ViewOption struct {
	Replace     bool   // If true, exec `CREATE`. If false, exec `CREATE OR REPLACE`
	CheckOption string // optional. e.g. `WITH [ CASCADED | LOCAL ] CHECK OPTION`
	Query       *DB    // required subquery.
}

ViewOption view option

Directories ΒΆ

Path Synopsis
lru

Jump to

Keyboard shortcuts

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