Config GORM config AllowGlobalUpdate allow global update ClauseBuilders clause builder ConnPool db conn pool CreateBatchSize default create batch size Dialector database dialector DisableAutomaticPing DisableForeignKeyConstraintWhenMigrating DisableNestedTransaction disable nested transaction DryRun generate sql without execute FullSaveAssociations full save associations IgnoreRelationshipsWhenMigrating Logger NamingStrategy tables, columns naming strategy NowFunc the function to be used when creating a new timestamp Plugins registered plugins PrepareStmt executes the given query in cached statement QueryFields executes the SQL query with all fields of the table 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 TranslateError enabling error translation AfterInitialize initialize plugins after db connected Apply update config to new config( Config) BindVarTo(writer clause.Writer, stmt *Statement, v interface{})( Config) DataTypeOf(*schema.Field) string( Config) DefaultValueOf(*schema.Field) clause.Expression( Config) Explain(sql string, vars ...interface{}) string( Config) Initialize(*DB) error( Config) Migrator(db *DB) Migrator( Config) Name() string( Config) QuoteTo(clause.Writer, string)
Config : Dialector
*Config : Option
Config : Plugin
func (*Config).Apply(config *Config) error
func Option.Apply(*Config) error
func gorm.io/driver/mysql.Dialector.Apply(config *Config) error
DB GORM DB definitionConfig*Config AllowGlobalUpdate allow global update ClauseBuilders clause builder ConnPool db conn pool CreateBatchSize default create batch size Dialector database dialector DisableAutomaticPing DisableForeignKeyConstraintWhenMigrating DisableNestedTransaction disable nested transaction DryRun generate sql without execute FullSaveAssociations full save associations IgnoreRelationshipsWhenMigrating Logger NamingStrategy tables, columns naming strategy NowFunc the function to be used when creating a new timestamp Plugins registered plugins PrepareStmt executes the given query in cached statement QueryFields executes the SQL query with all fields of the table 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 TranslateError enabling error translationErrorerrorRowsAffectedint64Statement*Statement AddError add error to db AfterInitialize initialize plugins after db connected Apply update config to new config 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"}
[FirstOrCreate]: https://gorm.io/docs/advanced_query.html#FirstOrCreate
[FirstOrInit]: https://gorm.io/docs/advanced_query.html#FirstOrInit(*DB) Association(column string) *Association 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}
[FirstOrCreate]: https://gorm.io/docs/advanced_query.html#FirstOrCreate
[FirstOrInit]: https://gorm.io/docs/advanced_query.html#FirstOrInit AutoMigrate run auto migration for given models Begin begins a transaction with any transaction options opts( DB) BindVarTo(writer clause.Writer, stmt *Statement, v interface{}) Callback returns callback manager 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)
[docs]: https://gorm.io/docs/sql_builder.html#Clauses Commit commits the changes in a transaction Connection uses a db connection to execute an arbitrary number of commands in fc. When finished, the connection is
returned to the connection pool.(*DB) Count(count *int64) (tx *DB) Create inserts value, returning the inserted data's primary key in value's id CreateInBatches inserts value in batches of batchSize DB returns `*sql.DB`( DB) DataTypeOf(*schema.Field) string Debug start debug mode( DB) DefaultValueOf(*schema.Field) clause.Expression 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. 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) Exec executes raw sql( DB) Explain(sql string, vars ...interface{}) string Find finds all records matching given conditions conds FindInBatches finds all records in batches of batchSize First finds the first record ordered by primary key, matching given conditions conds 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 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"} Get get value with key from current db instance's context 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) 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)( DB) Initialize(*DB) error InnerJoins specify inner joins conditions
db.InnerJoins("Account").Find(&user) InstanceGet get value with key from current db instance's context InstanceSet store value with key into current db instance's context 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{})) Last finds the last record ordered by primary key, matching given conditions conds 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) Migrator returns migrator 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")( DB) Name() string 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) 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) Omit specify fields that you want to ignore when creating, updating and querying 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) Order specify order when retrieving records from database
db.Order("name DESC")
db.Order(clause.OrderByColumn{Column: clause.Column{Name: "name"}, Desc: true}) Pluck queries a single column from a model, returning in the slice dest. E.g.:
var ages []int64
db.Model(&users).Pluck("age", &ages) Preload preload associations with given conditions
// get all users, and preload all non-cancelled orders
db.Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users)( DB) QuoteTo(clause.Writer, string)(*DB) Raw(sql string, values ...interface{}) (tx *DB) Rollback rollbacks the changes in a transaction(*DB) RollbackTo(name string) *DB(*DB) Row() *sql.Row(*DB) Rows() (*sql.Rows, error) Save updates value in database. If value doesn't contain a matching primary key, value is inserted.(*DB) SavePoint(name string) *DB Scan scans selected value to the struct dest(*DB) ScanRows(rows *sql.Rows, dest interface{}) error 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) 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) Session create new db session Set store value with key into current db instance's context SetupJoinTable setup join table schema Table specify the table you would like to run db operations
// Get a user
db.Table("users").Take(&result) Take finds the first record returned by the database in no specified order, matching given conditions conds 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{})
}) 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.(*DB) Unscoped() (tx *DB) Update updates column with value using callbacks. Reference: https://gorm.io/docs/update.html#Update-Changed-Fields(*DB) UpdateColumn(column string, value interface{}) (tx *DB)(*DB) UpdateColumns(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 Use use plugin 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)
[docs]: https://gorm.io/docs/query.html#Conditions WithContext change current instance db's context to ctx
DB : Option
DB : Plugin
func Open(dialector Dialector, opts ...Option) (db *DB, err error)
func (*DB).Assign(attrs ...interface{}) (tx *DB)
func (*DB).Attrs(attrs ...interface{}) (tx *DB)
func (*DB).Begin(opts ...*sql.TxOptions) *DB
func (*DB).Clauses(conds ...clause.Expression) (tx *DB)
func (*DB).Commit() *DB
func (*DB).Count(count *int64) (tx *DB)
func (*DB).Create(value interface{}) (tx *DB)
func (*DB).CreateInBatches(value interface{}, batchSize int) (tx *DB)
func (*DB).Debug() (tx *DB)
func (*DB).Delete(value interface{}, conds ...interface{}) (tx *DB)
func (*DB).Distinct(args ...interface{}) (tx *DB)
func (*DB).Exec(sql string, values ...interface{}) (tx *DB)
func (*DB).Find(dest interface{}, conds ...interface{}) (tx *DB)
func (*DB).FindInBatches(dest interface{}, batchSize int, fc func(tx *DB, batch int) error) *DB
func (*DB).First(dest interface{}, conds ...interface{}) (tx *DB)
func (*DB).FirstOrCreate(dest interface{}, conds ...interface{}) (tx *DB)
func (*DB).FirstOrInit(dest interface{}, conds ...interface{}) (tx *DB)
func (*DB).Group(name string) (tx *DB)
func (*DB).Having(query interface{}, args ...interface{}) (tx *DB)
func (*DB).InnerJoins(query string, args ...interface{}) (tx *DB)
func (*DB).InstanceSet(key string, value interface{}) *DB
func (*DB).Joins(query string, args ...interface{}) (tx *DB)
func (*DB).Last(dest interface{}, conds ...interface{}) (tx *DB)
func (*DB).Limit(limit int) (tx *DB)
func (*DB).Model(value interface{}) (tx *DB)
func (*DB).Not(query interface{}, args ...interface{}) (tx *DB)
func (*DB).Offset(offset int) (tx *DB)
func (*DB).Omit(columns ...string) (tx *DB)
func (*DB).Or(query interface{}, args ...interface{}) (tx *DB)
func (*DB).Order(value interface{}) (tx *DB)
func (*DB).Pluck(column string, dest interface{}) (tx *DB)
func (*DB).Preload(query string, args ...interface{}) (tx *DB)
func (*DB).Raw(sql string, values ...interface{}) (tx *DB)
func (*DB).Rollback() *DB
func (*DB).RollbackTo(name string) *DB
func (*DB).Save(value interface{}) (tx *DB)
func (*DB).SavePoint(name string) *DB
func (*DB).Scan(dest interface{}) (tx *DB)
func (*DB).Scopes(funcs ...func(*DB) *DB) (tx *DB)
func (*DB).Select(query interface{}, args ...interface{}) (tx *DB)
func (*DB).Session(config *Session) *DB
func (*DB).Set(key string, value interface{}) *DB
func (*DB).Table(name string, args ...interface{}) (tx *DB)
func (*DB).Take(dest interface{}, conds ...interface{}) (tx *DB)
func (*DB).Unscoped() (tx *DB)
func (*DB).Update(column string, value interface{}) (tx *DB)
func (*DB).UpdateColumn(column string, value interface{}) (tx *DB)
func (*DB).UpdateColumns(values interface{}) (tx *DB)
func (*DB).Updates(values interface{}) (tx *DB)
func (*DB).Where(query interface{}, args ...interface{}) (tx *DB)
func (*DB).WithContext(ctx context.Context) *DB
func github.com/limanmys/render-engine/internal/database.Connection() *DB
func Scan(rows Rows, db *DB, mode ScanMode)
func (*Config).AfterInitialize(db *DB) error
func Dialector.Initialize(*DB) error
func Dialector.Migrator(db *DB) Migrator
func Option.AfterInitialize(*DB) error
func Plugin.Initialize(*DB) error
func SavePointerDialectorInterface.RollbackTo(tx *DB, name string) error
func SavePointerDialectorInterface.SavePoint(tx *DB, name string) error
func Valuer.GormValue(context.Context, *DB) clause.Expr
func gorm.io/gorm/callbacks.AfterCreate(db *DB)
func gorm.io/gorm/callbacks.AfterDelete(db *DB)
func gorm.io/gorm/callbacks.AfterQuery(db *DB)
func gorm.io/gorm/callbacks.AfterUpdate(db *DB)
func gorm.io/gorm/callbacks.BeforeCreate(db *DB)
func gorm.io/gorm/callbacks.BeforeDelete(db *DB)
func gorm.io/gorm/callbacks.BeforeUpdate(db *DB)
func gorm.io/gorm/callbacks.BeginTransaction(db *DB)
func gorm.io/gorm/callbacks.BuildQuerySQL(db *DB)
func gorm.io/gorm/callbacks.CommitOrRollbackTransaction(db *DB)
func gorm.io/gorm/callbacks.DeleteBeforeAssociations(db *DB)
func gorm.io/gorm/callbacks.Preload(db *DB)
func gorm.io/gorm/callbacks.Query(db *DB)
func gorm.io/gorm/callbacks.RawExec(db *DB)
func gorm.io/gorm/callbacks.RegisterDefaultCallbacks(db *DB, config *callbacks.Config)
func gorm.io/gorm/callbacks.RowQuery(db *DB)
func gorm.io/gorm/callbacks.SetupUpdateReflectValue(db *DB)
func gorm.io/gorm/callbacks.AfterCreateInterface.AfterCreate(*DB) error
func gorm.io/gorm/callbacks.AfterDeleteInterface.AfterDelete(*DB) error
func gorm.io/gorm/callbacks.AfterFindInterface.AfterFind(*DB) error
func gorm.io/gorm/callbacks.AfterSaveInterface.AfterSave(*DB) error
func gorm.io/gorm/callbacks.AfterUpdateInterface.AfterUpdate(*DB) error
func gorm.io/gorm/callbacks.BeforeCreateInterface.BeforeCreate(*DB) error
func gorm.io/gorm/callbacks.BeforeDeleteInterface.BeforeDelete(*DB) error
func gorm.io/gorm/callbacks.BeforeSaveInterface.BeforeSave(*DB) error
func gorm.io/gorm/callbacks.BeforeUpdateInterface.BeforeUpdate(*DB) error
func gorm.io/gorm/migrator.GormDataTypeInterface.GormDBDataType(*DB, *schema.Field) string
func gorm.io/driver/mysql.Dialector.Initialize(db *DB) (err error)
func gorm.io/driver/mysql.Dialector.Migrator(db *DB) Migrator
func gorm.io/driver/mysql.Dialector.RollbackTo(tx *DB, name string) error
func gorm.io/driver/mysql.Dialector.SavePoint(tx *DB, name string) error
func gorm.io/driver/postgres.Dialector.Initialize(db *DB) (err error)
func gorm.io/driver/postgres.Dialector.Migrator(db *DB) Migrator
func gorm.io/driver/postgres.Dialector.RollbackTo(tx *DB, name string) error
func gorm.io/driver/postgres.Dialector.SavePoint(tx *DB, name string) error
func gorm.io/driver/postgres.Migrator.CreateSequence(tx *DB, stmt *Statement, field *schema.Field, serialDatabaseType string) (err error)
func gorm.io/driver/postgres.Migrator.DeleteSequence(tx *DB, stmt *Statement, field *schema.Field, fileType clause.Expr) (err error)
func gorm.io/driver/postgres.Migrator.UpdateSequence(tx *DB, stmt *Statement, field *schema.Field, serialDatabaseType string) (err error)
func github.com/limanmys/render-engine/app/models.(*Queue).BeforeCreate(tx *DB) (err error)
func github.com/limanmys/render-engine/app/models.(*Queue).BeforeUpdate(tx *DB) (err error)
func github.com/limanmys/render-engine/app/models.(*Settings).BeforeCreate(tx *DB) error
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
}CreatedAttime.TimeDeletedAtDeletedAtIDuintUpdatedAttime.Time
Statement statementBuildClauses[]stringClausesmap[string]clause.ClauseConnPoolConnPoolContextcontext.ContextCurDestIndexintDB*DBDB.Config*Config AllowGlobalUpdate allow global update ClauseBuilders clause builder CreateBatchSize default create batch size Dialector database dialector DisableAutomaticPing DisableForeignKeyConstraintWhenMigrating DisableNestedTransaction disable nested transaction DryRun generate sql without execute FullSaveAssociations full save associations IgnoreRelationshipsWhenMigrating Logger NamingStrategy tables, columns naming strategy NowFunc the function to be used when creating a new timestamp Plugins registered plugins PrepareStmt executes the given query in cached statement QueryFields executes the SQL query with all fields of the table 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 TranslateError enabling error translationDB.ErrorerrorDB.RowsAffectedint64DB.Statement*StatementDestinterface{}DistinctboolJoins[]joinModelinterface{} // omit columnsPreloadsmap[string][]interface{}RaiseErrorOnNotFoundboolReflectValuereflect.ValueSQLstrings.BuilderSchema*schema.Schema // selected columnsSettingssync.MapSkipHooksboolTablestringTableExpr*clause.ExprUnscopedboolVars[]interface{} AddClause add clause AddClauseIfNotExists add clause if not exists AddError add error to db AddVar add var AfterInitialize initialize plugins after db connected Apply update config to new config 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"}
[FirstOrCreate]: https://gorm.io/docs/advanced_query.html#FirstOrCreate
[FirstOrInit]: https://gorm.io/docs/advanced_query.html#FirstOrInit( Statement) Association(column string) *Association 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}
[FirstOrCreate]: https://gorm.io/docs/advanced_query.html#FirstOrCreate
[FirstOrInit]: https://gorm.io/docs/advanced_query.html#FirstOrInit AutoMigrate run auto migration for given models Begin begins a transaction with any transaction options opts( Statement) BindVarTo(writer clause.Writer, stmt *Statement, v interface{}) Build build sql with clauses names BuildCondition build condition Callback returns callback manager Changed check model changed or not when updating Commit commits the changes in a transaction Connection uses a db connection to execute an arbitrary number of commands in fc. When finished, the connection is
returned to the connection pool.( Statement) Count(count *int64) (tx *DB) Create inserts value, returning the inserted data's primary key in value's id CreateInBatches inserts value in batches of batchSize( Statement) DataTypeOf(*schema.Field) string Debug start debug mode( Statement) DefaultValueOf(*schema.Field) clause.Expression 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. Exec executes raw sql( Statement) Explain(sql string, vars ...interface{}) string Find finds all records matching given conditions conds FindInBatches finds all records in batches of batchSize First finds the first record ordered by primary key, matching given conditions conds 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 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"} Get get value with key from current db instance's context 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) 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)( Statement) Initialize(*DB) error InnerJoins specify inner joins conditions
db.InnerJoins("Account").Find(&user) InstanceGet get value with key from current db instance's context InstanceSet store value with key into current db instance's context Last finds the last record ordered by primary key, matching given conditions conds 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) Migrator returns migrator( Statement) Name() string 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) 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) Omit specify fields that you want to ignore when creating, updating and querying 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) Order specify order when retrieving records from database
db.Order("name DESC")
db.Order(clause.OrderByColumn{Column: clause.Column{Name: "name"}, Desc: true})(*Statement) Parse(value interface{}) (err error)(*Statement) ParseWithSpecialTableName(value interface{}, specialTableName string) (err error) Pluck queries a single column from a model, returning in the slice dest. E.g.:
var ages []int64
db.Model(&users).Pluck("age", &ages) Preload preload associations with given conditions
// get all users, and preload all non-cancelled orders
db.Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users) Quote returns quoted value QuoteTo write quoted value to writer( Statement) Raw(sql string, values ...interface{}) (tx *DB) Rollback rollbacks the changes in a transaction( Statement) RollbackTo(name string) *DB( Statement) Row() *sql.Row( Statement) Rows() (*sql.Rows, error) Save updates value in database. If value doesn't contain a matching primary key, value is inserted.( Statement) SavePoint(name string) *DB Scan scans selected value to the struct dest( Statement) ScanRows(rows *sql.Rows, dest interface{}) error 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) 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) SelectAndOmitColumns get select and omit columns, select -> true, omit -> false Session create new db session Set store value with key into current db instance's context SetColumn set column's value
stmt.SetColumn("Name", "jinzhu") // Hooks Method
stmt.SetColumn("Name", "jinzhu", true) // Callbacks Method SetupJoinTable setup join table schema Take finds the first record returned by the database in no specified order, matching given conditions conds 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{})
}) 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. Update updates column with value using callbacks. Reference: https://gorm.io/docs/update.html#Update-Changed-Fields( Statement) UpdateColumn(column string, value interface{}) (tx *DB)( Statement) UpdateColumns(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 Use use plugin 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)
[docs]: https://gorm.io/docs/query.html#Conditions WithContext change current instance db's context to ctx WriteByte write byte WriteQuoted write quoted value WriteString write string
Statement : Option
Statement : Plugin
*Statement : gorm.io/gorm/clause.Builder
*Statement : gorm.io/gorm/clause.Writer
*Statement : io.ByteWriter
*Statement : io.StringWriter
func Dialector.BindVarTo(writer clause.Writer, stmt *Statement, v interface{})
func SoftDeleteDeleteClause.ModifyStatement(stmt *Statement)
func SoftDeleteQueryClause.ModifyStatement(stmt *Statement)
func SoftDeleteUpdateClause.ModifyStatement(stmt *Statement)
func StatementModifier.ModifyStatement(*Statement)
func gorm.io/gorm/callbacks.ConvertMapToValuesForCreate(stmt *Statement, mapValue map[string]interface{}) (values clause.Values)
func gorm.io/gorm/callbacks.ConvertSliceOfMapToValuesForCreate(stmt *Statement, mapValues []map[string]interface{}) (values clause.Values)
func gorm.io/gorm/callbacks.ConvertToAssignments(stmt *Statement) (set clause.Set)
func gorm.io/gorm/callbacks.ConvertToCreateValues(stmt *Statement) (values clause.Values)
func gorm.io/gorm/migrator.BuildIndexOptionsInterface.BuildIndexOptions([]schema.IndexOption, *Statement) []interface{}
func gorm.io/gorm/migrator.Migrator.BuildIndexOptions(opts []schema.IndexOption, stmt *Statement) (results []interface{})
func gorm.io/gorm/migrator.Migrator.CurrentTable(stmt *Statement) interface{}
func gorm.io/gorm/migrator.Migrator.GuessConstraintAndTable(stmt *Statement, name string) (_ *schema.Constraint, _ *schema.Check, table string)
func gorm.io/driver/mysql.Dialector.BindVarTo(writer clause.Writer, stmt *Statement, v interface{})
func gorm.io/driver/mysql.Migrator.CurrentSchema(stmt *Statement, table string) (string, string)
func gorm.io/driver/postgres.Dialector.BindVarTo(writer clause.Writer, stmt *Statement, v interface{})
func gorm.io/driver/postgres.Migrator.BuildIndexOptions(opts []schema.IndexOption, stmt *Statement) (results []interface{})
func gorm.io/driver/postgres.Migrator.CreateSequence(tx *DB, stmt *Statement, field *schema.Field, serialDatabaseType string) (err error)
func gorm.io/driver/postgres.Migrator.CurrentSchema(stmt *Statement, table string) (interface{}, interface{})
func gorm.io/driver/postgres.Migrator.DeleteSequence(tx *DB, stmt *Statement, field *schema.Field, fileType clause.Expr) (err error)
func gorm.io/driver/postgres.Migrator.UpdateSequence(tx *DB, stmt *Statement, field *schema.Field, serialDatabaseType string) (err error)
Stmt*sql.StmtTransactionbool Close closes the statement. Exec executes a prepared statement with the given arguments and
returns a Result summarizing the effect of the statement.
Exec uses context.Background internally; to specify the context, use
ExecContext. ExecContext executes a prepared statement with the given arguments and
returns a Result summarizing the effect of the statement. Query executes a prepared query statement with the given arguments
and returns the query results as a *Rows.
Query uses context.Background internally; to specify the context, use
QueryContext. QueryContext executes a prepared query statement with the given arguments
and returns the query results as a *Rows. QueryRow executes a prepared query statement with the given arguments.
If an error occurs during the execution of the statement, that error will
be returned by a call to Scan on the returned *Row, which is always non-nil.
If the query selects no rows, the *Row's Scan will return ErrNoRows.
Otherwise, the *Row's Scan scans the first selected row and discards
the rest.
Example usage:
var name string
err := nameByUseridStmt.QueryRow(id).Scan(&name)
QueryRow uses context.Background internally; to specify the context, use
QueryRowContext. QueryRowContext executes a prepared query statement with the given arguments.
If an error occurs during the execution of the statement, that error will
be returned by a call to Scan on the returned *Row, which is always non-nil.
If the query selects no rows, the *Row's Scan will return ErrNoRows.
Otherwise, the *Row's Scan scans the first selected row and discards
the rest.
Stmt : io.Closer
ErrDuplicatedKey occurs when there is a unique key constraint violation
ErrEmptySlice empty slice found
ErrForeignKeyViolated occurs when there is a foreign key constraint violation
ErrInvalidData unsupported data
ErrInvalidDB invalid db
ErrInvalidField invalid field
ErrInvalidTransaction invalid transaction when you are trying to `Commit` or `Rollback`
ErrInvalidValue invalid value
ErrInvalidValueOfLength invalid values do not match length
ErrMissingWhereClause missing where clause
ErrModelAccessibleFieldsRequired model accessible fields required
ErrModelValueRequired model value required
ErrNotImplemented not implemented
ErrPreloadNotAllowed preload is not allowed when count is used
ErrPrimaryKeyRequired primary keys required
ErrRecordNotFound record not found error
ErrRegistered registered
ErrSubQueryRequired sub query required
ErrUnsupportedDriver unsupported driver
ErrUnsupportedRelation unsupported relations
Package-Level Constants (total 3)
scan modes
scan modes
scan modes
The pages are generated with Goldsv0.6.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds.