Documentation
¶
Index ¶
- Constants
- Variables
- func FieldColumn(value reflect.Value, name string) reflect.Value
- func FieldValue(value reflect.Value, index int) reflect.Value
- func GetType(value interface{}) reflect.Type
- func IndirectValue(value interface{}) reflect.Value
- func IsZero(value reflect.Value) bool
- func RegisterDialect(name string, dialect Dialect)
- func SetZero(value reflect.Value) reflect.Value
- type Association
- func (a *Association) Append(values ...interface{}) *Association
- func (a *Association) Clear() *Association
- func (a *Association) Count() int
- func (a *Association) Delete(values ...interface{}) *Association
- func (a *Association) Find(value interface{}) *Association
- func (a *Association) Replace(values ...interface{}) *Association
- type Callbacks
- func (c *Callbacks) Create() *CallbacksProcessor
- func (c *Callbacks) Delete() *CallbacksProcessor
- func (c *Callbacks) GetCreates() ScopedFuncs
- func (c *Callbacks) GetDeletes() ScopedFuncs
- func (c *Callbacks) GetQueries() ScopedFuncs
- func (c *Callbacks) GetUpdates() ScopedFuncs
- func (c *Callbacks) Query() *CallbacksProcessor
- func (c *Callbacks) RowQuery() *CallbacksProcessor
- func (c *Callbacks) Update() *CallbacksProcessor
- type CallbacksProcessor
- func (c *CallbacksProcessor) After(callbackName string) *CallbacksProcessor
- func (c *CallbacksProcessor) Before(callbackName string) *CallbacksProcessor
- func (c *CallbacksProcessor) Get(callbackName string) ScopedFunc
- func (c *CallbacksProcessor) Register(callbackName string, callback ScopedFunc)
- func (c *CallbacksProcessor) Remove(callbackName string)
- func (c *CallbacksProcessor) Replace(callbackName string, callback ScopedFunc)
- type CallbacksProcessors
- type Collector
- type DB
- type DBCon
- func (con *DBCon) AddError(err error) error
- func (con *DBCon) AddForeignKey(field string, dest string, onDelete string, onUpdate string) *DBCon
- func (con *DBCon) AddIndex(indexName string, columns ...string) *DBCon
- func (con *DBCon) AddUniqueIndex(indexName string, columns ...string) *DBCon
- func (con *DBCon) AsSQLDB() sqlInterf
- func (con *DBCon) Assign(attrs ...interface{}) *DBCon
- func (con *DBCon) Association(column string) *Association
- func (con *DBCon) Attrs(attrs ...interface{}) *DBCon
- func (con *DBCon) AutoMigrate(values ...interface{}) *DBCon
- func (con *DBCon) Begin() *DBCon
- func (con *DBCon) Callback() *Callbacks
- func (con *DBCon) Close() error
- func (con *DBCon) Commit() *DBCon
- func (con *DBCon) Count(value interface{}) *DBCon
- func (con *DBCon) Create(value interface{}) *DBCon
- func (con *DBCon) CreateTable(models ...interface{}) *DBCon
- func (con *DBCon) DB() *sql.DB
- func (con *DBCon) Debug() *DBCon
- func (con *DBCon) Delete(value interface{}, where ...interface{}) *DBCon
- func (con *DBCon) Dialect() Dialect
- func (con *DBCon) DropColumn(column string) *DBCon
- func (con *DBCon) DropTable(values ...interface{}) *DBCon
- func (con *DBCon) DropTableIfExists(values ...interface{}) *DBCon
- func (con *DBCon) Exec(sql string, values ...interface{}) *DBCon
- func (con *DBCon) Find(out interface{}, where ...interface{}) *DBCon
- func (con *DBCon) First(entity interface{}, where ...interface{}) *DBCon
- func (con *DBCon) FirstOrCreate(out interface{}, where ...interface{}) *DBCon
- func (con *DBCon) FirstOrInit(out interface{}, where ...interface{}) *DBCon
- func (con *DBCon) Get(name string) (interface{}, bool)
- func (con *DBCon) GetErrors() []error
- func (con *DBCon) Group(query string) *DBCon
- func (con *DBCon) HasTable(value interface{}) bool
- func (con *DBCon) Having(query string, values ...interface{}) *DBCon
- func (con *DBCon) Joins(query string, args ...interface{}) *DBCon
- func (con *DBCon) KnownModelStructs() map[reflect.Type]*ModelStruct
- func (con *DBCon) KnownNames(name string) string
- func (con *DBCon) Last(entity interface{}, where ...interface{}) *DBCon
- func (con *DBCon) Limit(limit interface{}) *DBCon
- func (con *DBCon) Log(v ...interface{})
- func (con *DBCon) LogMode(enable bool) *DBCon
- func (con *DBCon) Model(value interface{}) *DBCon
- func (con *DBCon) ModifyColumn(column string, typ string) *DBCon
- func (con *DBCon) NewRecord(value interface{}) bool
- func (con *DBCon) NewScope(value interface{}) *Scope
- func (con *DBCon) Not(query interface{}, args ...interface{}) *DBCon
- func (con *DBCon) Offset(offset interface{}) *DBCon
- func (con *DBCon) Omit(columns ...string) *DBCon
- func (con *DBCon) Or(query interface{}, args ...interface{}) *DBCon
- func (con *DBCon) Order(value interface{}, reorder ...bool) *DBCon
- func (con *DBCon) Pluck(column string, value interface{}) *DBCon
- func (con *DBCon) Preload(column string, conditions ...interface{}) *DBCon
- func (con *DBCon) Raw(sql string, values ...interface{}) *DBCon
- func (con *DBCon) RecordNotFound() bool
- func (con *DBCon) Related(value interface{}, foreignKeys ...string) *DBCon
- func (con *DBCon) RemoveIndex(indexName string) *DBCon
- func (con *DBCon) Rollback() *DBCon
- func (con *DBCon) Row() *sql.Row
- func (con *DBCon) Rows() (*sql.Rows, error)
- func (con *DBCon) Save(value interface{}) *DBCon
- func (con *DBCon) Scan(dest interface{}) *DBCon
- func (con *DBCon) ScanRows(rows *sql.Rows, result interface{}) error
- func (con *DBCon) Scopes(funcs ...DBConFunc) *DBCon
- func (con *DBCon) Select(query string, args ...interface{}) *DBCon
- func (con *DBCon) Set(name string, value interface{}) *DBCon
- func (con *DBCon) SetJoinTableHandler(source interface{}, column string, handler JoinTableHandlerInterface)
- func (con *DBCon) SetLogMode(mode int)
- func (con *DBCon) SetLogger(log logger)
- func (con *DBCon) SingularTable(enable bool)
- func (con *DBCon) Table(name string) *DBCon
- func (con *DBCon) Unscoped() *DBCon
- func (con *DBCon) Update(attrs ...interface{}) *DBCon
- func (con *DBCon) UpdateColumn(attrs ...interface{}) *DBCon
- func (con *DBCon) UpdateColumns(values interface{}) *DBCon
- func (con *DBCon) Updates(values interface{}, ignoreProtectedAttrs ...bool) *DBCon
- func (con *DBCon) Where(query interface{}, args ...interface{}) *DBCon
- type DBConFunc
- type DefaultForeignKeyNamer
- type Dialect
- type GormErrors
- type JoinTableForeignKey
- type JoinTableHandler
- func (h JoinTableHandler) Add(handler JoinTableHandlerInterface, con *DBCon, source interface{}, ...) error
- func (h JoinTableHandler) Delete(handler JoinTableHandlerInterface, con *DBCon) error
- func (h *JoinTableHandler) DestinationForeignKeys() []JoinTableForeignKey
- func (h *JoinTableHandler) GetHandlerStruct() *JoinTableHandler
- func (h JoinTableHandler) JoinWith(handler JoinTableHandlerInterface, con *DBCon, source interface{}) *DBCon
- func (h *JoinTableHandler) SetTable(name string)
- func (h *JoinTableHandler) Setup(field *StructField, source reflect.Type, destination reflect.Type)
- func (h *JoinTableHandler) SourceForeignKeys() []JoinTableForeignKey
- func (h JoinTableHandler) String() string
- func (h JoinTableHandler) Table(db *DBCon) string
- type JoinTableHandlerInterface
- type JoinTableInfo
- type LogWriter
- type Logger
- type Model
- type ModelStruct
- func (m *ModelStruct) Create(scope *Scope)
- func (m *ModelStruct) FieldByName(column string, con *DBCon) (*StructField, bool)
- func (m *ModelStruct) HasColumn(column string) bool
- func (m *ModelStruct) Interface() interface{}
- func (m *ModelStruct) PKs() StructFields
- func (m ModelStruct) String() string
- func (m *ModelStruct) StructFields() StructFields
- func (m *ModelStruct) TableName(db *DBCon) string
- type Scope
- func (s *Scope) CallMethod(methodName string)
- func (s *Scope) Err(err error) error
- func (s *Scope) Exec() *Scope
- func (s *Scope) FieldByName(name string) (*StructField, bool)
- func (s *Scope) Fields() StructFields
- func (s *Scope) Get(settingType uint64) (interface{}, bool)
- func (s *Scope) GetModelStruct() *ModelStruct
- func (s *Scope) HasError() bool
- func (s *Scope) PK() *StructField
- func (s *Scope) PKName() string
- func (s *Scope) PKs() StructFields
- func (s *Scope) PrimaryField() *StructField
- func (s *Scope) PrimaryFields() StructFields
- func (s *Scope) PrimaryKey() string
- func (s *Scope) PrimaryKeyValue() interface{}
- func (s *Scope) PrimaryKeyZero() bool
- func (s *Scope) Raw(sql string) *Scope
- func (s *Scope) Set(settingType uint64, value interface{}) *Scope
- func (s *Scope) SetColumn(column interface{}, value interface{}) error
- func (s *Scope) TableName() string
- func (s *Scope) Warn(v ...interface{})
- type ScopedFunc
- type ScopedFuncs
- type Search
- func (s *Search) Assign(attrs ...interface{}) *Search
- func (s *Search) Attrs(attrs ...interface{}) *Search
- func (s *Search) Clone() *Search
- func (s *Search) Exec(scope *Scope) (sql.Result, error)
- func (s *Search) Group(query string) *Search
- func (s *Search) Having(query string, values ...interface{}) *Search
- func (s *Search) IsRaw() bool
- 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) Query(scope *Scope) (*sql.Rows, error)
- func (s *Search) QueryRow(scope *Scope) *sql.Row
- func (s *Search) Select(query string, args ...interface{}) *Search
- func (s *Search) SetRaw() *Search
- func (s *Search) Where(query interface{}, values ...interface{}) *Search
- func (s *Search) Wheres(wheres ...interface{}) *Search
- type SqlConditions
- type SqlPair
- type StrSlice
- type StructField
- func (f *StructField) GetAssocFKs() StrSlice
- func (f *StructField) GetAssociationDBNames() StrSlice
- func (f *StructField) GetAssociationForeignFieldNames() StrSlice
- func (f *StructField) GetFKs() StrSlice
- func (f *StructField) GetForeignDBNames() StrSlice
- func (f *StructField) GetForeignFieldNames() StrSlice
- func (f *StructField) GetStrSetting(named uint8) string
- func (f *StructField) HasDefaultValue() bool
- func (f *StructField) HasNotNullSetting() bool
- func (f *StructField) HasRelations() bool
- func (f *StructField) HasSetting(named uint8) bool
- func (f *StructField) Interface() interface{}
- func (f *StructField) IsAutoIncrement() bool
- func (f *StructField) IsBlank() bool
- func (f *StructField) IsEmbedOrAnon() bool
- func (f *StructField) IsForeignKey() bool
- func (f *StructField) IsIgnored() bool
- func (f *StructField) IsNormal() bool
- func (f *StructField) IsPointer() bool
- func (f *StructField) IsPrimaryKey() bool
- func (f *StructField) IsScanner() bool
- func (f *StructField) IsSlice() bool
- func (f *StructField) IsStruct() bool
- func (f *StructField) IsTime() bool
- func (f *StructField) JoinHandler() JoinTableHandlerInterface
- func (f *StructField) LinkPoly(withField *StructField, tableName string)
- func (f *StructField) ParseFieldStructForDialect() (reflect.Value, string, int, string)
- func (f *StructField) RelKind() uint8
- func (f *StructField) RelationIsBelongsTo() bool
- func (f *StructField) RelationIsHasMany() bool
- func (f *StructField) RelationIsHasOne() bool
- func (f *StructField) RelationIsMany2Many() bool
- func (f *StructField) Set(value interface{}) error
- func (f *StructField) SetHasRelations()
- func (f *StructField) SetIsAutoIncrement()
- func (f *StructField) SetIsBlank()
- func (f *StructField) SetIsForeignKey()
- func (f *StructField) SetIsNormal()
- func (f *StructField) SetIsPrimaryKey()
- func (f *StructField) SetTagSetting(named uint8, value interface{})
- func (f StructField) String() string
- func (f *StructField) UnsetCheckRelations()
- func (f *StructField) UnsetIsAutoIncrement()
- func (f *StructField) UnsetIsBlank()
- func (f *StructField) UnsetIsPrimaryKey()
- func (f *StructField) UnsetTagSetting(named uint8)
- func (f *StructField) WillCheckRelations() bool
- type StructFields
- type TagSettings
- type Uint8Map
Constants ¶
const ( CommonDialectName = "common" CommonBoolean = "BOOLEAN" CommonInteger = "INTEGER" CommonAutoIncrement = "INTEGER AUTO_INCREMENT" CommonBigint = "BIGINT" CommonFloat = "FLOAT" CommonVarchar = "VARCHAR" CommonTimestamp = "TIMESTAMP" CommonBinary = "BINARY" CommonHasindexsql = "SELECT count(*) FROM INFORMATION_SCHEMA.STATISTICS WHERE table_schema = ? AND table_name = ? AND index_name = ?" CommonDropindex = "DROP INDEX %v" CommonHastableSql = "SELECT count(*) FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = ? AND table_name = ?" CommonHascolumnSql = "SELECT count(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = ? AND table_name = ? AND column_name = ?" CommonSelectDb = "SELECT DATABASE()" )
const ( MysqlDialectName = "mysql" MysqlBooleanType = "boolean" MysqlIntType = "int" MysqlAutoIncrement = "AUTO_INCREMENT" MysqlUnsigned = "unsigned" MysqlBigint = "bigint" MysqlDouble = "double" MysqlLongtext = "longtext" MysqlVarchar = "varchar" MysqlTimestamp = "timestamp" MysqlLongblog = "longblob" MysqlVarbinary = "varbinary" MysqlHasForeignKey = "" /* 156-byte string literal not displayed */ MysqlDropIndex = "DROP INDEX %v ON %v" MysqlSelectDb = "SELECT DATABASE()" )
const ( PgDialectName = "postgres" PgBooleanType = "boolean" PgIntType = "integer" PgSerial = "serial" PgBigSerial = "bigserial" PgBigint = "bigint" PgNumeric = "numeric" PgText = "text" PgTimestamp = "timestamp with time zone" PgVarchar = "varchar(%d)" PgHstore = "hstore" PgBytea = "bytea" PgUuid = "uuid" PgHasindexSql = "SELECT count(*) FROM pg_indexes WHERE tablename = $1 AND indexname = $2" PgHasfkSql = "" /* 128-byte string literal not displayed */ PgHastableSql = "SELECT count(*) FROM INFORMATION_SCHEMA.tables WHERE table_name = $1 AND table_type = 'BASE TABLE'" PgHascolumnSql = "SELECT count(*) FROM INFORMATION_SCHEMA.columns WHERE table_name = $1 AND column_name = $2" PgCurrdbSql = "SELECT CURRENT_DATABASE()" )
const ( SqliteDialectName = "sqlite3" SqliteBool = "bool" SqliteInteger = "integer" SqlitePk = "integer primary key autoincrement" SqliteBigint = "bigint" SqliteReal = "real" SqliteVarchar = "varchar(%d)" SqliteDatetime = "datetime" SqliteBlob = "blob" SqliteText = "text" SqliteHasindexSql = "SELECT count(*) FROM sqlite_master WHERE tbl_name = ? AND sql LIKE '%%INDEX %v ON%%'" SqliteHastableSql = "SELECT count(*) FROM sqlite_master WHERE type='table' AND name=?" SqliteHascolumnSql = "SELECT count(*) FROM sqlite_master WHERE tbl_name = ? AND (sql LIKE '%%\"%v\" %%' OR sql LIKE '%%%v %%');\n" )
const ( FieldCreatedAt = "CreatedAt" FieldUpdatedAt = "UpdatedAt" FieldDeletedAt = "DeletedAt" LogOff int = 1 LogVerbose int = 2 LogDebug int = 3 )
Variables ¶
var ( // DefaultTableNameHandler default table name handler DefaultTableNameHandler = func(con *DBCon, defaultTableName string) string { return defaultTableName } // 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() // } NowFunc = func() time.Time { return time.Now() } // 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") // 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") )
Functions ¶
func FieldColumn ¶
using inline advantage
func FieldValue ¶
using inline advantage
func IndirectValue ¶
using inline advantage IndirectValue return scope's reflect value's indirect value
func RegisterDialect ¶
RegisterDialect register new dialect
Types ¶
type Association ¶
type Association struct { Error error // contains filtered or unexported fields }
TODO : @Badu - Association has a field named Error - should be passed to DBCon TODO : @Badu - Association Mode contains some helper methods to handle relationship things easily.
func (*Association) Append ¶
func (a *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 (a *Association) Clear() *Association
Clear remove relationship between source & current associations, won't delete those associations
func (*Association) Count ¶
func (a *Association) Count() int
Count return the count of current associations
func (*Association) Delete ¶
func (a *Association) Delete(values ...interface{}) *Association
Delete remove relationship between source & passed arguments, but won't delete those arguments
func (*Association) Find ¶
func (a *Association) Find(value interface{}) *Association
Find find out all related associations
func (*Association) Replace ¶
func (a *Association) Replace(values ...interface{}) *Association
Replace replace current associations with new one
type Callbacks ¶
type Callbacks struct {
// contains filtered or unexported fields
}
Callback is a struct that contains all CURD 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 (*Callbacks) Create ¶
func (c *Callbacks) Create() *CallbacksProcessor
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 (*Callbacks) Delete ¶
func (c *Callbacks) Delete() *CallbacksProcessor
Delete could be used to register callbacks for deleting object, refer `Create` for usage
func (*Callbacks) GetCreates ¶
func (c *Callbacks) GetCreates() ScopedFuncs
Added for tests : DO NOT USE DIRECTLY
func (*Callbacks) GetDeletes ¶
func (c *Callbacks) GetDeletes() ScopedFuncs
func (*Callbacks) GetQueries ¶
func (c *Callbacks) GetQueries() ScopedFuncs
func (*Callbacks) GetUpdates ¶
func (c *Callbacks) GetUpdates() ScopedFuncs
func (*Callbacks) Query ¶
func (c *Callbacks) Query() *CallbacksProcessor
Query could be used to register callbacks for querying objects with query methods like `Find`, `First`, `Related`, `Association`... Refer `Create` for usage
func (*Callbacks) RowQuery ¶
func (c *Callbacks) RowQuery() *CallbacksProcessor
RowQuery could be used to register callbacks for querying objects with `Row`, `Rows`, refer `Create` for usage
func (*Callbacks) Update ¶
func (c *Callbacks) Update() *CallbacksProcessor
Update could be used to register callbacks for updating object, refer `Create` for usage
type CallbacksProcessor ¶
type CallbacksProcessor struct {
// contains filtered or unexported fields
}
CallbackProcessor contains callback informations
func (*CallbacksProcessor) After ¶
func (c *CallbacksProcessor) After(callbackName string) *CallbacksProcessor
After insert a new callback after callback `callbackName`, refer `Callbacks.Create`
func (*CallbacksProcessor) Before ¶
func (c *CallbacksProcessor) Before(callbackName string) *CallbacksProcessor
Before insert a new callback before callback `callbackName`, refer `Callbacks.Create`
func (*CallbacksProcessor) Get ¶
func (c *CallbacksProcessor) Get(callbackName string) ScopedFunc
Get registered callback
db.Callback().Create().Get("gorm:create")
func (*CallbacksProcessor) Register ¶
func (c *CallbacksProcessor) Register(callbackName string, callback ScopedFunc)
Register a new callback, refer `Callbacks.Create`
func (*CallbacksProcessor) Remove ¶
func (c *CallbacksProcessor) Remove(callbackName string)
Remove a registered callback
db.Callback().Create().Remove("gorm:update_time_stamp_when_create")
func (*CallbacksProcessor) Replace ¶
func (c *CallbacksProcessor) Replace(callbackName string, callback ScopedFunc)
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 CallbacksProcessors ¶
type CallbacksProcessors []*CallbacksProcessor
easier to read and can apply methods
type DB ¶
type DB struct {
DBCon
}
declared to allow existing code to run, dbcon.Open(...) db = &gorm.DB{*dbcon}
type DBCon ¶
type DBCon struct { Error error RowsAffected int64 //TODO : @Badu - this should sit inside Scope, because it's contextual // contains filtered or unexported fields }
DBCon contains information for current db connection
func (*DBCon) AddError ¶
////////////////////////////////////////////////////////////////////////////// Errors ////////////////////////////////////////////////////////////////////////////// AddError add error to the db
func (*DBCon) AddForeignKey ¶
AddForeignKey Add foreign key to the given scope, e.g:
db.Model(&User{}).AddForeignKey("city_id", "cities(id)", "RESTRICT", "RESTRICT")
TODO : @Badu - make it work with interfaces instead of strings (field, dest)
func (*DBCon) AddUniqueIndex ¶
AddUniqueIndex add unique index for columns with given name
func (*DBCon) AsSQLDB ¶
func (con *DBCon) AsSQLDB() sqlInterf
CommonDB return the underlying `*sql.DB` or `*sql.Tx` instance, mainly intended to allow coexistence with legacy non-GORM code.
func (*DBCon) Assign ¶
Assign assign result with argument regardless it is found or not with `FirstOrInit` or `FirstOrCreate` Note : no scope
func (*DBCon) Association ¶
func (con *DBCon) Association(column string) *Association
Association start `Association Mode` to handler relations things easier in that mode
func (*DBCon) Attrs ¶
Attrs initialize struct with argument if record not found with `FirstOrInit` or `FirstOrCreate` Note : no scope
func (*DBCon) AutoMigrate ¶
AutoMigrate run auto migration for given models, will only add missing fields, won't delete/change current data
func (*DBCon) Callback ¶
Callback return `Callbacks` container, you could add/change/delete callbacks with it
db.Callback().Create().Register("update_created_at", updateCreated)
func (*DBCon) Close ¶
////////////////////////////////////////////////////////////////////////////// scoped and other methods ////////////////////////////////////////////////////////////////////////////// Close close current db connection
func (*DBCon) CreateTable ¶
CreateTable create table for models
func (*DBCon) Delete ¶
Delete delete value match given conditions, if the value has primary key, then will including the primary key as condition
func (*DBCon) DropColumn ¶
DropColumn drop a column
func (*DBCon) DropTableIfExists ¶
DropTableIfExists drop table if it is exist
func (*DBCon) FirstOrCreate ¶
FirstOrCreate find first matched record or create a new one with given conditions (only works with struct, map conditions)
func (*DBCon) FirstOrInit ¶
FirstOrInit find first matched record or initialize a new one with given conditions (only works with struct, map conditions)
func (*DBCon) Joins ¶
Joins specify Joins conditions
db.Joins("JOIN emails ON emails.user_id = users.id AND emails.email = ?", "user@example.org").Find(&user)
Note:no scope
func (*DBCon) KnownModelStructs ¶
func (con *DBCon) KnownModelStructs() map[reflect.Type]*ModelStruct
func (*DBCon) KnownNames ¶
func (*DBCon) LogMode ¶
LogMode set log mode, `true` for detailed logs, `false` for no log, default, will only print error logs
func (*DBCon) 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 (*DBCon) ModifyColumn ¶
ModifyColumn modify column to type
func (*DBCon) Not ¶
Not filter records that don't match current conditions, similar to `Where` Note : no scope
func (*DBCon) Offset ¶
Offset specify the number of records to skip before starting to return the records Note : no scope
func (*DBCon) Omit ¶
Omit specify fields that you want to ignore when saving to database for creating, updating Note : no scope
func (*DBCon) Or ¶
Or filter records that match before conditions or this one, similar to `Where` Note : no scope
func (*DBCon) 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
Note : no scope
func (*DBCon) Pluck ¶
Pluck used to query single column from a model as a map
var ages []int64 db.Find(&users).Pluck("age", &ages)
func (*DBCon) Preload ¶
Preload preload associations with given conditions
db.Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users)
Note : no scope
func (*DBCon) 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)
Note : no scope
func (*DBCon) RecordNotFound ¶
RecordNotFound check if returning ErrRecordNotFound error
func (*DBCon) RemoveIndex ¶
RemoveIndex remove index with name
func (*DBCon) Save ¶
Save update value in database, if the value doesn't have primary key, will insert it
func (*DBCon) Scopes ¶
Scopes pass current database connection to arguments `func(*DBCon) *DBCon`, 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 (*DBCon) 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 Note : no scope
func (*DBCon) Set ¶
Set set setting by name, which could be used in callbacks, will clone a new db, and update its setting
func (*DBCon) SetJoinTableHandler ¶
func (con *DBCon) SetJoinTableHandler(source interface{}, column string, handler JoinTableHandlerInterface)
SetJoinTableHandler set a model's join table handler for a relation
func (*DBCon) SetLogMode ¶
func (*DBCon) SingularTable ¶
SingularTable use singular table by default
func (*DBCon) Unscoped ¶
Unscoped return all record including deleted record, refer Soft Delete Note : no scope (as the name says)
func (*DBCon) UpdateColumn ¶
UpdateColumn update attributes without callbacks
func (*DBCon) UpdateColumns ¶
UpdateColumns update attributes without callbacks
func (*DBCon) Where ¶
////////////////////////////////////////////////////////////////////////////// "unscoped" methods ////////////////////////////////////////////////////////////////////////////// Where return a new relation, filter records with given conditions, accepts `map`, `struct` or `string` as conditions Note : no scope
type DefaultForeignKeyNamer ¶
type DefaultForeignKeyNamer struct { }
DefaultForeignKeyNamer contains the default foreign key name generator method
func (DefaultForeignKeyNamer) BuildForeignKeyName ¶
func (DefaultForeignKeyNamer) BuildForeignKeyName(tableName, field, dest string) string
type Dialect ¶
type Dialect interface { // GetName get dialect's name GetName() string // SetDB set db for dialect SetDB(db *sql.DB) // BindVar return the placeholder for actual values in SQL statements, in many dbs it is "?", Postgres using $1 BindVar(i int) string // GetQuoter returns the rune for quoting field name to avoid SQL parsing exceptions by using a reserved word as a field name //TODO : @Badu - should return a rune GetQuoter() 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 // 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 // BuildForeignKeyName returns a foreign key name for the given table, field and reference BuildForeignKeyName(tableName, field, dest string) string // CurrentDatabase return current database name CurrentDatabase() string }
Dialect interface contains behaviors that differ across SQL database
type GormErrors ¶
type GormErrors []error
Errors contains all happened errors
func (GormErrors) Add ¶
func (e GormErrors) Add(newErrors ...error) GormErrors
func (GormErrors) GetErrors ¶
func (e GormErrors) GetErrors() []error
GetErrors get all happened errors
type JoinTableForeignKey ¶
JoinTableForeignKey join table foreign key struct TODO : @Badu -this holds some sort of processed clone of FOREIGN_DB_NAMES, FOREIGN_FIELD_NAMES, ASSOCIATION_FOREIGN_FIELD_NAMES, ASSOCIATION_FOREIGN_DB_NAMES
type JoinTableHandler ¶
type JoinTableHandler struct { TableName string `sql:"-"` Source JoinTableInfo `sql:"-"` Destination JoinTableInfo `sql:"-"` }
JoinTableHandler default join table handler
func (JoinTableHandler) Add ¶
func (h JoinTableHandler) Add(handler JoinTableHandlerInterface, con *DBCon, source interface{}, destination interface{}) error
implementation of JoinTableHandlerInterface Add create relationship in join table for source and destination
func (JoinTableHandler) Delete ¶
func (h JoinTableHandler) Delete(handler JoinTableHandlerInterface, con *DBCon) error
implementation of JoinTableHandlerInterface Delete delete relationship in join table for sources
func (*JoinTableHandler) DestinationForeignKeys ¶
func (h *JoinTableHandler) DestinationForeignKeys() []JoinTableForeignKey
implementation of JoinTableHandlerInterface DestinationForeignKeys return destination foreign keys
func (*JoinTableHandler) GetHandlerStruct ¶
func (h *JoinTableHandler) GetHandlerStruct() *JoinTableHandler
for debugging
func (JoinTableHandler) JoinWith ¶
func (h JoinTableHandler) JoinWith(handler JoinTableHandlerInterface, con *DBCon, source interface{}) *DBCon
implementation of JoinTableHandlerInterface JoinWith query with `Join` conditions
func (*JoinTableHandler) SetTable ¶
func (h *JoinTableHandler) SetTable(name string)
implementation of JoinTableHandlerInterface
func (*JoinTableHandler) Setup ¶
func (h *JoinTableHandler) Setup( field *StructField, source reflect.Type, destination reflect.Type)
implementation of JoinTableHandlerInterface Setup initialize a default join table handler
func (*JoinTableHandler) SourceForeignKeys ¶
func (h *JoinTableHandler) SourceForeignKeys() []JoinTableForeignKey
implementation of JoinTableHandlerInterface SourceForeignKeys return source foreign keys
func (JoinTableHandler) String ¶
func (h JoinTableHandler) String() string
implementation of Stringer
func (JoinTableHandler) Table ¶
func (h JoinTableHandler) Table(db *DBCon) string
implementation of JoinTableHandlerInterface Table return join table's table name
type JoinTableHandlerInterface ¶
type JoinTableHandlerInterface interface { // initialize join table handler Setup(field *StructField, source reflect.Type, destination reflect.Type) // Table return join table's table name Table(db *DBCon) string // Sets table name SetTable(name string) // Add create relationship in join table for source and destination Add(handler JoinTableHandlerInterface, db *DBCon, source interface{}, destination interface{}) error // Delete delete relationship in join table for sources Delete(handler JoinTableHandlerInterface, db *DBCon) error // JoinWith query with `Join` conditions JoinWith(handler JoinTableHandlerInterface, db *DBCon, source interface{}) *DBCon // SourceForeignKeys return source foreign keys SourceForeignKeys() []JoinTableForeignKey // DestinationForeignKeys return destination foreign keys DestinationForeignKeys() []JoinTableForeignKey //for debugging purposes GetHandlerStruct() *JoinTableHandler }
JoinTableHandlerInterface is an interface for how to handle many2many relations
type JoinTableInfo ¶
type JoinTableInfo 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 ¶
ModelStruct model definition
func (*ModelStruct) Create ¶
func (m *ModelStruct) Create(scope *Scope)
func (*ModelStruct) FieldByName ¶
func (m *ModelStruct) FieldByName(column string, con *DBCon) (*StructField, bool)
func (*ModelStruct) HasColumn ¶
func (m *ModelStruct) HasColumn(column string) bool
func (*ModelStruct) Interface ¶
func (m *ModelStruct) Interface() interface{}
func (*ModelStruct) PKs ¶
func (m *ModelStruct) PKs() StructFields
func (*ModelStruct) StructFields ¶
func (m *ModelStruct) StructFields() StructFields
func (*ModelStruct) TableName ¶
func (m *ModelStruct) TableName(db *DBCon) string
TableName get model's table name
type Scope ¶
type Scope struct { Search *Search Value 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) FieldByName ¶
func (s *Scope) FieldByName(name string) (*StructField, bool)
FieldByName find `gorm.StructField` with field name or db name
func (*Scope) Fields ¶
func (s *Scope) Fields() StructFields
Fields get value's fields from ModelStruct
func (*Scope) GetModelStruct ¶
func (s *Scope) GetModelStruct() *ModelStruct
GetModelStruct get value's model struct, relationships based on struct and tag definition
func (*Scope) PK ¶
func (s *Scope) PK() *StructField
was PrimaryField() - PK() 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) PKs ¶
func (s *Scope) PKs() StructFields
was PrimaryFields() : PKs() return scope's primary fields
func (*Scope) PrimaryKeyValue ¶
func (s *Scope) PrimaryKeyValue() interface{}
PrimaryKeyValue get the primary key's value
func (*Scope) PrimaryKeyZero ¶
PrimaryKeyZero check main primary field's value is blank or not
type ScopedFunc ¶
type ScopedFunc func(*Scope)
type Search ¶
type Search struct { Conditions SqlConditions SQL string SQLVars []interface{} Value interface{} //TODO : @Badu - moved here from DBCon - in the end should use Scope's Value // contains filtered or unexported fields }
type SqlConditions ¶
type SqlConditions map[sqlConditionType]sqlCondition
func (SqlConditions) CompareInit ¶
func (c SqlConditions) CompareInit(cond SqlConditions) bool
utils for test case
func (SqlConditions) CompareOrder ¶
func (c SqlConditions) CompareOrder(cond SqlConditions) bool
utils for test case
func (SqlConditions) CompareSelect ¶
func (c SqlConditions) CompareSelect(cond SqlConditions) bool
utils for test case
func (SqlConditions) CompareWhere ¶
func (c SqlConditions) CompareWhere(cond SqlConditions) bool
utils for test case
type StrSlice ¶
type StrSlice []string
============================================ Slice of strings for better reading ============================================
type StructField ¶
type StructField struct { DBName string StructName string Names []string Value reflect.Value Type reflect.Type // contains filtered or unexported fields }
StructField model field's struct definition
func NewStructField ¶
func NewStructField(fromStruct reflect.StructField, toDBName string) (*StructField, error)
func (*StructField) GetAssocFKs ¶
func (f *StructField) GetAssocFKs() StrSlice
func (*StructField) GetAssociationDBNames ¶
func (f *StructField) GetAssociationDBNames() StrSlice
func (*StructField) GetAssociationForeignFieldNames ¶
func (f *StructField) GetAssociationForeignFieldNames() StrSlice
func (*StructField) GetFKs ¶
func (f *StructField) GetFKs() StrSlice
func (*StructField) GetForeignDBNames ¶
func (f *StructField) GetForeignDBNames() StrSlice
func (*StructField) GetForeignFieldNames ¶
func (f *StructField) GetForeignFieldNames() StrSlice
func (*StructField) GetStrSetting ¶
func (f *StructField) GetStrSetting(named uint8) string
TODO : make methods for each setting (readable code)
func (*StructField) HasDefaultValue ¶
func (f *StructField) HasDefaultValue() bool
func (*StructField) HasNotNullSetting ¶
func (f *StructField) HasNotNullSetting() bool
func (*StructField) HasRelations ¶
func (f *StructField) HasRelations() bool
func (*StructField) HasSetting ¶
func (f *StructField) HasSetting(named uint8) bool
gets a key (for code readability)
func (*StructField) Interface ¶
func (f *StructField) Interface() interface{}
func (*StructField) IsAutoIncrement ¶
func (f *StructField) IsAutoIncrement() bool
func (*StructField) IsBlank ¶
func (f *StructField) IsBlank() bool
func (*StructField) IsEmbedOrAnon ¶
func (f *StructField) IsEmbedOrAnon() bool
func (*StructField) IsForeignKey ¶
func (f *StructField) IsForeignKey() bool
func (*StructField) IsIgnored ¶
func (f *StructField) IsIgnored() bool
func (*StructField) IsNormal ¶
func (f *StructField) IsNormal() bool
func (*StructField) IsPointer ¶
func (f *StructField) IsPointer() bool
func (*StructField) IsPrimaryKey ¶
func (f *StructField) IsPrimaryKey() bool
func (*StructField) IsScanner ¶
func (f *StructField) IsScanner() bool
func (*StructField) IsSlice ¶
func (f *StructField) IsSlice() bool
func (*StructField) IsStruct ¶
func (f *StructField) IsStruct() bool
func (*StructField) IsTime ¶
func (f *StructField) IsTime() bool
func (*StructField) JoinHandler ¶
func (f *StructField) JoinHandler() JoinTableHandlerInterface
func (*StructField) LinkPoly ¶
func (f *StructField) LinkPoly(withField *StructField, tableName string)
func (*StructField) ParseFieldStructForDialect ¶
ParseFieldStructForDialect parse field struct for dialect
func (*StructField) RelKind ¶
func (f *StructField) RelKind() uint8
func (*StructField) RelationIsBelongsTo ¶
func (f *StructField) RelationIsBelongsTo() bool
func (*StructField) RelationIsHasMany ¶
func (f *StructField) RelationIsHasMany() bool
func (*StructField) RelationIsHasOne ¶
func (f *StructField) RelationIsHasOne() bool
func (*StructField) RelationIsMany2Many ¶
func (f *StructField) RelationIsMany2Many() bool
func (*StructField) Set ¶
func (f *StructField) Set(value interface{}) error
func (*StructField) SetHasRelations ¶
func (f *StructField) SetHasRelations()
func (*StructField) SetIsAutoIncrement ¶
func (f *StructField) SetIsAutoIncrement()
Set set a value to the field
func (*StructField) SetIsBlank ¶
func (f *StructField) SetIsBlank()
func (*StructField) SetIsForeignKey ¶
func (f *StructField) SetIsForeignKey()
func (*StructField) SetIsNormal ¶
func (f *StructField) SetIsNormal()
func (*StructField) SetIsPrimaryKey ¶
func (f *StructField) SetIsPrimaryKey()
func (*StructField) SetTagSetting ¶
func (f *StructField) SetTagSetting(named uint8, value interface{})
func (*StructField) UnsetCheckRelations ¶
func (f *StructField) UnsetCheckRelations()
func (*StructField) UnsetIsAutoIncrement ¶
func (f *StructField) UnsetIsAutoIncrement()
func (*StructField) UnsetIsBlank ¶
func (f *StructField) UnsetIsBlank()
func (*StructField) UnsetIsPrimaryKey ¶
func (f *StructField) UnsetIsPrimaryKey()
func (*StructField) UnsetTagSetting ¶
func (f *StructField) UnsetTagSetting(named uint8)
func (*StructField) WillCheckRelations ¶
func (f *StructField) WillCheckRelations() bool
type TagSettings ¶
type TagSettings struct { Uint8Map // contains filtered or unexported fields }
since there is no other way of embedding a map
Source Files
¶
- association.go
- callback.go
- callback_processor.go
- callback_processors.go
- collector.go
- db.go
- default_foreign_key_namer.go
- dialect_common.go
- dialect_mysql.go
- dialect_postgres.go
- dialect_sqlite3.go
- errors.go
- init.go
- join_table_handler.go
- logger.go
- model_struct.go
- safe_fields_map.go
- safe_map.go
- safe_model_struct_map.go
- scope.go
- scoped_funcs.go
- search.go
- sql_conditions.go
- string_slice.go
- struct_field.go
- struct_fields.go
- tag_settings.go
- types.go
- utils.go
- utils_migrations.go
- utils_relations.go