Documentation
¶
Index ¶
- Variables
- func IsByteArrayOrSlice(value reflect.Value) bool
- func IsRecordNotFoundError(err error) bool
- func RegisterDialect(name string, dialect Dialect)
- func ToDBName(name string) string
- 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) Error() error
- 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 DefaultForeignKeyNamer
- type Dialect
- type Errors
- type Expression
- type FakeRepository
- func (r *FakeRepository) AddError(err error) error
- func (r *FakeRepository) AddForeignKey(field string, dest string, onDelete string, onUpdate string) Repository
- func (r *FakeRepository) AddIndex(indexName string, columns ...string) Repository
- func (r *FakeRepository) AddUniqueIndex(indexName string, columns ...string) Repository
- func (r *FakeRepository) Assign(attrs ...interface{}) Repository
- func (r *FakeRepository) Association(column string) *Association
- func (r *FakeRepository) Attrs(attrs ...interface{}) Repository
- func (r *FakeRepository) AutoMigrate(values ...interface{}) Repository
- func (r *FakeRepository) Begin() Repository
- func (r *FakeRepository) BlockGlobalUpdate(enable bool) Repository
- func (r *FakeRepository) Callback() *Callback
- func (r *FakeRepository) Callbacks() *Callback
- func (r *FakeRepository) Clone() Repository
- func (r *FakeRepository) Close() error
- func (r *FakeRepository) Commit() Repository
- func (r *FakeRepository) CommonDB() SQLCommon
- func (r *FakeRepository) Count(value interface{}) Repository
- func (r *FakeRepository) Create(value interface{}) Repository
- func (r *FakeRepository) CreateTable(models ...interface{}) Repository
- func (r *FakeRepository) Debug() Repository
- func (r *FakeRepository) Delete(value interface{}, where ...interface{}) Repository
- func (r *FakeRepository) Dialect() Dialect
- func (r *FakeRepository) DropColumn(column string) Repository
- func (r *FakeRepository) DropTable(values ...interface{}) Repository
- func (r *FakeRepository) DropTableIfExists(values ...interface{}) Repository
- func (r *FakeRepository) Error() error
- func (r *FakeRepository) Exec(sql string, values ...interface{}) Repository
- func (r *FakeRepository) Expect(err error)
- func (r *FakeRepository) Find(out interface{}, where ...interface{}) Repository
- func (r *FakeRepository) First(out interface{}, where ...interface{}) Repository
- func (r *FakeRepository) FirstOrCreate(out interface{}, where ...interface{}) Repository
- func (r *FakeRepository) FirstOrInit(out interface{}, where ...interface{}) Repository
- func (r *FakeRepository) Get(name string) (value interface{}, ok bool)
- func (r *FakeRepository) GetErrors() []error
- func (r *FakeRepository) Group(query string) Repository
- func (r *FakeRepository) HasBlockGlobalUpdate() bool
- func (r *FakeRepository) HasTable(value interface{}) bool
- func (r *FakeRepository) Having(query interface{}, values ...interface{}) Repository
- func (r *FakeRepository) InstantSet(name string, value interface{}) Repository
- func (r *FakeRepository) IsSingularTable() bool
- func (r *FakeRepository) Joins(query string, args ...interface{}) Repository
- func (r *FakeRepository) Last(out interface{}, where ...interface{}) Repository
- func (r *FakeRepository) Limit(limit interface{}) Repository
- func (r *FakeRepository) Log(v ...interface{})
- func (r *FakeRepository) LogMode(enable bool) Repository
- func (r *FakeRepository) Mock(method string, data interface{}) *FakeRepository
- func (r *FakeRepository) Model(value interface{}) Repository
- func (r *FakeRepository) ModifyColumn(column string, typ string) Repository
- func (r *FakeRepository) New() Repository
- func (r *FakeRepository) NewRecord(value interface{}) bool
- func (r *FakeRepository) NewScope(value interface{}) *Scope
- func (r *FakeRepository) Not(query interface{}, args ...interface{}) Repository
- func (r *FakeRepository) Offset(offset interface{}) Repository
- func (r *FakeRepository) Omit(columns ...string) Repository
- func (r *FakeRepository) Or(query interface{}, args ...interface{}) Repository
- func (r *FakeRepository) Order(value interface{}, reorder ...bool) Repository
- func (r *FakeRepository) Parent() Repository
- func (r *FakeRepository) Pluck(column string, value interface{}) Repository
- func (r *FakeRepository) Preload(column string, conditions ...interface{}) Repository
- func (r *FakeRepository) Print(v ...interface{})
- func (r *FakeRepository) QueryExpr() *Expression
- func (r *FakeRepository) Raw(sql string, values ...interface{}) Repository
- func (r *FakeRepository) RecordNotFound() bool
- func (r *FakeRepository) Related(value interface{}, foreignKeys ...string) Repository
- func (r *FakeRepository) RemoveForeignKey(field string, dest string) Repository
- func (r *FakeRepository) RemoveIndex(indexName string) Repository
- func (r *FakeRepository) Rollback() Repository
- func (r *FakeRepository) Row() *sql.Row
- func (r *FakeRepository) Rows() (*sql.Rows, error)
- func (r *FakeRepository) RowsAffected() int64
- func (r *FakeRepository) SQLCommonDB() SQLCommon
- func (r *FakeRepository) Save(value interface{}) Repository
- func (r *FakeRepository) Scan(dest interface{}) Repository
- func (r *FakeRepository) ScanRows(rows *sql.Rows, result interface{}) error
- func (r *FakeRepository) Scopes(funcs ...func(Repository) Repository) Repository
- func (r *FakeRepository) Search() *Search
- func (r *FakeRepository) Select(query interface{}, args ...interface{}) Repository
- func (r *FakeRepository) Set(name string, value interface{}) Repository
- func (r *FakeRepository) SetCallbacks(cb *Callback) Repository
- func (r *FakeRepository) SetDialect(d Dialect) Repository
- func (r *FakeRepository) SetError(err error) Repository
- func (r *FakeRepository) SetIsSingularTable(singularTable bool) Repository
- func (r *FakeRepository) SetJoinTableHandler(source interface{}, column string, handler JoinTableHandlerInterface)
- func (r *FakeRepository) SetLogger(log Logger) Repository
- func (r *FakeRepository) SetParent(p Repository) Repository
- func (r *FakeRepository) SetRowsAffected(row int64) Repository
- func (r *FakeRepository) SetSQLCommonDB(sc SQLCommon) Repository
- func (r *FakeRepository) SetSearch(search *Search) Repository
- func (r *FakeRepository) SetValue(v interface{}) Repository
- func (r *FakeRepository) SetValues(vals map[string]interface{}) Repository
- func (r *FakeRepository) SingularTable(enable bool)
- func (r *FakeRepository) Slog(sql string, t time.Time, vars ...interface{})
- func (r *FakeRepository) SqlDB() *sql.DB
- func (r *FakeRepository) SubQuery() *Expression
- func (r *FakeRepository) Table(name string) Repository
- func (r *FakeRepository) Take(out interface{}, where ...interface{}) Repository
- func (r *FakeRepository) Unscoped() Repository
- func (r *FakeRepository) Update(attrs ...interface{}) Repository
- func (r *FakeRepository) UpdateColumn(attrs ...interface{}) Repository
- func (r *FakeRepository) UpdateColumns(values interface{}) Repository
- func (r *FakeRepository) Updates(values interface{}, ignoreProtectedAttrs ...bool) Repository
- func (r *FakeRepository) Value() interface{}
- func (r *FakeRepository) Values() map[string]interface{}
- func (r *FakeRepository) Where(query interface{}, args ...interface{}) Repository
- type Field
- type JoinTableForeignKey
- type JoinTableHandler
- func (s JoinTableHandler) Add(handler JoinTableHandlerInterface, db Repository, source interface{}, ...) error
- func (s JoinTableHandler) Delete(handler JoinTableHandlerInterface, db Repository, sources ...interface{}) error
- func (s *JoinTableHandler) DestinationForeignKeys() []JoinTableForeignKey
- func (s JoinTableHandler) JoinWith(handler JoinTableHandlerInterface, db Repository, source interface{}) Repository
- func (s *JoinTableHandler) Setup(relationship *Relationship, tableName string, source reflect.Type, ...)
- func (s *JoinTableHandler) SourceForeignKeys() []JoinTableForeignKey
- func (s JoinTableHandler) Table(db Repository) string
- type JoinTableHandlerInterface
- type JoinTableSource
- type LogWriter
- type Logger
- type Mocker
- type Model
- type ModelStruct
- type Relationship
- type Repository
- 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() Repository
- 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() Repository
- 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 Search
- func (s *Search) Assign(attrs ...interface{}) *Search
- func (s *Search) Attrs(attrs ...interface{}) *Search
- func (s *Search) Group(query string) *Search
- func (s *Search) Having(query interface{}, values ...interface{}) *Search
- func (s *Search) Joins(query string, values ...interface{}) *Search
- func (s *Search) Limit(limit interface{}) *Search
- func (s *Search) Not(query interface{}, values ...interface{}) *Search
- func (s *Search) Offset(offset interface{}) *Search
- func (s *Search) Omit(columns ...string) *Search
- func (s *Search) Or(query interface{}, values ...interface{}) *Search
- func (s *Search) Order(value interface{}, reorder ...bool) *Search
- func (s *Search) Preload(schema string, values ...interface{}) *Search
- func (s *Search) Raw(b bool) *Search
- func (s *Search) Select(query interface{}, args ...interface{}) *Search
- func (s *Search) Table(name string) *Search
- func (s *Search) Where(query interface{}, values ...interface{}) *Search
- type StructField
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 Repository, 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 } if value, ok := field.TagSettings["COMMENT"]; ok { additionalType = additionalType + " COMMENT " + value } return fieldValue, dataType, size, strings.TrimSpace(additionalType) }
ParseFieldStructForDialect get field's sql data type
Functions ¶
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 RegisterDialect ¶
RegisterDialect register new dialect
Types ¶
type Association ¶
type Association struct {
// 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) Error ¶
func (association *Association) Error() error
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 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
}
Dialect interface contains behaviors that differ across SQL database
func GetDialect ¶
GetDialect gets the dialect for the specified dialect name
type Expression ¶
type Expression struct {
// contains filtered or unexported fields
}
SQL expression
func Expr ¶
func Expr(expression string, args ...interface{}) *Expression
Expr generate raw SQL expression, for example:
DB.Model(&product).Update("price", gorm.Expr("price * ? + ?", 2, 100))
type FakeRepository ¶
type FakeRepository struct {
// contains filtered or unexported fields
}
DB contains information for current db connection
func (*FakeRepository) AddError ¶
func (r *FakeRepository) AddError(err error) error
AddError add error to the db
func (*FakeRepository) AddForeignKey ¶
func (r *FakeRepository) AddForeignKey(field string, dest string, onDelete string, onUpdate string) Repository
AddForeignKey Add foreign key to the given scope, e.g:
db.Model(&User{}).AddForeignKey("city_id", "cities(id)", "RESTRICT", "RESTRICT")
func (*FakeRepository) AddIndex ¶
func (r *FakeRepository) AddIndex(indexName string, columns ...string) Repository
AddIndex add index for columns with given name
func (*FakeRepository) AddUniqueIndex ¶
func (r *FakeRepository) AddUniqueIndex(indexName string, columns ...string) Repository
AddUniqueIndex add unique index for columns with given name
func (*FakeRepository) Assign ¶
func (r *FakeRepository) Assign(attrs ...interface{}) Repository
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 (*FakeRepository) Association ¶
func (r *FakeRepository) 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 (*FakeRepository) Attrs ¶
func (r *FakeRepository) Attrs(attrs ...interface{}) Repository
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 (*FakeRepository) AutoMigrate ¶
func (r *FakeRepository) AutoMigrate(values ...interface{}) Repository
AutoMigrate run auto migration for given models, will only add missing fields, won't delete/change current data
func (*FakeRepository) Begin ¶
func (r *FakeRepository) Begin() Repository
Begin begin a transaction
func (*FakeRepository) BlockGlobalUpdate ¶
func (r *FakeRepository) BlockGlobalUpdate(enable bool) Repository
BlockGlobalUpdate if true, generates an error on update/delete without where clause. This is to prevent eventual error with empty objects updates/deletions
func (*FakeRepository) Callback ¶
func (r *FakeRepository) Callback() *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 (*FakeRepository) Callbacks ¶
func (r *FakeRepository) Callbacks() *Callback
func (*FakeRepository) Clone ¶
func (r *FakeRepository) Clone() Repository
func (*FakeRepository) Close ¶
func (r *FakeRepository) Close() error
Close close current db connection. If database connection is not an io.Closer, returns an error.
func (*FakeRepository) Commit ¶
func (r *FakeRepository) Commit() Repository
Commit commit a transaction
func (*FakeRepository) CommonDB ¶
func (r *FakeRepository) CommonDB() SQLCommon
CommonDB return the underlying `*sql.DB` or `*sql.Tx` instance, mainly intended to allow coexistence with legacy non-GORM code.
func (*FakeRepository) Count ¶
func (r *FakeRepository) Count(value interface{}) Repository
Count get how many records for a model
func (*FakeRepository) Create ¶
func (r *FakeRepository) Create(value interface{}) Repository
Create insert the value into database
func (*FakeRepository) CreateTable ¶
func (r *FakeRepository) CreateTable(models ...interface{}) Repository
CreateTable create table for models
func (*FakeRepository) Delete ¶
func (r *FakeRepository) Delete(value interface{}, where ...interface{}) Repository
Delete delete value match given conditions, if the value has primary key, then will including the primary key as condition
func (*FakeRepository) DropColumn ¶
func (r *FakeRepository) DropColumn(column string) Repository
DropColumn drop a column
func (*FakeRepository) DropTable ¶
func (r *FakeRepository) DropTable(values ...interface{}) Repository
DropTable drop table for models
func (*FakeRepository) DropTableIfExists ¶
func (r *FakeRepository) DropTableIfExists(values ...interface{}) Repository
DropTableIfExists drop table if it is exist
func (*FakeRepository) Error ¶
func (r *FakeRepository) Error() error
func (*FakeRepository) Exec ¶
func (r *FakeRepository) Exec(sql string, values ...interface{}) Repository
Exec execute raw sql
func (*FakeRepository) Expect ¶
func (r *FakeRepository) Expect(err error)
func (*FakeRepository) Find ¶
func (r *FakeRepository) Find(out interface{}, where ...interface{}) Repository
Find find records that match given conditions
func (*FakeRepository) First ¶
func (r *FakeRepository) First(out interface{}, where ...interface{}) Repository
First find first record that match given conditions, order by primary key
func (*FakeRepository) FirstOrCreate ¶
func (r *FakeRepository) FirstOrCreate(out interface{}, where ...interface{}) Repository
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 (*FakeRepository) FirstOrInit ¶
func (r *FakeRepository) FirstOrInit(out interface{}, where ...interface{}) Repository
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 (*FakeRepository) Get ¶
func (r *FakeRepository) Get(name string) (value interface{}, ok bool)
Get get setting by name
func (*FakeRepository) GetErrors ¶
func (r *FakeRepository) GetErrors() []error
GetErrors get happened errors from the db
func (*FakeRepository) Group ¶
func (r *FakeRepository) Group(query string) Repository
Group specify the group method on the find
func (*FakeRepository) HasBlockGlobalUpdate ¶
func (r *FakeRepository) HasBlockGlobalUpdate() bool
HasBlockGlobalUpdate return state of block
func (*FakeRepository) HasTable ¶
func (r *FakeRepository) HasTable(value interface{}) bool
HasTable check has table or not
func (*FakeRepository) Having ¶
func (r *FakeRepository) Having(query interface{}, values ...interface{}) Repository
Having specify HAVING conditions for GROUP BY
func (*FakeRepository) InstantSet ¶
func (r *FakeRepository) InstantSet(name string, value interface{}) Repository
InstantSet instant set setting, will affect current db
func (*FakeRepository) IsSingularTable ¶
func (r *FakeRepository) IsSingularTable() bool
func (*FakeRepository) Joins ¶
func (r *FakeRepository) Joins(query string, args ...interface{}) Repository
Joins specify Joins conditions
db.Joins("JOIN emails ON emails.user_id = users.id AND emails.email = ?", "jinzhu@example.org").Find(&user)
func (*FakeRepository) Last ¶
func (r *FakeRepository) Last(out interface{}, where ...interface{}) Repository
Last find last record that match given conditions, order by primary key
func (*FakeRepository) Limit ¶
func (r *FakeRepository) Limit(limit interface{}) Repository
Limit specify the number of records to be retrieved
func (*FakeRepository) Log ¶
func (r *FakeRepository) Log(v ...interface{})
func (*FakeRepository) LogMode ¶
func (r *FakeRepository) LogMode(enable bool) Repository
LogMode set log mode, `true` for detailed logs, `false` for no log, default, will only print error logs
func (*FakeRepository) Mock ¶
func (r *FakeRepository) Mock(method string, data interface{}) *FakeRepository
func (*FakeRepository) Model ¶
func (r *FakeRepository) Model(value interface{}) Repository
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 (*FakeRepository) ModifyColumn ¶
func (r *FakeRepository) ModifyColumn(column string, typ string) Repository
ModifyColumn modify column to type
func (*FakeRepository) New ¶
func (r *FakeRepository) New() Repository
New clone a new db connection without search conditions
func (*FakeRepository) NewRecord ¶
func (r *FakeRepository) NewRecord(value interface{}) bool
NewRecord check if value's primary key is blank
func (*FakeRepository) NewScope ¶
func (r *FakeRepository) NewScope(value interface{}) *Scope
NewScope create a scope for current operation
func (*FakeRepository) Not ¶
func (r *FakeRepository) Not(query interface{}, args ...interface{}) Repository
Not filter records that don't match current conditions, similar to `Where`
func (*FakeRepository) Offset ¶
func (r *FakeRepository) Offset(offset interface{}) Repository
Offset specify the number of records to skip before starting to return the records
func (*FakeRepository) Omit ¶
func (r *FakeRepository) Omit(columns ...string) Repository
Omit specify fields that you want to ignore when saving to database for creating, updating
func (*FakeRepository) Or ¶
func (r *FakeRepository) Or(query interface{}, args ...interface{}) Repository
Or filter records that match before conditions or this one, similar to `Where`
func (*FakeRepository) Order ¶
func (r *FakeRepository) Order(value interface{}, reorder ...bool) Repository
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 (*FakeRepository) Parent ¶
func (r *FakeRepository) Parent() Repository
func (*FakeRepository) Pluck ¶
func (r *FakeRepository) Pluck(column string, value interface{}) Repository
Pluck used to query single column from a model as a map
var ages []int64
db.Find(&users).Pluck("age", &ages)
func (*FakeRepository) Preload ¶
func (r *FakeRepository) Preload(column string, conditions ...interface{}) Repository
Preload preload associations with given conditions
db.Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users)
func (*FakeRepository) Print ¶
func (r *FakeRepository) Print(v ...interface{})
func (*FakeRepository) QueryExpr ¶
func (r *FakeRepository) QueryExpr() *Expression
QueryExpr returns the query as expr object
func (*FakeRepository) Raw ¶
func (r *FakeRepository) Raw(sql string, values ...interface{}) Repository
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 (*FakeRepository) RecordNotFound ¶
func (r *FakeRepository) RecordNotFound() bool
RecordNotFound check if returning ErrRecordNotFound error
func (*FakeRepository) Related ¶
func (r *FakeRepository) Related(value interface{}, foreignKeys ...string) Repository
Related get related associations
func (*FakeRepository) RemoveForeignKey ¶
func (r *FakeRepository) RemoveForeignKey(field string, dest string) Repository
RemoveForeignKey Remove foreign key from the given scope, e.g:
db.Model(&User{}).RemoveForeignKey("city_id", "cities(id)")
func (*FakeRepository) RemoveIndex ¶
func (r *FakeRepository) RemoveIndex(indexName string) Repository
RemoveIndex remove index with name
func (*FakeRepository) Rollback ¶
func (r *FakeRepository) Rollback() Repository
Rollback rollback a transaction
func (*FakeRepository) Row ¶
func (r *FakeRepository) Row() *sql.Row
Row return `*sql.Row` with given conditions
func (*FakeRepository) Rows ¶
func (r *FakeRepository) Rows() (*sql.Rows, error)
Rows return `*sql.Rows` with given conditions
func (*FakeRepository) RowsAffected ¶
func (r *FakeRepository) RowsAffected() int64
func (*FakeRepository) SQLCommonDB ¶
func (r *FakeRepository) SQLCommonDB() SQLCommon
func (*FakeRepository) Save ¶
func (r *FakeRepository) Save(value interface{}) Repository
Save update value in database, if the value doesn't have primary key, will insert it
func (*FakeRepository) Scan ¶
func (r *FakeRepository) Scan(dest interface{}) Repository
Scan scan value to a struct
func (*FakeRepository) ScanRows ¶
func (r *FakeRepository) ScanRows(rows *sql.Rows, result interface{}) error
ScanRows scan `*sql.Rows` to give struct
func (*FakeRepository) Scopes ¶
func (r *FakeRepository) Scopes(funcs ...func(Repository) Repository) Repository
func (*FakeRepository) Search ¶
func (r *FakeRepository) Search() *Search
func (*FakeRepository) Select ¶
func (r *FakeRepository) Select(query interface{}, args ...interface{}) Repository
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 (*FakeRepository) Set ¶
func (r *FakeRepository) Set(name string, value interface{}) Repository
Set set setting by name, which could be used in callbacks, will clone a new db, and update its setting
func (*FakeRepository) SetCallbacks ¶
func (r *FakeRepository) SetCallbacks(cb *Callback) Repository
func (*FakeRepository) SetDialect ¶
func (r *FakeRepository) SetDialect(d Dialect) Repository
func (*FakeRepository) SetError ¶
func (r *FakeRepository) SetError(err error) Repository
func (*FakeRepository) SetIsSingularTable ¶
func (r *FakeRepository) SetIsSingularTable(singularTable bool) Repository
func (*FakeRepository) SetJoinTableHandler ¶
func (r *FakeRepository) SetJoinTableHandler(source interface{}, column string, handler JoinTableHandlerInterface)
SetJoinTableHandler set a model's join table handler for a relation
func (*FakeRepository) SetLogger ¶
func (r *FakeRepository) SetLogger(log Logger) Repository
SetLogger replace default logger
func (*FakeRepository) SetParent ¶
func (r *FakeRepository) SetParent(p Repository) Repository
func (*FakeRepository) SetRowsAffected ¶
func (r *FakeRepository) SetRowsAffected(row int64) Repository
func (*FakeRepository) SetSQLCommonDB ¶
func (r *FakeRepository) SetSQLCommonDB(sc SQLCommon) Repository
func (*FakeRepository) SetSearch ¶
func (r *FakeRepository) SetSearch(search *Search) Repository
func (*FakeRepository) SetValue ¶
func (r *FakeRepository) SetValue(v interface{}) Repository
func (*FakeRepository) SetValues ¶
func (r *FakeRepository) SetValues(vals map[string]interface{}) Repository
func (*FakeRepository) SingularTable ¶
func (r *FakeRepository) SingularTable(enable bool)
SingularTable use singular table by default
func (*FakeRepository) Slog ¶
func (r *FakeRepository) Slog(sql string, t time.Time, vars ...interface{})
func (*FakeRepository) SqlDB ¶
func (r *FakeRepository) SqlDB() *sql.DB
DB get `*sql.DB` from current connection If the underlying database connection is not a *sql.DB, returns nil
func (*FakeRepository) SubQuery ¶
func (r *FakeRepository) SubQuery() *Expression
SubQuery returns the query as sub query
func (*FakeRepository) Table ¶
func (r *FakeRepository) Table(name string) Repository
Table specify the table you would like to run db operations
func (*FakeRepository) Take ¶
func (r *FakeRepository) Take(out interface{}, where ...interface{}) Repository
Take return a record that match given conditions, the order will depend on the database implementation
func (*FakeRepository) Unscoped ¶
func (r *FakeRepository) Unscoped() Repository
Unscoped return all record including deleted record, refer Soft Delete https://jinzhu.github.io/gorm/crud.html#soft-delete
func (*FakeRepository) Update ¶
func (r *FakeRepository) Update(attrs ...interface{}) Repository
Update update attributes with callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update
func (*FakeRepository) UpdateColumn ¶
func (r *FakeRepository) UpdateColumn(attrs ...interface{}) Repository
UpdateColumn update attributes without callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update
func (*FakeRepository) UpdateColumns ¶
func (r *FakeRepository) UpdateColumns(values interface{}) Repository
UpdateColumns update attributes without callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update
func (*FakeRepository) Updates ¶
func (r *FakeRepository) Updates(values interface{}, ignoreProtectedAttrs ...bool) Repository
Updates update attributes with callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update
func (*FakeRepository) Value ¶
func (r *FakeRepository) Value() interface{}
func (*FakeRepository) Values ¶
func (r *FakeRepository) Values() map[string]interface{}
func (*FakeRepository) Where ¶
func (r *FakeRepository) Where(query interface{}, args ...interface{}) Repository
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 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 Repository, 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 Repository, 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 Repository, source interface{}) Repository
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 Repository) 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 Repository) string
// Add create relationship in join table for source and destination
Add(handler JoinTableHandlerInterface, db Repository, source interface{}, destination interface{}) error
// Delete delete relationship in join table for sources
Delete(handler JoinTableHandlerInterface, db Repository, sources ...interface{}) error
// JoinWith query with `Join` conditions
JoinWith(handler JoinTableHandlerInterface, db Repository, source interface{}) Repository
// 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 Mocker ¶
type Mocker interface {
Mock(method string, data interface{}) *FakeRepository
Expect(err error)
}
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 Repository) 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 Repository ¶
type Repository interface {
AddError(err error) error
AddForeignKey(field string, dest string, onDelete string, onUpdate string) Repository
AddIndex(indexName string, columns ...string) Repository
AddUniqueIndex(indexName string, columns ...string) Repository
Assign(attrs ...interface{}) Repository
Association(column string) *Association
Attrs(attrs ...interface{}) Repository
AutoMigrate(values ...interface{}) Repository
Begin() Repository
BlockGlobalUpdate(enable bool) Repository
Callback() *Callback
Close() error
Commit() Repository
CommonDB() SQLCommon
Count(value interface{}) Repository
Create(value interface{}) Repository
CreateTable(models ...interface{}) Repository
SqlDB() *sql.DB
Debug() Repository
Delete(value interface{}, where ...interface{}) Repository
Dialect() Dialect
DropColumn(column string) Repository
DropTable(values ...interface{}) Repository
DropTableIfExists(values ...interface{}) Repository
Exec(sql string, values ...interface{}) Repository
Find(out interface{}, where ...interface{}) Repository
First(out interface{}, where ...interface{}) Repository
FirstOrCreate(out interface{}, where ...interface{}) Repository
FirstOrInit(out interface{}, where ...interface{}) Repository
Get(name string) (value interface{}, ok bool)
GetErrors() []error
Group(query string) Repository
HasBlockGlobalUpdate() bool
HasTable(value interface{}) bool
Having(query interface{}, values ...interface{}) Repository
InstantSet(name string, value interface{}) Repository
Joins(query string, args ...interface{}) Repository
Last(out interface{}, where ...interface{}) Repository
Limit(limit interface{}) Repository
LogMode(enable bool) Repository
Model(value interface{}) Repository
ModifyColumn(column string, typ string) Repository
New() Repository
NewRecord(value interface{}) bool
NewScope(value interface{}) *Scope
Not(query interface{}, args ...interface{}) Repository
Offset(offset interface{}) Repository
Omit(columns ...string) Repository
Or(query interface{}, args ...interface{}) Repository
Order(value interface{}, reorder ...bool) Repository
Pluck(column string, value interface{}) Repository
Preload(column string, conditions ...interface{}) Repository
QueryExpr() *Expression
Raw(sql string, values ...interface{}) Repository
RecordNotFound() bool
Related(value interface{}, foreignKeys ...string) Repository
RemoveForeignKey(field string, dest string) Repository
RemoveIndex(indexName string) Repository
Rollback() Repository
Row() *sql.Row
Rows() (*sql.Rows, error)
Save(value interface{}) Repository
Scan(dest interface{}) Repository
ScanRows(rows *sql.Rows, result interface{}) error
Scopes(funcs ...func(Repository) Repository) Repository
Select(query interface{}, args ...interface{}) Repository
Set(name string, value interface{}) Repository
SetJoinTableHandler(source interface{}, column string, handler JoinTableHandlerInterface)
SetLogger(log Logger) Repository
SingularTable(enable bool)
SubQuery() *Expression
Table(name string) Repository
Take(out interface{}, where ...interface{}) Repository
Unscoped() Repository
Update(attrs ...interface{}) Repository
UpdateColumn(attrs ...interface{}) Repository
UpdateColumns(values interface{}) Repository
Updates(values interface{}, ignoreProtectedAttrs ...bool) Repository
Where(query interface{}, args ...interface{}) Repository
Value() interface{}
SetValue(v interface{}) Repository
Error() error
SetError(err error) Repository
RowsAffected() int64
SetRowsAffected(row int64) Repository
Search() *Search
SetSearch(s *Search) Repository
Parent() Repository
SetParent(p Repository) Repository
SQLCommonDB() SQLCommon
SetSQLCommonDB(sc SQLCommon) Repository
Callbacks() *Callback
SetCallbacks(cb *Callback) Repository
IsSingularTable() bool
SetIsSingularTable(singularTable bool) Repository
SetDialect(d Dialect) Repository
Clone() Repository
Log(v ...interface{})
Slog(sql string, t time.Time, vars ...interface{})
Print(v ...interface{})
Values() map[string]interface{}
SetValues(vals map[string]interface{}) Repository
}
func Open ¶
func Open(dialect string, args ...interface{}) (db Repository, err error)
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/hidevopsio/gorm/dialects/mysql" // import _ "github.com/hidevopsio/gorm/dialects/postgres" // import _ "github.com/hidevopsio/gorm/dialects/sqlite" // import _ "github.com/hidevopsio/gorm/dialects/mssql"
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) NewDB ¶
func (scope *Scope) NewDB() Repository
NewDB create a new DB without search information
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_mysql.go
- dialect_postgres.go
- dialect_sqlite3.go
- errors.go
- fake.go
- field.go
- interface.go
- join_table_handler.go
- logger.go
- main.go
- model.go
- model_struct.go
- scope.go
- search.go
- utils.go