Documentation ¶
Index ¶
- Variables
- func And(stmts ...interface{}) *expr
- func Concat(stmts ...interface{}) *expr
- func Expr(expression string, args ...interface{}) *expr
- func IsByteArrayOrSlice(value reflect.Value) bool
- func IsRecordNotFoundError(err error) bool
- func Not(stmt interface{}) *expr
- func Or(stmts ...interface{}) *expr
- func Order(stmts ...interface{}) *expr
- func RegisterDialect(name string, dialect Dialect)
- func ToDBName(name string) string
- func Union(stmts ...interface{}) *expr
- type Association
- func (association *Association) Append(values ...interface{}) *Association
- func (association *Association) Clear() *Association
- func (association *Association) Count() int
- func (association *Association) Delete(values ...interface{}) *Association
- func (association *Association) Find(value interface{}) *Association
- func (association *Association) Replace(values ...interface{}) *Association
- type Callback
- type CallbackProcessor
- func (cp *CallbackProcessor) After(callbackName string) *CallbackProcessor
- func (cp *CallbackProcessor) Before(callbackName string) *CallbackProcessor
- func (cp *CallbackProcessor) Get(callbackName string) (callback func(scope *Scope))
- func (cp *CallbackProcessor) Register(callbackName string, callback func(scope *Scope))
- func (cp *CallbackProcessor) Remove(callbackName string)
- func (cp *CallbackProcessor) Replace(callbackName string, callback func(scope *Scope))
- type DB
- func (s *DB) AddError(err error) error
- func (s *DB) AddForeignKey(field string, dest string, onDelete string, onUpdate string) *DB
- func (s *DB) AddIndex(indexName string, columns ...string) *DB
- func (s *DB) AddUniqueIndex(indexName string, columns ...string) *DB
- func (s *DB) AppendAfterCommitCallback(f func(db *DB))
- func (s *DB) AppendAfterRollbackCallback(f func(db *DB))
- func (s *DB) AppendAfterTransactionCallback(f func(db *DB))
- func (s *DB) Assign(attrs ...interface{}) *DB
- func (s *DB) Association(column string) *Association
- func (s *DB) Attrs(attrs ...interface{}) *DB
- func (s *DB) AutoMigrate(values ...interface{}) *DB
- func (s *DB) Begin() *DB
- func (s *DB) BeginTx(ctx context.Context, opts *sql.TxOptions) *DB
- func (s *DB) BlockGlobalUpdate(enable bool) *DB
- func (db *DB) C(model interface{}, names ...string) string
- func (db *DB) CA(model interface{}, alias string, names ...string) string
- func (db *DB) CAO(model interface{}, alias string, names ...string) string
- func (db *DB) CQ(model interface{}, names ...string) string
- func (s *DB) Callback() *Callback
- func (s *DB) Close() error
- func (db *DB) Coalesce(stmts ...interface{}) string
- func (db *DB) CoalesceExpr(stmts ...interface{}) *expr
- func (s *DB) Commit() *DB
- func (s *DB) CommonDB() SQLCommon
- func (s *DB) Count(value interface{}) *DB
- func (s *DB) Create(value interface{}) *DB
- func (s *DB) CreateTable(models ...interface{}) *DB
- func (s *DB) DB() *sql.DB
- func (s *DB) Debug() *DB
- func (s *DB) Delete(value interface{}, where ...interface{}) *DB
- func (s *DB) Dialect() Dialect
- func (s *DB) DropColumn(column string) *DB
- func (s *DB) DropTable(values ...interface{}) *DB
- func (s *DB) DropTableIfExists(values ...interface{}) *DB
- func (s *DB) Exec(sql string, values ...interface{}) *DB
- func (s *DB) Find(out interface{}, where ...interface{}) *DB
- func (s *DB) First(out interface{}, where ...interface{}) *DB
- func (s *DB) FirstOrCreate(out interface{}, where ...interface{}) *DB
- func (s *DB) FirstOrInit(out interface{}, where ...interface{}) *DB
- func (db *DB) FormatDate(e *expr, format string) *expr
- func (db *DB) FormatDateColumn(e *expr, format string) string
- func (s *DB) Get(name string) (value interface{}, ok bool)
- func (s *DB) GetErrors() []error
- func (db *DB) GetSQL() string
- func (db *DB) GetSQLWhereClause() string
- func (s *DB) Group(query string) *DB
- func (db *DB) GroupConcat(e *expr, separator string, orderExpr *expr) string
- func (db *DB) GroupConcatExpr(e *expr, separator string, orderExpr *expr) *expr
- func (s *DB) HasBlockGlobalUpdate() bool
- func (s *DB) HasTable(value interface{}) bool
- func (s *DB) Having(query interface{}, values ...interface{}) *DB
- func (db *DB) InnerJoin(model interface{}, alias ...string) *jexpr
- func (s *DB) InstantSet(name string, value interface{}) *DB
- func (s *DB) Joins(query interface{}, args ...interface{}) *DB
- func (db *DB) L(model interface{}, name string) *expr
- func (db *DB) LA(model interface{}, alias string, name string) *expr
- func (db *DB) LAO(model interface{}, alias string, name string) *expr
- func (s *DB) Last(out interface{}, where ...interface{}) *DB
- func (db *DB) LeftJoin(model interface{}, alias ...string) *jexpr
- func (s *DB) Limit(limit interface{}) *DB
- func (s *DB) LogMode(enable bool) *DB
- func (s *DB) Model(value interface{}) *DB
- func (s *DB) ModifyColumn(column string, typ string) *DB
- func (s *DB) New() *DB
- func (s *DB) NewRecord(value interface{}) bool
- func (s *DB) NewScope(value interface{}) *Scope
- func (s *DB) Not(query interface{}, args ...interface{}) *DB
- func (s *DB) Offset(offset interface{}) *DB
- func (s *DB) Omit(columns ...string) *DB
- func (s *DB) Or(query interface{}, args ...interface{}) *DB
- func (s *DB) Order(value interface{}, reorder ...bool) *DB
- func (db *DB) OuterJoin(model interface{}, alias ...string) *jexpr
- func (s *DB) Pluck(column string, value interface{}) *DB
- func (s *DB) Preload(column string, conditions ...interface{}) *DB
- func (s *DB) PrependAfterCommitCallback(f func(db *DB))
- func (s *DB) PrependAfterRollbackCallback(f func(db *DB))
- func (s *DB) PrependAfterTransactionCallback(f func(db *DB))
- func (db *DB) QT(model interface{}) string
- func (s *DB) QueryExpr(alias ...string) *expr
- func (db *DB) QuoteExpr(table string, column string) *expr
- func (s *DB) Raw(sql string, values ...interface{}) *DB
- func (s *DB) RecordNotFound() bool
- func (s *DB) Related(value interface{}, foreignKeys ...string) *DB
- func (s *DB) RemoveForeignKey(field string, dest string) *DB
- func (s *DB) RemoveIndex(indexName string) *DB
- func (db *DB) RightJoin(model interface{}, alias ...string) *jexpr
- func (s *DB) Rollback() *DB
- func (s *DB) Row() *sql.Row
- func (s *DB) Rows() (*sql.Rows, error)
- func (s *DB) Save(value interface{}) *DB
- func (s *DB) Scan(dest interface{}) *DB
- func (s *DB) ScanRows(rows *sql.Rows, result interface{}) error
- func (s *DB) Scopes(funcs ...func(*DB) *DB) *DB
- func (s *DB) Select(query interface{}, args ...interface{}) *DB
- func (db *DB) SelectExprs(fields ...interface{}) *DB
- func (db *DB) SelectFields(fields ...string) *DB
- func (s *DB) Set(name string, value interface{}) *DB
- func (s *DB) SetJoinTableHandler(source interface{}, column string, handler JoinTableHandlerInterface)
- func (s *DB) SetLogWriter(log LogWriter)
- func (s *DB) SetLogger(log logger)
- func (s *DB) SingularTable(enable bool)
- func (s *DB) SkipAssocSave() *DB
- func (s *DB) SubQuery() *expr
- func (db *DB) T(model interface{}) string
- func (s *DB) Table(name string) *DB
- func (s *DB) Take(out interface{}, where ...interface{}) *DB
- func (db *DB) TimestampDiff(unit TimeUnit, timestamp1 interface{}, timestamp2 interface{}) string
- func (db *DB) TimestampDiffExpr(unit TimeUnit, timestamp1 interface{}, timestamp2 interface{}) *expr
- func (s *DB) Unscoped() *DB
- func (s *DB) Update(attrs ...interface{}) *DB
- func (s *DB) UpdateColumn(attrs ...interface{}) *DB
- func (s *DB) UpdateColumns(values interface{}) *DB
- func (db *DB) UpdateFields(fields ...string) *DB
- func (db *DB) UpdateFieldsWithoutHooks(fields ...string) *DB
- func (s *DB) Updates(values interface{}, ignoreProtectedAttrs ...bool) *DB
- func (s *DB) Where(query interface{}, args ...interface{}) *DB
- func (s *DB) WrapInTx(f func(tx *DB) error) (err error)
- type DefaultForeignKeyNamer
- type Dialect
- type Errors
- type Field
- type JoinTableForeignKey
- type JoinTableHandler
- func (s JoinTableHandler) Add(handler JoinTableHandlerInterface, db *DB, source interface{}, ...) error
- func (s JoinTableHandler) Delete(handler JoinTableHandlerInterface, db *DB, sources ...interface{}) error
- func (s *JoinTableHandler) DestinationForeignKeys() []JoinTableForeignKey
- func (s JoinTableHandler) JoinWith(handler JoinTableHandlerInterface, db *DB, source interface{}) *DB
- func (s *JoinTableHandler) Setup(relationship *Relationship, tableName string, source reflect.Type, ...)
- func (s *JoinTableHandler) SourceForeignKeys() []JoinTableForeignKey
- func (s JoinTableHandler) Table(db *DB) string
- type JoinTableHandlerInterface
- type JoinTableSource
- type LogWriter
- type Logger
- type Model
- type ModelStruct
- type Relationship
- type RowQueryResult
- type RowsQueryResult
- type SQLCommon
- type Scope
- func (scope *Scope) AddToVars(value interface{}) string
- func (scope *Scope) Begin() *Scope
- func (scope *Scope) CallMethod(methodName string)
- func (scope *Scope) CombinedConditionSql() string
- func (scope *Scope) CommitOrRollback() *Scope
- func (scope *Scope) DB() *DB
- func (scope *Scope) Dialect() Dialect
- func (scope *Scope) Err(err error) error
- func (scope *Scope) Exec() *Scope
- func (scope *Scope) FieldByName(name string) (field *Field, ok bool)
- func (scope *Scope) Fields() []*Field
- func (scope *Scope) Get(name string) (interface{}, bool)
- func (scope *Scope) GetModelStruct() *ModelStruct
- func (scope *Scope) GetStructFields() (fields []*StructField)
- func (scope *Scope) HasColumn(column string) bool
- func (scope *Scope) HasError() bool
- func (scope *Scope) IndirectValue() reflect.Value
- func (scope *Scope) InstanceGet(name string) (interface{}, bool)
- func (scope *Scope) InstanceID() string
- func (scope *Scope) InstanceSet(name string, value interface{}) *Scope
- func (scope *Scope) Log(v ...interface{})
- func (scope *Scope) New(value interface{}) *Scope
- func (scope *Scope) NewDB() *DB
- func (scope *Scope) OmitAttrs() []string
- func (scope *Scope) PrimaryField() *Field
- func (scope *Scope) PrimaryFields() (fields []*Field)
- func (scope *Scope) PrimaryKey() string
- func (scope *Scope) PrimaryKeyValue() interface{}
- func (scope *Scope) PrimaryKeyZero() bool
- func (scope *Scope) Quote(str string) string
- func (scope *Scope) QuotedTableName() (name string)
- func (scope *Scope) Raw(sql string) *Scope
- func (scope *Scope) SQLDB() SQLCommon
- func (scope *Scope) SelectAttrs() []string
- func (scope *Scope) Set(name string, value interface{}) *Scope
- func (scope *Scope) SetColumn(column interface{}, value interface{}) error
- func (scope *Scope) SkipLeft()
- func (scope *Scope) TableName() string
- type StructField
- type TimeUnit
Constants ¶
This section is empty.
Variables ¶
var ( // ErrRecordNotFound record not found error, happens when haven't find any matched data when looking up with a struct ErrRecordNotFound = errors.New("record not found") // ErrInvalidSQL invalid SQL error, happens when you passed invalid SQL ErrInvalidSQL = errors.New("invalid SQL") // ErrInvalidTransaction invalid transaction when you are trying to `Commit` or `Rollback` ErrInvalidTransaction = errors.New("no valid transaction") // ErrCantStartTransaction can't start transaction when you are trying to start one with `Begin` ErrCantStartTransaction = errors.New("can't start transaction") // ErrUnaddressable unaddressable value ErrUnaddressable = errors.New("using unaddressable value") )
var DefaultCallback = &Callback{}
DefaultCallback default callbacks defined by gorm
var DefaultTableNameHandler = func(db *DB, defaultTableName string) string {
return defaultTableName
}
DefaultTableNameHandler default table name handler
var LogFormatter = func(values ...interface{}) (messages []interface{}) { if len(values) > 1 { var ( sql string formattedValues []string level = values[0] currentTime = "\n\033[33m[" + NowFunc().Format("2006-01-02 15:04:05") + "]\033[0m" source = fmt.Sprintf("\033[35m(%v)\033[0m", values[1]) ) messages = []interface{}{source, currentTime} if level == "sql" { messages = append(messages, fmt.Sprintf(" \033[36;1m[%.2fms]\033[0m ", float64(values[2].(time.Duration).Nanoseconds()/1e4)/100.0)) for _, value := range values[4].([]interface{}) { indirectValue := reflect.Indirect(reflect.ValueOf(value)) if indirectValue.IsValid() { value = indirectValue.Interface() if t, ok := value.(time.Time); ok { formattedValues = append(formattedValues, fmt.Sprintf("'%v'", t.Format("2006-01-02 15:04:05"))) } else if b, ok := value.([]byte); ok { if str := string(b); isPrintable(str) { formattedValues = append(formattedValues, fmt.Sprintf("'%v'", str)) } else { formattedValues = append(formattedValues, "'<binary>'") } } else if r, ok := value.(driver.Valuer); ok { if value, err := r.Value(); err == nil && value != nil { formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value)) } else { formattedValues = append(formattedValues, "NULL") } } else { formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value)) } } else { formattedValues = append(formattedValues, "NULL") } } if numericPlaceHolderRegexp.MatchString(values[3].(string)) { sql = values[3].(string) for index, value := range formattedValues { placeholder := fmt.Sprintf(`\$%d([^\d]|$)`, index+1) sql = regexp.MustCompile(placeholder).ReplaceAllString(sql, value+"$1") } } else { formattedValuesLength := len(formattedValues) for index, value := range sqlRegexp.Split(values[3].(string), -1) { sql += value if index < formattedValuesLength { sql += formattedValues[index] } } } messages = append(messages, sql) messages = append(messages, fmt.Sprintf(" \n\033[36;31m[%v]\033[0m ", strconv.FormatInt(values[5].(int64), 10)+" rows affected or returned ")) } else { messages = append(messages, "\033[31;1m") messages = append(messages, values[2:]...) messages = append(messages, "\033[0m") } } return }
var NowFunc = func() time.Time { return time.Now() }
NowFunc returns current time, this function is exported in order to be able to give the flexibility to the developer to customize it according to their needs, e.g:
gorm.NowFunc = func() time.Time { return time.Now().UTC() }
var ParseFieldStructForDialect = func(field *StructField, dialect Dialect) (fieldValue reflect.Value, sqlType string, size int, additionalType string) { // Get redirected field type var ( reflectType = field.Struct.Type dataType = field.TagSettings["TYPE"] ) for reflectType.Kind() == reflect.Ptr { reflectType = reflectType.Elem() } fieldValue = reflect.Indirect(reflect.New(reflectType)) if gormDataType, ok := fieldValue.Interface().(interface { GormDataType(Dialect) string }); ok { dataType = gormDataType.GormDataType(dialect) } if dataType == "" { var getScannerValue func(reflect.Value) getScannerValue = func(value reflect.Value) { fieldValue = value if _, isScanner := reflect.New(fieldValue.Type()).Interface().(sql.Scanner); isScanner && fieldValue.Kind() == reflect.Struct { getScannerValue(fieldValue.Field(0)) } } getScannerValue(fieldValue) } if num, ok := field.TagSettings["SIZE"]; ok { size, _ = strconv.Atoi(num) } else { size = 255 } additionalType = field.TagSettings["NOT NULL"] + " " + field.TagSettings["UNIQUE"] if value, ok := field.TagSettings["DEFAULT"]; ok { additionalType = additionalType + " DEFAULT " + value } return fieldValue, dataType, size, strings.TrimSpace(additionalType) }
ParseFieldStructForDialect get field's sql data type
Functions ¶
func And ¶
func And(stmts ...interface{}) *expr
And will create a statement which "ands" all given statements. stmts have to be *gorm.expr variables (but it is interface{}, so it can be used by external packages...)
func Concat ¶
func Concat(stmts ...interface{}) *expr
Concat will create an expression which concats all given statements together.
func Expr ¶
func Expr(expression string, args ...interface{}) *expr
Expr generate raw SQL expression, for example:
DB.Model(&product).Update("price", gorm.Expr("price * ? + ?", 2, 100))
func IsByteArrayOrSlice ¶
IsByteArrayOrSlice returns true of the reflected value is an array or slice
func IsRecordNotFoundError ¶
IsRecordNotFoundError returns current error has record not found error or not
func Not ¶
func Not(stmt interface{}) *expr
Not negates the given statement by surrounding its expression with "NOT (expr)" stmt has to be a *gorm.expr (but it is interface{}, so it can be used by external packages...)
func Or ¶
func Or(stmts ...interface{}) *expr
Or will create a statement which "ors" all given statements. stmts have to be *gorm.expr variables (but it is interface{}, so it can be used by external packages...)
func RegisterDialect ¶
RegisterDialect register new dialect
Types ¶
type Association ¶
type Association struct { Error error // contains filtered or unexported fields }
Association Mode contains some helper methods to handle relationship things easily.
func (*Association) Append ¶
func (association *Association) Append(values ...interface{}) *Association
Append append new associations for many2many, has_many, replace current association for has_one, belongs_to
func (*Association) Clear ¶
func (association *Association) Clear() *Association
Clear remove relationship between source & current associations, won't delete those associations
func (*Association) Count ¶
func (association *Association) Count() int
Count return the count of current associations
func (*Association) Delete ¶
func (association *Association) Delete(values ...interface{}) *Association
Delete remove relationship between source & passed arguments, but won't delete those arguments
func (*Association) Find ¶
func (association *Association) Find(value interface{}) *Association
Find find out all related associations
func (*Association) Replace ¶
func (association *Association) Replace(values ...interface{}) *Association
Replace replace current associations with new one
type Callback ¶
type Callback struct {
// contains filtered or unexported fields
}
Callback is a struct that contains all CRUD callbacks
Field `creates` contains callbacks will be call when creating object Field `updates` contains callbacks will be call when updating object Field `deletes` contains callbacks will be call when deleting object Field `queries` contains callbacks will be call when querying object with query methods like Find, First, Related, Association... Field `rowQueries` contains callbacks will be call when querying object with Row, Rows... Field `processors` contains all callback processors, will be used to generate above callbacks in order
func (*Callback) Create ¶
func (c *Callback) Create() *CallbackProcessor
Create could be used to register callbacks for creating object
db.Callback().Create().After("gorm:create").Register("plugin:run_after_create", func(*Scope) { // business logic ... // set error if some thing wrong happened, will rollback the creating scope.Err(errors.New("error")) })
func (*Callback) Delete ¶
func (c *Callback) Delete() *CallbackProcessor
Delete could be used to register callbacks for deleting object, refer `Create` for usage
func (*Callback) Query ¶
func (c *Callback) Query() *CallbackProcessor
Query could be used to register callbacks for querying objects with query methods like `Find`, `First`, `Related`, `Association`... Refer `Create` for usage
func (*Callback) RowQuery ¶
func (c *Callback) RowQuery() *CallbackProcessor
RowQuery could be used to register callbacks for querying objects with `Row`, `Rows`, refer `Create` for usage
func (*Callback) Update ¶
func (c *Callback) Update() *CallbackProcessor
Update could be used to register callbacks for updating object, refer `Create` for usage
type CallbackProcessor ¶
type CallbackProcessor struct {
// contains filtered or unexported fields
}
CallbackProcessor contains callback informations
func (*CallbackProcessor) After ¶
func (cp *CallbackProcessor) After(callbackName string) *CallbackProcessor
After insert a new callback after callback `callbackName`, refer `Callbacks.Create`
func (*CallbackProcessor) Before ¶
func (cp *CallbackProcessor) Before(callbackName string) *CallbackProcessor
Before insert a new callback before callback `callbackName`, refer `Callbacks.Create`
func (*CallbackProcessor) Get ¶
func (cp *CallbackProcessor) Get(callbackName string) (callback func(scope *Scope))
Get registered callback
db.Callback().Create().Get("gorm:create")
func (*CallbackProcessor) Register ¶
func (cp *CallbackProcessor) Register(callbackName string, callback func(scope *Scope))
Register a new callback, refer `Callbacks.Create`
func (*CallbackProcessor) Remove ¶
func (cp *CallbackProcessor) Remove(callbackName string)
Remove a registered callback
db.Callback().Create().Remove("gorm:update_time_stamp_when_create")
func (*CallbackProcessor) Replace ¶
func (cp *CallbackProcessor) Replace(callbackName string, callback func(scope *Scope))
Replace a registered callback with new callback
db.Callback().Create().Replace("gorm:update_time_stamp_when_create", func(*Scope) { scope.SetColumn("Created", now) scope.SetColumn("Updated", now) })
type DB ¶
type DB struct { Value interface{} Error error RowsAffected int64 // contains filtered or unexported fields }
DB contains information for current db connection
func Open ¶
Open initialize a new db connection, need to import driver first, e.g:
import _ "github.com/go-sql-driver/mysql" func main() { db, err := gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local") }
GORM has wrapped some drivers, for easier to remember driver's import path, so you could import the mysql driver with
import _ "github.com/jinzhu/gorm/dialects/mysql" // import _ "github.com/jinzhu/gorm/dialects/postgres" // import _ "github.com/jinzhu/gorm/dialects/sqlite" // import _ "github.com/jinzhu/gorm/dialects/mssql"
func (*DB) AddForeignKey ¶
AddForeignKey Add foreign key to the given scope, e.g:
db.Model(&User{}).AddForeignKey("city_id", "cities(id)", "RESTRICT", "RESTRICT")
func (*DB) AddUniqueIndex ¶
AddUniqueIndex add unique index for columns with given name
func (*DB) AppendAfterCommitCallback ¶
AppendAfterCommitCallback invoke callback after transaction committed If no transaction is currently running, it will be invoked immediately This method appends the given callback function to the register callback functions. This means, that the callback will be invoked after all previously registered callbacks.
func (*DB) AppendAfterRollbackCallback ¶
AppendAfterRollbackCallback invoke callback after transaction rolled back If no transaction is currently running, it will be invoked immediately This method appends the given callback function to the register callback functions. This means, that the callback will be invoked after all previously registered callbacks.
func (*DB) AppendAfterTransactionCallback ¶
AppendAfterTransactionCallback invoke callback after transaction finished (committed or rolled back). If no transaction is currently running, it will be invoked immediately This method appends the given callback function to the register callback functions. This means, that the callback will be invoked after all previously registered callbacks.
func (*DB) Assign ¶
Assign assign result with argument regardless it is found or not with `FirstOrInit` https://jinzhu.github.io/gorm/crud.html#firstorinit or `FirstOrCreate` https://jinzhu.github.io/gorm/crud.html#firstorcreate
func (*DB) Association ¶
func (s *DB) Association(column string) *Association
Association start `Association Mode` to handler relations things easir in that mode, refer: https://jinzhu.github.io/gorm/associations.html#association-mode
func (*DB) Attrs ¶
Attrs initialize struct with argument if record not found with `FirstOrInit` https://jinzhu.github.io/gorm/crud.html#firstorinit or `FirstOrCreate` https://jinzhu.github.io/gorm/crud.html#firstorcreate
func (*DB) AutoMigrate ¶
AutoMigrate run auto migration for given models, will only add missing fields, won't delete/change current data
func (*DB) BlockGlobalUpdate ¶
BlockGlobalUpdate if true, generates an error on update/delete without where clause. This is to prevent eventual error with empty objects updates/deletions
func (*DB) Callback ¶
Callback return `Callbacks` container, you could add/change/delete callbacks with it
db.Callback().Create().Register("update_created_at", updateCreated)
Refer https://jinzhu.github.io/gorm/development.html#callbacks
func (*DB) Close ¶
Close close current db connection. If database connection is not an io.Closer, returns an error.
func (*DB) CoalesceExpr ¶
func (db *DB) CoalesceExpr(stmts ...interface{}) *expr
func (*DB) CommonDB ¶
CommonDB return the underlying `*sql.DB` or `*sql.Tx` instance, mainly intended to allow coexistence with legacy non-GORM code.
func (*DB) CreateTable ¶
CreateTable create table for models
func (*DB) DB ¶
DB get `*sql.DB` from current connection If the underlying database connection is not a *sql.DB, returns nil
func (*DB) Delete ¶
Delete delete value match given conditions, if the value has primary key, then will including the primary key as condition
func (*DB) DropTableIfExists ¶
DropTableIfExists drop table if it is exist
func (*DB) FirstOrCreate ¶
FirstOrCreate find first matched record or create a new one with given conditions (only works with struct, map conditions) https://jinzhu.github.io/gorm/crud.html#firstorcreate
func (*DB) FirstOrInit ¶
FirstOrInit find first matched record or initialize a new one with given conditions (only works with struct, map conditions) https://jinzhu.github.io/gorm/crud.html#firstorinit
func (*DB) FormatDate ¶
func (*DB) FormatDateColumn ¶
func (*DB) GetSQLWhereClause ¶
func (*DB) GroupConcat ¶
func (*DB) GroupConcatExpr ¶
func (*DB) HasBlockGlobalUpdate ¶
HasBlockGlobalUpdate return state of block
func (*DB) InstantSet ¶
InstantSet instant set setting, will affect current db
func (*DB) Joins ¶
Joins specify Joins conditions
db.Joins("JOIN emails ON emails.user_id = users.id AND emails.email = ?", "jinzhu@example.org").Find(&user)
func (*DB) LogMode ¶
LogMode set log mode, `true` for detailed logs, `false` for no log, default, will only print error logs
func (*DB) Model ¶
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 the user's name to `hello` db.Model(&user).Update("name", "hello")
func (*DB) ModifyColumn ¶
ModifyColumn modify column to type
func (*DB) Offset ¶
Offset specify the number of records to skip before starting to return the records
func (*DB) Omit ¶
Omit specify fields that you want to ignore when saving to database for creating, updating
func (*DB) Order ¶
Order specify order when retrieve records from database, set reorder to `true` to overwrite defined conditions
db.Order("name DESC") db.Order("name DESC", true) // reorder db.Order(gorm.Expr("name = ? DESC", "first")) // sql expression
func (*DB) Pluck ¶
Pluck used to query single column from a model as a map
var ages []int64 db.Find(&users).Pluck("age", &ages)
func (*DB) Preload ¶
Preload preload associations with given conditions
db.Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users)
func (*DB) PrependAfterCommitCallback ¶
PrependAfterCommitCallback invoke callback after transaction committed If no transaction is currently running, it will be invoked immediately This method prepends the given callback function to the register callback functions. This means, that the callback will be invoked before all previously registered callbacks.
func (*DB) PrependAfterRollbackCallback ¶
PrependAfterRollbackCallback invoke callback after transaction rolled back. If no transaction is currently running, it will be invoked immediately This method prepends the given callback function to the register callback functions. This means, that the callback will be invoked before all previously registered callbacks.
func (*DB) PrependAfterTransactionCallback ¶
PrependAfterTransactionCallback invoke callback after transaction finished (committed or rolled back). If no transaction is currently running, it will be invoked immediately This method prepends the given callback function to the register callback functions. This means, that the callback will be invoked before all previously registered callbacks.
func (*DB) Raw ¶
Raw use raw sql as conditions, won't run it unless invoked by other methods
db.Raw("SELECT name, age FROM users WHERE name = ?", 3).Scan(&result)
func (*DB) RecordNotFound ¶
RecordNotFound check if returning ErrRecordNotFound error
func (*DB) RemoveForeignKey ¶
RemoveForeignKey Remove foreign key from the given scope, e.g:
db.Model(&User{}).RemoveForeignKey("city_id", "cities(id)")
func (*DB) RemoveIndex ¶
RemoveIndex remove index with name
func (*DB) Save ¶
Save update value in database, if the value doesn't have primary key, will insert it
func (*DB) Scopes ¶
Scopes pass current database connection to arguments `func(*DB) *DB`, which could be used to add conditions dynamically
func AmountGreaterThan1000(db *gorm.DB) *gorm.DB { return db.Where("amount > ?", 1000) } func OrderStatus(status []string) func (db *gorm.DB) *gorm.DB { return func (db *gorm.DB) *gorm.DB { return db.Scopes(AmountGreaterThan1000).Where("status in (?)", status) } } db.Scopes(AmountGreaterThan1000, OrderStatus([]string{"paid", "shipped"})).Find(&orders)
func (*DB) Select ¶
Select specify fields that you want to retrieve from database when querying, by default, will select all fields; When creating/updating, specify fields that you want to save to database
func (*DB) SelectExprs ¶
func (*DB) SelectFields ¶
func (*DB) Set ¶
Set set setting by name, which could be used in callbacks, will clone a new db, and update its setting
func (*DB) SetJoinTableHandler ¶
func (s *DB) SetJoinTableHandler(source interface{}, column string, handler JoinTableHandlerInterface)
SetJoinTableHandler set a model's join table handler for a relation
func (*DB) SetLogWriter ¶
SetLogWriter sets the LogWriter the default logger should write to
func (*DB) SingularTable ¶
SingularTable use singular table by default
func (*DB) SkipAssocSave ¶
SkipAssocSave disables saving of associations
func (*DB) Take ¶
Take return a record that match given conditions, the order will depend on the database implementation
func (*DB) TimestampDiff ¶
func (*DB) TimestampDiffExpr ¶
func (*DB) Unscoped ¶
Unscoped return all record including deleted record, refer Soft Delete https://jinzhu.github.io/gorm/crud.html#soft-delete
func (*DB) Update ¶
Update update attributes with callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update
func (*DB) UpdateColumn ¶
UpdateColumn update attributes without callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update
func (*DB) UpdateColumns ¶
UpdateColumns update attributes without callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update
func (*DB) UpdateFields ¶
func (*DB) UpdateFieldsWithoutHooks ¶
UpdateFieldsWithoutHooks updates the specified fields of the current model without calling any Update hooks and without touching the UpdatedAt column (if any exists). The specified fields have to be the names of the struct variables.
func (*DB) Updates ¶
Updates update attributes with callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update
func (*DB) Where ¶
Where return a new relation, filter records with given conditions, accepts `map`, `struct` or `string` as conditions, refer http://jinzhu.github.io/gorm/crud.html#query
type DefaultForeignKeyNamer ¶
type DefaultForeignKeyNamer struct { }
DefaultForeignKeyNamer contains the default foreign key name generator method
func (DefaultForeignKeyNamer) BuildKeyName ¶
func (DefaultForeignKeyNamer) BuildKeyName(kind, tableName string, fields ...string) string
BuildKeyName returns a valid key name (foreign key, index key) for the given table, field and reference
type Dialect ¶
type Dialect interface { // GetName get dialect's name GetName() string // SetDB set db for dialect SetDB(db SQLCommon) // BindVar return the placeholder for actual values in SQL statements, in many dbs it is "?", Postgres using $1 BindVar(i int) string // Quote quotes field name to avoid SQL parsing exceptions by using a reserved word as a field name Quote(key string) string // DataTypeOf return data's sql type DataTypeOf(field *StructField) string // HasIndex check has index or not HasIndex(tableName string, indexName string) bool // HasForeignKey check has foreign key or not HasForeignKey(tableName string, foreignKeyName string) bool // RemoveIndex remove index RemoveIndex(tableName string, indexName string) error // HasTable check has table or not HasTable(tableName string) bool // HasColumn check has column or not HasColumn(tableName string, columnName string) bool // ModifyColumn modify column's type ModifyColumn(tableName string, columnName string, typ string) error // LimitAndOffsetSQL return generated SQL with Limit and Offset, as mssql has special case LimitAndOffsetSQL(limit, offset interface{}) string // SelectFromDummyTable return select values, for most dbs, `SELECT values` just works, mysql needs `SELECT value FROM DUAL` SelectFromDummyTable() string // LastInsertIdReturningSuffix most dbs support LastInsertId, but postgres needs to use `RETURNING` LastInsertIDReturningSuffix(tableName, columnName string) string // DefaultValueStr DefaultValueStr() string // BuildKeyName returns a valid key name (foreign key, index key) for the given table, field and reference BuildKeyName(kind, tableName string, fields ...string) string // CurrentDatabase return current database name CurrentDatabase() string // Formates the date and tries to be as similar as possible with all databases // | | gorm | SQLITE | MYSQL | MSSQL | POSTGRES | // | ----------- | ---- | ----------------- | ----------------- | ---------------- | ---------------- | // | YEAR | %y | %Y (0000-9999) | %Y (0000-9999) | YYYY (0000-9999) | YYYY (0000-9999) | // | MONTH | %m | %m (01-12) | %m (01-12) | MM (00-12) | MM (0000-9999) | // | WEEK | %w | %W (00-53) | %u (00-53) | -- | WW (1-53) | // | DAY | %d | %d (00-31) | %d (00-31) | dd (00-31) | DD (00-31) | // | DAY OF WEEK | %D | %w (SUN 0-6 SAT) | %w (SUN 0-6 SAT) | -- | D (SUN 1-7 SAT) | // | HOUR | %h | %H (00-24) | %H (00-23) | HH (00-31) | HH24 (00-23) | // | MINUTE | %m | %M (00-59) | %i (00-59) | mm (00-59) | MI (00-59) | // | SECOND | %s | %S (00-59) | %S (00-59) | ss (00-59) | SS (00-59) | FormatDate(*expr, string) *expr }
Dialect interface contains behaviors that differ across SQL database
type Field ¶
type Field struct { *StructField IsBlank bool Field reflect.Value }
Field model field definition
type JoinTableForeignKey ¶
JoinTableForeignKey join table foreign key struct
type JoinTableHandler ¶
type JoinTableHandler struct { TableName string `sql:"-"` Source JoinTableSource `sql:"-"` Destination JoinTableSource `sql:"-"` }
JoinTableHandler default join table handler
func (JoinTableHandler) Add ¶
func (s JoinTableHandler) Add(handler JoinTableHandlerInterface, db *DB, source interface{}, destination interface{}) error
Add create relationship in join table for source and destination
func (JoinTableHandler) Delete ¶
func (s JoinTableHandler) Delete(handler JoinTableHandlerInterface, db *DB, sources ...interface{}) error
Delete delete relationship in join table for sources
func (*JoinTableHandler) DestinationForeignKeys ¶
func (s *JoinTableHandler) DestinationForeignKeys() []JoinTableForeignKey
DestinationForeignKeys return destination foreign keys
func (JoinTableHandler) JoinWith ¶
func (s JoinTableHandler) JoinWith(handler JoinTableHandlerInterface, db *DB, source interface{}) *DB
JoinWith query with `Join` conditions
func (*JoinTableHandler) Setup ¶
func (s *JoinTableHandler) Setup(relationship *Relationship, tableName string, source reflect.Type, destination reflect.Type)
Setup initialize a default join table handler
func (*JoinTableHandler) SourceForeignKeys ¶
func (s *JoinTableHandler) SourceForeignKeys() []JoinTableForeignKey
SourceForeignKeys return source foreign keys
func (JoinTableHandler) Table ¶
func (s JoinTableHandler) Table(db *DB) string
Table return join table's table name
type JoinTableHandlerInterface ¶
type JoinTableHandlerInterface interface { // initialize join table handler Setup(relationship *Relationship, tableName string, source reflect.Type, destination reflect.Type) // Table return join table's table name Table(db *DB) string // Add create relationship in join table for source and destination Add(handler JoinTableHandlerInterface, db *DB, source interface{}, destination interface{}) error // Delete delete relationship in join table for sources Delete(handler JoinTableHandlerInterface, db *DB, sources ...interface{}) error // JoinWith query with `Join` conditions JoinWith(handler JoinTableHandlerInterface, db *DB, source interface{}) *DB // SourceForeignKeys return source foreign keys SourceForeignKeys() []JoinTableForeignKey // DestinationForeignKeys return destination foreign keys DestinationForeignKeys() []JoinTableForeignKey }
JoinTableHandlerInterface is an interface for how to handle many2many relations
type JoinTableSource ¶
type JoinTableSource struct { ModelType reflect.Type ForeignKeys []JoinTableForeignKey }
JoinTableSource is a struct that contains model type and foreign keys
type LogWriter ¶
type LogWriter interface {
Println(v ...interface{})
}
LogWriter log writer interface
type Model ¶
type Model struct { ID uint `gorm:"primary_key"` CreatedAt time.Time UpdatedAt time.Time DeletedAt *time.Time `sql:"index"` }
Model base model definition, including fields `ID`, `CreatedAt`, `UpdatedAt`, `DeletedAt`, which could be embedded in your models
type User struct { gorm.Model }
type ModelStruct ¶
type ModelStruct struct { PrimaryFields []*StructField StructFields []*StructField ModelType reflect.Type // contains filtered or unexported fields }
ModelStruct model definition
func (*ModelStruct) TableName ¶
func (s *ModelStruct) TableName(db *DB) string
TableName get model's table name
type Relationship ¶
type Relationship struct { Kind string PolymorphicType string PolymorphicDBName string PolymorphicValue string ForeignFieldNames []string ForeignDBNames []string AssociationForeignFieldNames []string AssociationForeignDBNames []string JoinTableHandler JoinTableHandlerInterface }
Relationship described the relationship between models
type RowQueryResult ¶
type RowsQueryResult ¶
type SQLCommon ¶
type SQLCommon interface { Exec(query string, args ...interface{}) (sql.Result, error) Prepare(query string) (*sql.Stmt, error) Query(query string, args ...interface{}) (*sql.Rows, error) QueryRow(query string, args ...interface{}) *sql.Row }
SQLCommon is the minimal database connection functionality gorm requires. Implemented by *sql.DB.
type Scope ¶
type Scope struct { Search *search Value interface{} SQL string SQLVars []interface{} // contains filtered or unexported fields }
Scope contain current operation's information when you perform any operation on the database
func (*Scope) CallMethod ¶
CallMethod call scope value's method, if it is a slice, will call its element's method one by one
func (*Scope) CombinedConditionSql ¶
CombinedConditionSQL return combined condition SQL
func (*Scope) CommitOrRollback ¶
CommitOrRollback commit current transaction if no error happened, otherwise will rollback it
func (*Scope) FieldByName ¶
FieldByName find `gorm.Field` with field name or db name
func (*Scope) GetModelStruct ¶
func (scope *Scope) GetModelStruct() *ModelStruct
GetModelStruct get value's model struct, relationships based on struct and tag definition
func (*Scope) GetStructFields ¶
func (scope *Scope) GetStructFields() (fields []*StructField)
GetStructFields get model's field structs
func (*Scope) IndirectValue ¶
IndirectValue return scope's reflect value's indirect value
func (*Scope) InstanceGet ¶
InstanceGet get instance setting from current operation
func (*Scope) InstanceID ¶
InstanceID get InstanceID for scope
func (*Scope) InstanceSet ¶
InstanceSet set instance setting for current operation, but not for operations in callbacks, like saving associations callback
func (*Scope) PrimaryField ¶
PrimaryField return scope's main primary field, if defined more that one primary fields, will return the one having column name `id` or the first one
func (*Scope) PrimaryFields ¶
PrimaryFields return scope's primary fields
func (*Scope) PrimaryKey ¶
PrimaryKey get main primary field's db name
func (*Scope) PrimaryKeyValue ¶
func (scope *Scope) PrimaryKeyValue() interface{}
PrimaryKeyValue get the primary key's value
func (*Scope) PrimaryKeyZero ¶
PrimaryKeyZero check main primary field's value is blank or not
func (*Scope) QuotedTableName ¶
QuotedTableName return quoted table name
func (*Scope) SelectAttrs ¶
SelectAttrs return selected attributes
type StructField ¶
type StructField struct { DBName string Name string Names []string IsPrimaryKey bool IsNormal bool IsIgnored bool IsScanner bool HasDefaultValue bool Tag reflect.StructTag TagSettings map[string]string Struct reflect.StructField IsForeignKey bool Relationship *Relationship }
StructField model field's struct definition
Source Files ¶
- association.go
- callback.go
- callback_create.go
- callback_delete.go
- callback_query.go
- callback_query_preload.go
- callback_row_query.go
- callback_save.go
- callback_update.go
- dialect.go
- dialect_common.go
- dialect_mssql.go
- dialect_mysql.go
- dialect_postgres.go
- dialect_sqlite3.go
- errors.go
- expression_ext.go
- field.go
- interface.go
- join_table_handler.go
- logger.go
- main.go
- model.go
- model_struct.go
- scope.go
- search.go
- utils.go