package gorm

Import Path
	gorm.io/gorm (on go.dev)

Dependency Relation
	imports 20 packages, and imported by 6 packages


Package-Level Type Names (total 41)
/* sort by: | */
Association Mode contains some helper methods to handle relationship things easily. DB *DB Error error Relationship *schema.Relationship Unscope bool (*Association) Append(values ...interface{}) error (*Association) Clear() error (*Association) Count() (count int64) (*Association) Delete(values ...interface{}) error (*Association) Find(out interface{}, conds ...interface{}) error (*Association) Replace(values ...interface{}) error (*Association) Unscoped() *Association func (*Association).Unscoped() *Association func (*DB).Association(column string) *Association
Type Parameters: T: any ( ChainInterface[T]) Build(builder clause.Builder) ( ChainInterface[T]) Count(ctx context.Context, column string) (result int64, err error) ( ChainInterface[T]) Delete(ctx context.Context) (rowsAffected int, err error) ( ChainInterface[T]) Distinct(args ...interface{}) ChainInterface[T] ( ChainInterface[T]) Find(ctx context.Context) ([]T, error) ( ChainInterface[T]) FindInBatches(ctx context.Context, batchSize int, fc func(data []T, batch int) error) error ( ChainInterface[T]) First(context.Context) (T, error) ( ChainInterface[T]) Group(name string) ChainInterface[T] ( ChainInterface[T]) Having(query interface{}, args ...interface{}) ChainInterface[T] ( ChainInterface[T]) Joins(query clause.JoinTarget, on func(db JoinBuilder, joinTable clause.Table, curTable clause.Table) error) ChainInterface[T] ( ChainInterface[T]) Last(ctx context.Context) (T, error) ( ChainInterface[T]) Limit(offset int) ChainInterface[T] ( ChainInterface[T]) MapColumns(m map[string]string) ChainInterface[T] ( ChainInterface[T]) Not(query interface{}, args ...interface{}) ChainInterface[T] ( ChainInterface[T]) Offset(offset int) ChainInterface[T] ( ChainInterface[T]) Omit(columns ...string) ChainInterface[T] ( ChainInterface[T]) Or(query interface{}, args ...interface{}) ChainInterface[T] ( ChainInterface[T]) Order(value interface{}) ChainInterface[T] ( ChainInterface[T]) Preload(association string, query func(db PreloadBuilder) error) ChainInterface[T] ( ChainInterface[T]) Row(ctx context.Context) *sql.Row ( ChainInterface[T]) Rows(ctx context.Context) (*sql.Rows, error) ( ChainInterface[T]) Scan(ctx context.Context, r interface{}) error ( ChainInterface[T]) Scopes(scopes ...func(db *Statement)) ChainInterface[T] ( ChainInterface[T]) Select(query string, args ...interface{}) ChainInterface[T] ( ChainInterface[T]) Set(assignments ...clause.Assigner) SetUpdateOnlyInterface[T] ( ChainInterface[T]) Table(name string, args ...interface{}) ChainInterface[T] ( ChainInterface[T]) Take(context.Context) (T, error) ( ChainInterface[T]) Update(ctx context.Context, name string, value any) (rowsAffected int, err error) ( ChainInterface[T]) Updates(ctx context.Context, t T) (rowsAffected int, err error) ( ChainInterface[T]) Where(query interface{}, args ...interface{}) ChainInterface[T] ChainInterface : ExecInterface[T] ChainInterface : gorm.io/gorm/clause.Expression func ChainInterface[T].Distinct(args ...interface{}) ChainInterface[T] func ChainInterface[T].Group(name string) ChainInterface[T] func ChainInterface[T].Having(query interface{}, args ...interface{}) ChainInterface[T] func ChainInterface[T].Joins(query clause.JoinTarget, on func(db JoinBuilder, joinTable clause.Table, curTable clause.Table) error) ChainInterface[T] func ChainInterface[T].Limit(offset int) ChainInterface[T] func ChainInterface[T].MapColumns(m map[string]string) ChainInterface[T] func ChainInterface[T].Not(query interface{}, args ...interface{}) ChainInterface[T] func ChainInterface[T].Offset(offset int) ChainInterface[T] func ChainInterface[T].Omit(columns ...string) ChainInterface[T] func ChainInterface[T].Or(query interface{}, args ...interface{}) ChainInterface[T] func ChainInterface[T].Order(value interface{}) ChainInterface[T] func ChainInterface[T].Preload(association string, query func(db PreloadBuilder) error) ChainInterface[T] func ChainInterface[T].Scopes(scopes ...func(db *Statement)) ChainInterface[T] func ChainInterface[T].Select(query string, args ...interface{}) ChainInterface[T] func ChainInterface[T].Table(name string, args ...interface{}) ChainInterface[T] func ChainInterface[T].Where(query interface{}, args ...interface{}) ChainInterface[T] func CreateInterface[T].Distinct(args ...interface{}) ChainInterface[T] func CreateInterface[T].Group(name string) ChainInterface[T] func CreateInterface[T].Having(query interface{}, args ...interface{}) ChainInterface[T] func CreateInterface[T].Joins(query clause.JoinTarget, on func(db JoinBuilder, joinTable clause.Table, curTable clause.Table) error) ChainInterface[T] func CreateInterface[T].Limit(offset int) ChainInterface[T] func CreateInterface[T].MapColumns(m map[string]string) ChainInterface[T] func CreateInterface[T].Not(query interface{}, args ...interface{}) ChainInterface[T] func CreateInterface[T].Offset(offset int) ChainInterface[T] func CreateInterface[T].Omit(columns ...string) ChainInterface[T] func CreateInterface[T].Or(query interface{}, args ...interface{}) ChainInterface[T] func CreateInterface[T].Order(value interface{}) ChainInterface[T] func CreateInterface[T].Preload(association string, query func(db PreloadBuilder) error) ChainInterface[T] func CreateInterface[T].Scopes(scopes ...func(db *Statement)) ChainInterface[T] func CreateInterface[T].Select(query string, args ...interface{}) ChainInterface[T] func CreateInterface[T].Where(query interface{}, args ...interface{}) ChainInterface[T] func Interface[T].Distinct(args ...interface{}) ChainInterface[T] func Interface[T].Group(name string) ChainInterface[T] func Interface[T].Having(query interface{}, args ...interface{}) ChainInterface[T] func Interface[T].Joins(query clause.JoinTarget, on func(db JoinBuilder, joinTable clause.Table, curTable clause.Table) error) ChainInterface[T] func Interface[T].Limit(offset int) ChainInterface[T] func Interface[T].MapColumns(m map[string]string) ChainInterface[T] func Interface[T].Not(query interface{}, args ...interface{}) ChainInterface[T] func Interface[T].Offset(offset int) ChainInterface[T] func Interface[T].Omit(columns ...string) ChainInterface[T] func Interface[T].Or(query interface{}, args ...interface{}) ChainInterface[T] func Interface[T].Order(value interface{}) ChainInterface[T] func Interface[T].Preload(association string, query func(db PreloadBuilder) error) ChainInterface[T] func Interface[T].Scopes(scopes ...func(db *Statement)) ChainInterface[T] func Interface[T].Select(query string, args ...interface{}) ChainInterface[T] func Interface[T].Where(query interface{}, args ...interface{}) ChainInterface[T]
ColumnType column type interface ( ColumnType) AutoIncrement() (isAutoIncrement bool, ok bool) // varchar(64) ( ColumnType) Comment() (value string, ok bool) // varchar ( ColumnType) DecimalSize() (precision int64, scale int64, ok bool) ( ColumnType) DefaultValue() (value string, ok bool) ( ColumnType) Length() (length int64, ok bool) ( ColumnType) Name() string ( ColumnType) Nullable() (nullable bool, ok bool) ( ColumnType) PrimaryKey() (isPrimaryKey bool, ok bool) ( ColumnType) ScanType() reflect.Type ( ColumnType) Unique() (unique bool, ok bool) gorm.io/gorm/migrator.ColumnType ColumnType : github.com/polarsignals/frostdb/query/logicalplan.Named func Migrator.ColumnTypes(dst interface{}) ([]ColumnType, error) func gorm.io/gorm/migrator.Migrator.ColumnTypes(value interface{}) ([]ColumnType, error) func gorm.io/driver/mysql.Migrator.ColumnTypes(value interface{}) ([]ColumnType, error) func Migrator.MigrateColumn(dst interface{}, field *schema.Field, columnType ColumnType) error func Migrator.MigrateColumnUnique(dst interface{}, field *schema.Field, columnType ColumnType) error func gorm.io/gorm/migrator.Migrator.MigrateColumn(value interface{}, field *schema.Field, columnType ColumnType) error func gorm.io/gorm/migrator.Migrator.MigrateColumnUnique(value interface{}, field *schema.Field, columnType ColumnType) error func gorm.io/driver/mysql.Migrator.MigrateColumnUnique(value interface{}, field *schema.Field, columnType ColumnType) error
Config GORM config AllowGlobalUpdate allow global update ClauseBuilders clause builder ConnPool db conn pool CreateBatchSize default create batch size DefaultContextTimeout time.Duration DefaultTransactionTimeout time.Duration 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 PrepareStmt cache support LRU expired, default maxsize=int64 Max value and ttl=1h PrepareStmtTTL time.Duration PropagateUnscoped propagate Unscoped to every other nested 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 Config : github.com/polarsignals/frostdb/query/logicalplan.Named func (*Config).Apply(config *Config) error func Option.Apply(*Config) error func gorm.io/driver/mysql.Dialector.Apply(config *Config) error
ConnPool db conns pool interface ( ConnPool) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) ( ConnPool) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) ( ConnPool) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) ( ConnPool) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row *PreparedStmtDB *PreparedStmtTX Tx (interface) *database/sql.Conn *database/sql.DB *database/sql.Tx ConnPool : gorm.io/gorm/internal/stmt_store.ConnPool func ConnPoolBeginner.BeginTx(ctx context.Context, opts *sql.TxOptions) (ConnPool, error) func (*PreparedStmtDB).BeginTx(ctx context.Context, opt *sql.TxOptions) (ConnPool, error) func NewPreparedStmtDB(connPool ConnPool, maxSize int, ttl time.Duration) *PreparedStmtDB func github.com/ncruces/go-sqlite3/gormlite.OpenDB(db ConnPool) Dialector
ConnPoolBeginner conn pool beginner ( ConnPoolBeginner) BeginTx(ctx context.Context, opts *sql.TxOptions) (ConnPool, error) *PreparedStmtDB
Type Parameters: T: any ( CreateInterface[T]) Build(builder clause.Builder) ( CreateInterface[T]) Count(ctx context.Context, column string) (result int64, err error) ( CreateInterface[T]) Create(ctx context.Context, r *T) error ( CreateInterface[T]) CreateInBatches(ctx context.Context, r *[]T, batchSize int) error ( CreateInterface[T]) Delete(ctx context.Context) (rowsAffected int, err error) ( CreateInterface[T]) Distinct(args ...interface{}) ChainInterface[T] ( CreateInterface[T]) Find(ctx context.Context) ([]T, error) ( CreateInterface[T]) FindInBatches(ctx context.Context, batchSize int, fc func(data []T, batch int) error) error ( CreateInterface[T]) First(context.Context) (T, error) ( CreateInterface[T]) Group(name string) ChainInterface[T] ( CreateInterface[T]) Having(query interface{}, args ...interface{}) ChainInterface[T] ( CreateInterface[T]) Joins(query clause.JoinTarget, on func(db JoinBuilder, joinTable clause.Table, curTable clause.Table) error) ChainInterface[T] ( CreateInterface[T]) Last(ctx context.Context) (T, error) ( CreateInterface[T]) Limit(offset int) ChainInterface[T] ( CreateInterface[T]) MapColumns(m map[string]string) ChainInterface[T] ( CreateInterface[T]) Not(query interface{}, args ...interface{}) ChainInterface[T] ( CreateInterface[T]) Offset(offset int) ChainInterface[T] ( CreateInterface[T]) Omit(columns ...string) ChainInterface[T] ( CreateInterface[T]) Or(query interface{}, args ...interface{}) ChainInterface[T] ( CreateInterface[T]) Order(value interface{}) ChainInterface[T] ( CreateInterface[T]) Preload(association string, query func(db PreloadBuilder) error) ChainInterface[T] ( CreateInterface[T]) Row(ctx context.Context) *sql.Row ( CreateInterface[T]) Rows(ctx context.Context) (*sql.Rows, error) ( CreateInterface[T]) Scan(ctx context.Context, r interface{}) error chain methods available at start; return ChainInterface ( CreateInterface[T]) Select(query string, args ...interface{}) ChainInterface[T] ( CreateInterface[T]) Set(assignments ...clause.Assigner) SetCreateOrUpdateInterface[T] ( CreateInterface[T]) Table(name string, args ...interface{}) CreateInterface[T] ( CreateInterface[T]) Take(context.Context) (T, error) ( CreateInterface[T]) Update(ctx context.Context, name string, value any) (rowsAffected int, err error) ( CreateInterface[T]) Updates(ctx context.Context, t T) (rowsAffected int, err error) ( CreateInterface[T]) Where(query interface{}, args ...interface{}) ChainInterface[T] CreateInterface : ExecInterface[T] CreateInterface : gorm.io/gorm/clause.Expression func CreateInterface[T].Table(name string, args ...interface{}) CreateInterface[T] func Interface[T].Table(name string, args ...interface{}) CreateInterface[T]
DB GORM DB definition Config *Config AllowGlobalUpdate allow global update ClauseBuilders clause builder ConnPool db conn pool CreateBatchSize default create batch size Config.DefaultContextTimeout time.Duration Config.DefaultTransactionTimeout time.Duration 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 PrepareStmt cache support LRU expired, default maxsize=int64 Max value and ttl=1h Config.PrepareStmtTTL time.Duration PropagateUnscoped propagate Unscoped to every other nested 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 Error error RowsAffected int64 Statement *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"} (*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} 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) 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) MapColumns modify the column names in the query results to facilitate align to the corresponding structural fields 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}) db.Order(clause.OrderBy{Columns: []clause.OrderByColumn{ {Column: clause.Column{Name: "name"}, Desc: true}, {Column: clause.Column{Name: "age"}, 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. 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. 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) WithContext change current instance db's context to ctx DB : Option DB : Plugin DB : github.com/polarsignals/frostdb/query/logicalplan.Named 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).MapColumns(m map[string]string) (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 gorm.io/gorm/migrator.Migrator.GetQueryAndExecTx() (queryTx, execTx *DB) func github.com/pancsta/asyncmachine-go/pkg/history/gorm.NewSqlite(name string, debug bool) (*DB, *sql.DB, error) func github.com/pancsta/asyncmachine-go/pkg/history/gorm.(*Memory).JoinState(query *DB, name string) *DB func github.com/pancsta/asyncmachine-go/pkg/history/gorm.(*Memory).JoinTransition(query *DB) *DB func G[T](db *DB, opts ...clause.Expression) Interface[T] 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/datatypes.BinUUID.GormDBDataType(db *DB, field *schema.Field) string func gorm.io/datatypes.JSON.GormDBDataType(db *DB, field *schema.Field) string func gorm.io/datatypes.JSON.GormValue(ctx context.Context, db *DB) clause.Expr func gorm.io/datatypes.JSONMap.GormDBDataType(db *DB, field *schema.Field) string func gorm.io/datatypes.JSONMap.GormValue(ctx context.Context, db *DB) clause.Expr func gorm.io/datatypes.JSONSlice[T].GormDBDataType(db *DB, field *schema.Field) string func gorm.io/datatypes.JSONSlice[T].GormValue(ctx context.Context, db *DB) clause.Expr func gorm.io/datatypes.JSONType[T].GormDBDataType(db *DB, field *schema.Field) string func gorm.io/datatypes.JSONType[T].GormValue(ctx context.Context, db *DB) clause.Expr func gorm.io/datatypes.Time.GormDBDataType(db *DB, field *schema.Field) string func gorm.io/datatypes.URL.GormDBDataType(db *DB, field *schema.Field) string func gorm.io/datatypes.UUID.GormDBDataType(db *DB, field *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 github.com/pancsta/asyncmachine-go/pkg/history/gorm.GetMachine(db *DB, id string, inclStates bool) (*gorm.Machine, error) func github.com/pancsta/asyncmachine-go/pkg/history/gorm.ListMachines(db *DB) ([]*amhist.MachineRecord, error) func github.com/pancsta/asyncmachine-go/pkg/history/gorm.NewMemory(ctx context.Context, db *DB, mach am.Api, cfg gorm.Config, onErr func(err error)) (*gorm.Memory, error) func github.com/pancsta/asyncmachine-go/pkg/history/gorm.(*Memory).JoinState(query *DB, name string) *DB func github.com/pancsta/asyncmachine-go/pkg/history/gorm.(*Memory).JoinTransition(query *DB) *DB
Time time.Time // Valid is true if Time is not NULL ( DeletedAt) DeleteClauses(f *schema.Field) []clause.Interface ( DeletedAt) MarshalJSON() ([]byte, error) ( DeletedAt) QueryClauses(f *schema.Field) []clause.Interface Scan implements the Scanner interface. (*DeletedAt) UnmarshalJSON(b []byte) error ( DeletedAt) UpdateClauses(f *schema.Field) []clause.Interface Value implements the driver Valuer interface. DeletedAt : gorm.io/gorm/schema.DeleteClausesInterface DeletedAt : gorm.io/gorm/schema.QueryClausesInterface DeletedAt : gorm.io/gorm/schema.UpdateClausesInterface *DeletedAt : database/sql.Scanner DeletedAt : database/sql/driver.Valuer DeletedAt : encoding/json.Marshaler *DeletedAt : encoding/json.Unmarshaler DeletedAt : github.com/goccy/go-json.Marshaler *DeletedAt : github.com/goccy/go-json.Unmarshaler
Dialector GORM database dialector ( Dialector) BindVarTo(writer clause.Writer, stmt *Statement, v interface{}) ( Dialector) DataTypeOf(*schema.Field) string ( Dialector) DefaultValueOf(*schema.Field) clause.Expression ( Dialector) Explain(sql string, vars ...interface{}) string ( Dialector) Initialize(*DB) error ( Dialector) Migrator(db *DB) Migrator ( Dialector) Name() string ( Dialector) QuoteTo(clause.Writer, string) Config gorm.io/gorm/migrator.Config gorm.io/gorm/migrator.Migrator gorm.io/driver/mysql.Dialector Dialector : Plugin Dialector : github.com/polarsignals/frostdb/query/logicalplan.Named func gorm.io/driver/mysql.New(config mysql.Config) Dialector func gorm.io/driver/mysql.Open(dsn string) Dialector func github.com/ncruces/go-sqlite3/gormlite.Open(dsn string) Dialector func github.com/ncruces/go-sqlite3/gormlite.OpenDB(db ConnPool) Dialector func Open(dialector Dialector, opts ...Option) (db *DB, err error)
( ErrorTranslator) Translate(err error) error gorm.io/driver/mysql.Dialector gorm.io/driver/mysql.Migrator
Type Parameters: T: any ( ExecInterface[T]) Find(ctx context.Context) ([]T, error) ( ExecInterface[T]) FindInBatches(ctx context.Context, batchSize int, fc func(data []T, batch int) error) error ( ExecInterface[T]) First(context.Context) (T, error) ( ExecInterface[T]) Last(ctx context.Context) (T, error) ( ExecInterface[T]) Row(ctx context.Context) *sql.Row ( ExecInterface[T]) Rows(ctx context.Context) (*sql.Rows, error) ( ExecInterface[T]) Scan(ctx context.Context, r interface{}) error ( ExecInterface[T]) Take(context.Context) (T, error) func Interface[T].Raw(sql string, values ...interface{}) ExecInterface[T]
GetDBConnector SQL db connector ( GetDBConnector) GetDBConn() (*sql.DB, error) *PreparedStmtDB *PreparedStmtTX
( Index) Columns() []string ( Index) Name() string ( Index) Option() string ( Index) PrimaryKey() (isPrimaryKey bool, ok bool) ( Index) Table() string ( Index) Unique() (unique bool, ok bool) gorm.io/gorm/migrator.Index Index : github.com/polarsignals/frostdb/query/logicalplan.Named func Migrator.GetIndexes(dst interface{}) ([]Index, error) func gorm.io/gorm/migrator.Migrator.GetIndexes(dst interface{}) ([]Index, error) func gorm.io/driver/mysql.Migrator.GetIndexes(value interface{}) ([]Index, error)
Type Parameters: T: any ( Interface[T]) Build(builder clause.Builder) ( Interface[T]) Count(ctx context.Context, column string) (result int64, err error) ( Interface[T]) Create(ctx context.Context, r *T) error ( Interface[T]) CreateInBatches(ctx context.Context, r *[]T, batchSize int) error ( Interface[T]) Delete(ctx context.Context) (rowsAffected int, err error) ( Interface[T]) Distinct(args ...interface{}) ChainInterface[T] ( Interface[T]) Exec(ctx context.Context, sql string, values ...interface{}) error ( Interface[T]) Find(ctx context.Context) ([]T, error) ( Interface[T]) FindInBatches(ctx context.Context, batchSize int, fc func(data []T, batch int) error) error ( Interface[T]) First(context.Context) (T, error) ( Interface[T]) Group(name string) ChainInterface[T] ( Interface[T]) Having(query interface{}, args ...interface{}) ChainInterface[T] ( Interface[T]) Joins(query clause.JoinTarget, on func(db JoinBuilder, joinTable clause.Table, curTable clause.Table) error) ChainInterface[T] ( Interface[T]) Last(ctx context.Context) (T, error) ( Interface[T]) Limit(offset int) ChainInterface[T] ( Interface[T]) MapColumns(m map[string]string) ChainInterface[T] ( Interface[T]) Not(query interface{}, args ...interface{}) ChainInterface[T] ( Interface[T]) Offset(offset int) ChainInterface[T] ( Interface[T]) Omit(columns ...string) ChainInterface[T] ( Interface[T]) Or(query interface{}, args ...interface{}) ChainInterface[T] ( Interface[T]) Order(value interface{}) ChainInterface[T] ( Interface[T]) Preload(association string, query func(db PreloadBuilder) error) ChainInterface[T] ( Interface[T]) Raw(sql string, values ...interface{}) ExecInterface[T] ( Interface[T]) Row(ctx context.Context) *sql.Row ( Interface[T]) Rows(ctx context.Context) (*sql.Rows, error) ( Interface[T]) Scan(ctx context.Context, r interface{}) error chain methods available at start; return ChainInterface ( Interface[T]) Select(query string, args ...interface{}) ChainInterface[T] ( Interface[T]) Set(assignments ...clause.Assigner) SetCreateOrUpdateInterface[T] ( Interface[T]) Table(name string, args ...interface{}) CreateInterface[T] ( Interface[T]) Take(context.Context) (T, error) ( Interface[T]) Update(ctx context.Context, name string, value any) (rowsAffected int, err error) ( Interface[T]) Updates(ctx context.Context, t T) (rowsAffected int, err error) ( Interface[T]) Where(query interface{}, args ...interface{}) ChainInterface[T] Interface : CreateInterface[T] Interface : ExecInterface[T] Interface : gorm.io/gorm/clause.Expression func G[T](db *DB, opts ...clause.Expression) Interface[T]
( JoinBuilder) Not(query interface{}, args ...interface{}) JoinBuilder ( JoinBuilder) Omit(...string) JoinBuilder ( JoinBuilder) Or(query interface{}, args ...interface{}) JoinBuilder ( JoinBuilder) Select(...string) JoinBuilder ( JoinBuilder) Where(query interface{}, args ...interface{}) JoinBuilder func JoinBuilder.Not(query interface{}, args ...interface{}) JoinBuilder func JoinBuilder.Omit(...string) JoinBuilder func JoinBuilder.Or(query interface{}, args ...interface{}) JoinBuilder func JoinBuilder.Select(...string) JoinBuilder func JoinBuilder.Where(query interface{}, args ...interface{}) JoinBuilder
Migrator migrator interface Columns ( Migrator) AlterColumn(dst interface{}, field string) error AutoMigrate ( Migrator) ColumnTypes(dst interface{}) ([]ColumnType, error) Constraints Indexes Tables Views Database ( Migrator) DropColumn(dst interface{}, field string) error ( Migrator) DropConstraint(dst interface{}, name string) error ( Migrator) DropIndex(dst interface{}, name string) error ( Migrator) DropTable(dst ...interface{}) error ( Migrator) DropView(name string) error ( Migrator) FullDataTypeOf(*schema.Field) clause.Expr ( Migrator) GetIndexes(dst interface{}) ([]Index, error) ( Migrator) GetTables() (tableList []string, err error) ( Migrator) GetTypeAliases(databaseTypeName string) []string ( Migrator) HasColumn(dst interface{}, field string) bool ( Migrator) HasConstraint(dst interface{}, name string) bool ( Migrator) HasIndex(dst interface{}, name string) bool ( Migrator) HasTable(dst interface{}) bool ( Migrator) MigrateColumn(dst interface{}, field *schema.Field, columnType ColumnType) error MigrateColumnUnique migrate column's UNIQUE constraint, it's part of MigrateColumn. ( Migrator) RenameColumn(dst interface{}, oldName, field string) error ( Migrator) RenameIndex(dst interface{}, oldName, newName string) error ( Migrator) RenameTable(oldName, newName interface{}) error ( Migrator) TableType(dst interface{}) (TableType, error) gorm.io/gorm/migrator.Migrator gorm.io/driver/mysql.Migrator func (*DB).Migrator() Migrator func Dialector.Migrator(db *DB) Migrator func gorm.io/driver/mysql.Dialector.Migrator(db *DB) Migrator
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 } CreatedAt time.Time DeletedAt DeletedAt ID uint UpdatedAt time.Time
Option gorm option interface ( Option) AfterInitialize(*DB) error ( Option) Apply(*Config) error *Config DB Statement func Open(dialector Dialector, opts ...Option) (db *DB, err error)
( ParamsFilter) ParamsFilter(ctx context.Context, sql string, params ...interface{}) (string, []interface{})
Plugin GORM plugin interface ( Plugin) Initialize(*DB) error ( Plugin) Name() string Config DB Dialector (interface) Statement gorm.io/gorm/migrator.Config gorm.io/gorm/migrator.Migrator gorm.io/driver/mysql.Dialector gorm.io/driver/mysql.Migrator Plugin : github.com/polarsignals/frostdb/query/logicalplan.Named func (*DB).Use(plugin Plugin) error
( PreloadBuilder) Limit(offset int) PreloadBuilder ( PreloadBuilder) LimitPerRecord(num int) PreloadBuilder ( PreloadBuilder) Not(query interface{}, args ...interface{}) PreloadBuilder ( PreloadBuilder) Offset(offset int) PreloadBuilder ( PreloadBuilder) Omit(...string) PreloadBuilder ( PreloadBuilder) Or(query interface{}, args ...interface{}) PreloadBuilder ( PreloadBuilder) Order(value interface{}) PreloadBuilder ( PreloadBuilder) Select(...string) PreloadBuilder ( PreloadBuilder) Where(query interface{}, args ...interface{}) PreloadBuilder func PreloadBuilder.Limit(offset int) PreloadBuilder func PreloadBuilder.LimitPerRecord(num int) PreloadBuilder func PreloadBuilder.Not(query interface{}, args ...interface{}) PreloadBuilder func PreloadBuilder.Offset(offset int) PreloadBuilder func PreloadBuilder.Omit(...string) PreloadBuilder func PreloadBuilder.Or(query interface{}, args ...interface{}) PreloadBuilder func PreloadBuilder.Order(value interface{}) PreloadBuilder func PreloadBuilder.Select(...string) PreloadBuilder func PreloadBuilder.Where(query interface{}, args ...interface{}) PreloadBuilder
ConnPool ConnPool Mux *sync.RWMutex Stmts stmt_store.Store (*PreparedStmtDB) BeginTx(ctx context.Context, opt *sql.TxOptions) (ConnPool, error) Close closes all prepared statements in the store (*PreparedStmtDB) ExecContext(ctx context.Context, query string, args ...interface{}) (result sql.Result, err error) GetDBConn returns the underlying *sql.DB connection (*PreparedStmtDB) Ping() error ( PreparedStmtDB) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) (*PreparedStmtDB) QueryContext(ctx context.Context, query string, args ...interface{}) (rows *sql.Rows, err error) (*PreparedStmtDB) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row Reset Deprecated use Close instead *PreparedStmtDB : ConnPool *PreparedStmtDB : ConnPoolBeginner *PreparedStmtDB : GetDBConnector PreparedStmtDB : gorm.io/gorm/internal/stmt_store.ConnPool func NewPreparedStmtDB(connPool ConnPool, maxSize int, ttl time.Duration) *PreparedStmtDB
PreparedStmtDB *PreparedStmtDB Tx Tx (*PreparedStmtTX) Commit() error (*PreparedStmtTX) ExecContext(ctx context.Context, query string, args ...interface{}) (result sql.Result, err error) (*PreparedStmtTX) GetDBConn() (*sql.DB, error) (*PreparedStmtTX) Ping() error ( PreparedStmtTX) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) (*PreparedStmtTX) QueryContext(ctx context.Context, query string, args ...interface{}) (rows *sql.Rows, err error) (*PreparedStmtTX) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row (*PreparedStmtTX) Rollback() error ( PreparedStmtTX) StmtContext(ctx context.Context, stmt *sql.Stmt) *sql.Stmt *PreparedStmtTX : ConnPool *PreparedStmtTX : GetDBConnector *PreparedStmtTX : Tx *PreparedStmtTX : TxCommitter PreparedStmtTX : gorm.io/gorm/internal/stmt_store.ConnPool *PreparedStmtTX : database/sql/driver.Tx
Rows rows interface ( Rows) Close() error ( Rows) ColumnTypes() ([]*sql.ColumnType, error) ( Rows) Columns() ([]string, error) ( Rows) Err() error ( Rows) Next() bool ( Rows) Scan(dest ...interface{}) error *database/sql.Rows Rows : github.com/apache/arrow-go/v18/arrow/compute/exec.ArrayIter[bool] Rows : github.com/prometheus/common/expfmt.Closer Rows : io.Closer func Scan(rows Rows, db *DB, mode ScanMode)
SavePointerDialectorInterface save pointer interface ( SavePointerDialectorInterface) RollbackTo(tx *DB, name string) error ( SavePointerDialectorInterface) SavePoint(tx *DB, name string) error gorm.io/driver/mysql.Dialector gorm.io/driver/mysql.Migrator
ScanMode scan data mode func Scan(rows Rows, db *DB, mode ScanMode) const ScanInitialized const ScanOnConflictDoNothing const ScanUpdate
Session session config when create session with Session() method AllowGlobalUpdate bool Context context.Context CreateBatchSize int DisableNestedTransaction bool DryRun bool FullSaveAssociations bool Initialized bool Logger logger.Interface NewDB bool NowFunc func() time.Time PrepareStmt bool PropagateUnscoped bool QueryFields bool SkipDefaultTransaction bool SkipHooks bool func (*DB).Session(config *Session) *DB
Type Parameters: T: any SetCreateOrUpdateInterface is returned by Set at start; Create or Update are allowed ( SetCreateOrUpdateInterface[T]) Create(ctx context.Context) error ( SetCreateOrUpdateInterface[T]) Update(ctx context.Context) (rowsAffected int, err error) SetCreateOrUpdateInterface : SetUpdateOnlyInterface[...] func CreateInterface[T].Set(assignments ...clause.Assigner) SetCreateOrUpdateInterface[T] func Interface[T].Set(assignments ...clause.Assigner) SetCreateOrUpdateInterface[T]
Type Parameters: T: any SetUpdateOnlyInterface is returned by Set after chaining; only Update is allowed ( SetUpdateOnlyInterface[T]) Update(ctx context.Context) (rowsAffected int, err error) SetCreateOrUpdateInterface[...] (interface) func ChainInterface[T].Set(assignments ...clause.Assigner) SetUpdateOnlyInterface[T]
Field *schema.Field ZeroValue sql.NullString ( SoftDeleteDeleteClause) Build(clause.Builder) ( SoftDeleteDeleteClause) MergeClause(*clause.Clause) ( SoftDeleteDeleteClause) ModifyStatement(stmt *Statement) ( SoftDeleteDeleteClause) Name() string SoftDeleteDeleteClause : StatementModifier SoftDeleteDeleteClause : gorm.io/gorm/clause.Expression SoftDeleteDeleteClause : gorm.io/gorm/clause.Interface SoftDeleteDeleteClause : github.com/polarsignals/frostdb/query/logicalplan.Named
Field *schema.Field ZeroValue sql.NullString ( SoftDeleteQueryClause) Build(clause.Builder) ( SoftDeleteQueryClause) MergeClause(*clause.Clause) ( SoftDeleteQueryClause) ModifyStatement(stmt *Statement) ( SoftDeleteQueryClause) Name() string SoftDeleteQueryClause : StatementModifier SoftDeleteQueryClause : gorm.io/gorm/clause.Expression SoftDeleteQueryClause : gorm.io/gorm/clause.Interface SoftDeleteQueryClause : github.com/polarsignals/frostdb/query/logicalplan.Named
Field *schema.Field ZeroValue sql.NullString ( SoftDeleteUpdateClause) Build(clause.Builder) ( SoftDeleteUpdateClause) MergeClause(*clause.Clause) ( SoftDeleteUpdateClause) ModifyStatement(stmt *Statement) ( SoftDeleteUpdateClause) Name() string SoftDeleteUpdateClause : StatementModifier SoftDeleteUpdateClause : gorm.io/gorm/clause.Expression SoftDeleteUpdateClause : gorm.io/gorm/clause.Interface SoftDeleteUpdateClause : github.com/polarsignals/frostdb/query/logicalplan.Named
Statement statement BuildClauses []string Clauses map[string]clause.Clause // map columns ConnPool ConnPool Context context.Context CurDestIndex int DB *DB DB.Config *Config AllowGlobalUpdate allow global update ClauseBuilders clause builder CreateBatchSize default create batch size DB.Config.DefaultContextTimeout time.Duration DB.Config.DefaultTransactionTimeout time.Duration 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 PrepareStmt cache support LRU expired, default maxsize=int64 Max value and ttl=1h DB.Config.PrepareStmtTTL time.Duration PropagateUnscoped propagate Unscoped to every other nested 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 DB.Error error DB.RowsAffected int64 DB.Statement *Statement Dest interface{} Distinct bool Joins []join Model interface{} // omit columns Preloads map[string][]interface{} RaiseErrorOnNotFound bool ReflectValue reflect.Value Result *result SQL strings.Builder Schema *schema.Schema // selected columns Settings sync.Map SkipHooks bool Table string TableExpr *clause.Expr Unscoped bool Vars []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"} ( 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} 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) MapColumns modify the column names in the query results to facilitate align to the corresponding structural fields 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}) db.Order(clause.OrderBy{Columns: []clause.OrderByColumn{ {Column: clause.Column{Name: "name"}, Desc: true}, {Column: clause.Column{Name: "age"}, 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) 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 : github.com/polarsignals/frostdb/query/logicalplan.Named *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.CheckConstraint, string) func gorm.io/gorm/migrator.Migrator.GuessConstraintInterfaceAndTable(stmt *Statement, name string) (_ schema.ConstraintInterface, 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)
StatementModifier statement modifier interface ( StatementModifier) ModifyStatement(*Statement) SoftDeleteDeleteClause SoftDeleteQueryClause SoftDeleteUpdateClause
TableType table type interface ( TableType) Comment() (comment string, ok bool) ( TableType) Name() string ( TableType) Schema() string ( TableType) Type() string gorm.io/gorm/migrator.TableType TableType : github.com/polarsignals/frostdb/query/logicalplan.Named func Migrator.TableType(dst interface{}) (TableType, error) func gorm.io/gorm/migrator.Migrator.TableType(dst interface{}) (TableType, error) func gorm.io/driver/mysql.Migrator.TableType(value interface{}) (tableType TableType, err error)
Tx sql.Tx interface ( Tx) Commit() error ( Tx) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) ( Tx) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) ( Tx) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) ( Tx) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row ( Tx) Rollback() error ( Tx) StmtContext(ctx context.Context, stmt *sql.Stmt) *sql.Stmt *PreparedStmtTX *database/sql.Tx Tx : ConnPool Tx : TxCommitter Tx : gorm.io/gorm/internal/stmt_store.ConnPool Tx : database/sql/driver.Tx
TxBeginner tx beginner ( TxBeginner) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error) *database/sql.Conn *database/sql.DB
TxCommitter tx committer ( TxCommitter) Commit() error ( TxCommitter) Rollback() error *PreparedStmtTX Tx (interface) *database/sql.Tx database/sql/driver.Tx (interface) github.com/ncruces/go-sqlite3.Txn github.com/ncruces/go-sqlite3.VTabSavepointer (interface) github.com/ncruces/go-sqlite3.VTabTxn (interface) *go.etcd.io/bbolt.Tx TxCommitter : database/sql/driver.Tx
Valuer gorm valuer interface ( Valuer) GormValue(context.Context, *DB) clause.Expr gorm.io/datatypes.JSON gorm.io/datatypes.JSONMap gorm.io/datatypes.JSONSlice[...] gorm.io/datatypes.JSONType[...]
ViewOption view option // optional. e.g. `WITH [ CASCADED | LOCAL ] CHECK OPTION` // required subquery. // If true, exec `CREATE`. If false, exec `CREATE OR REPLACE` func Migrator.CreateView(name string, option ViewOption) error func gorm.io/gorm/migrator.Migrator.CreateView(name string, option ViewOption) error
Package-Level Functions (total 6)
Expr returns clause.Expr, which can be used to pass SQL expression as params
Type Parameters: T: any
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.
Open initialize db session based on dialector
Scan scan rows into db statement
Package-Level Variables (total 22)
ErrCheckConstraintViolated occurs when there is a check constraint violation
ErrDryRunModeUnsupported dry run mode unsupported
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