Documentation
¶
Index ¶
- Constants
- Variables
- func AbbrToTextType(abbr string) string
- func AcceptTypeForModelStruct(typ interface{}) (ok bool)
- func AcceptableTypeForModelStructInterface(i interface{}) (typ reflect.Type)
- func AfterScanMethodCallback(_ *Method, method interface{}, field *Field, scope *Scope)
- func BindVar(dialect Dialector, assigner Assigner, value interface{}, replacement string) string
- func BindVarStructure(dialect Dialector, field *FieldStructure, replacement string) string
- func Each(it RecordsIterator, cb func(i int, r interface{}) error) (err error)
- func ErrorByType(expected reflect.Type, err ...error) (theError error)
- func ExcludeTypeForModelStruct(typ ...interface{})
- func IDValueRawConverterRegister(typ reflect.Type, converter IDValueRawConverter)
- func IdStringTo(id string, value interface{}) error
- func InID(id ...ID) *idSliceScoper
- func InIDNamedTable(tableName string, id ...ID) *idSliceNamedTable
- func InlinePreloadCallback(scope *Scope)
- func InlinePreloadFieldsKeyOf(value interface{}) string
- func IsBlank(value reflect.Value) bool
- func IsByteArrayOrSlice(value reflect.Value) bool
- func IsDuplicateUniqueIndexError(err ...error) bool
- func IsError(expected error, err ...error) (is bool)
- func IsErrorTyp(expected reflect.Type, err ...error) (is bool)
- func IsManyResult(dst interface{}) (many bool)
- func IsQueryError(err ...error) bool
- func IsRecordNotFoundError(err error) bool
- func Iterate(it RecordsIterator) (err error)
- func M2MNameOf(a reflect.Type, b reflect.Type) (prefix, name string)
- func M2MNameOfString(aName, bName string) (prefix, name string)
- func OpenIterate(opener RecordsIteratorOpener) (err error)
- func PathsFromQuery(query string) (paths []string)
- func Quote(q Quoter, key string) string
- func QuoteConvert(q Quoter, s string) string
- func QuoteConvertChar(q Quoter, fromChar string, s string) string
- func Register(assigner ...Assigner)
- func RegisterDialect(name string, dialect Dialector)
- func SenderOf(value reflect.Value) (send func(el reflect.Value))
- func SetIdCallback(scope *Scope)
- func SetNonZero(rvalue reflect.Value, value interface{})
- func SetZero(rvalue reflect.Value)
- func StructTypeOf(value reflect.Type) (typ reflect.Type, many, ptr bool)
- func StructTypeOfInterface(value interface{}) (typ reflect.Type, many, ptr bool)
- func ToDBName(name string) string
- func TupleQueryArgs(argCount int) (query string)
- func ValuerFunc(f func() (driver.Value, error)) driver.Valuer
- func WalkErr(cb func(err error) (stop bool), errs ...error) (stop bool)
- func ZeroIdOf(value interface{}) bool
- type AfterInlinePreloadScanner
- type Alias
- type AormNonFieldStructor
- type ArgBinder
- type AssignArgBinder
- type Assigner
- type AssignerRegistrator
- func (a *AssignerRegistrator) ApplyToDialect(dialect Dialector)
- func (a *AssignerRegistrator) Get(typ reflect.Type) (assigner Assigner)
- func (a *AssignerRegistrator) Has(typ reflect.Type) (ok bool)
- func (a *AssignerRegistrator) Of(value interface{}) (assigner Assigner)
- func (a *AssignerRegistrator) Register(assigners ...Assigner)
- type Association
- func (this *Association) Append(values ...interface{}) *Association
- func (this *Association) Clear() *Association
- func (this *Association) Count() int
- func (this *Association) Delete(values ...interface{}) *Association
- func (this *Association) Error() error
- func (this *Association) Find(value interface{}) *Association
- func (this *Association) HasError() bool
- func (this *Association) Replace(values ...interface{}) *Association
- type Audited
- type AuditedModel
- type AuditedSD
- type AuditedSDModel
- type Auditor
- type BIDAssigner
- func (a BIDAssigner) DbBindVar(dialect Dialector, argVar string) string
- func (BIDAssigner) FromRaw(raw interface{}) IDValuer
- func (BIDAssigner) SQLSize(_ Dialector) int
- func (BIDAssigner) SQLType(dialect Dialector) string
- func (BIDAssigner) Scaner(_ Dialector, dest reflect.Value) Scanner
- func (BIDAssigner) ToRaw(value IDValuer) interface{}
- func (BIDAssigner) Type() reflect.Type
- func (BIDAssigner) Valuer(dialect Dialector, value interface{}) driver.Valuer
- type BIDIdValuer
- type BytesId
- type BytesParser
- 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 Clause
- type ClauseScoper
- type Clauser
- type ColumnDismissibleTypeScaner
- type ColumnDismissibleTypeScanerHandler
- type Conditions
- func (this *Conditions) MergeTo(db *DB) *DB
- func (this *Conditions) Not(query interface{}, values ...interface{}) *Conditions
- func (this *Conditions) Or(query interface{}, values ...interface{}) *Conditions
- func (this *Conditions) Prepare(cb func(c *Conditions, query interface{}, args []interface{}, ...))
- func (this *Conditions) Where(query interface{}, values ...interface{}) *Conditions
- func (this *Conditions) WhereClause(scope *Scope) (result Query)
- type DB
- func (s *DB) AddError(err error) error
- func (s *DB) AddForeignKey(field string, dest string, onDelete string, onUpdate string) *DB
- func (s *DB) AddIndex(indexName string, columns ...string) *DB
- func (s *DB) AddUniqueIndex(indexName string, columns ...string) *DB
- func (s *DB) Assign(attrs ...interface{}) *DB
- func (s *DB) Association(relatedFieldName string) *Association
- func (s *DB) Attrs(attrs ...interface{}) *DB
- func (s *DB) AutoInlinePreload(value interface{}) *DB
- func (s *DB) AutoMigrate(values ...interface{}) *DB
- func (s *DB) Begin() *DB
- func (s *DB) BlockGlobalUpdate(enable bool) *DB
- func (s *DB) Callback() *Callback
- func (s *DB) Close() error
- func (s *DB) ColumnsScannerCallback(...) *DB
- func (s *DB) Commit() *DB
- func (s *DB) CommonDB() SQLCommon
- func (s *DB) Count(value interface{}) *DB
- func (s *DB) Create(value interface{}) *DB
- func (s *DB) CreateTable(models ...interface{}) *DB
- func (s *DB) DB() *sql.DB
- func (s *DB) Deadline() (deadline time.Time, ok bool)
- func (s *DB) Debug() *DB
- func (s *DB) DefaultColumnValue(valuer func(scope *Scope, record interface{}, column string) interface{}) *DB
- func (s *DB) Delete(value interface{}, where ...interface{}) *DB
- func (s *DB) Dialect() Dialector
- func (s *DB) DisableAfterScanCallback(typs ...interface{}) *DB
- func (s *DB) Done() <-chan struct{}
- func (s *DB) DropColumn(column string) *DB
- func (s *DB) DropTable(values ...interface{}) *DB
- func (s *DB) DropTableIfExists(values ...interface{}) *DB
- func (s *DB) DryRun() *DB
- func (s *DB) EnableAfterScanCallback(typs ...interface{}) *DB
- func (s *DB) Err() error
- func (s *DB) Exec(sql string, values ...interface{}) *DB
- func (s *DB) Exists(where ...interface{}) (ok bool, err error)
- func (s *DB) ExistsValue(value interface{}, where ...interface{}) (ok bool, err error)
- func (s *DB) ExtraSelect(key string, values []interface{}, query interface{}, args ...interface{}) *DB
- func (s *DB) ExtraSelectCallback(f ...func(recorde interface{}, data map[string]*ExtraResult)) *DB
- func (s *DB) ExtraSelectFields(key string, value interface{}, names []string, ...) *DB
- func (s *DB) ExtraSelectFieldsSetter(key string, setter ExtraSelectFieldsSetter, structFields []*StructField, ...) *DB
- func (s *DB) Find(out interface{}, where ...interface{}) *DB
- func (s *DB) First(out interface{}, where ...interface{}) *DB
- func (s *DB) FirstOrCreate(out interface{}, where ...interface{}) *DB
- func (s *DB) FirstOrInit(out interface{}, where ...interface{}) *DB
- func (s *DB) Get(name string) (value interface{}, ok bool)
- func (s *DB) GetArgVariabler(arg interface{}) (argVar ArgBinder)
- func (s *DB) GetAssigner(typ reflect.Type) (assigner Assigner)
- func (s *DB) GetCurrentUser() (user interface{}, ok bool)
- func (s *DB) GetCurrentUserID() (id interface{})
- func (s *DB) GetErrors() []error
- func (s *DB) Group(query string) *DB
- func (s *DB) HasBlockGlobalUpdate() bool
- func (s *DB) HasOrder() bool
- func (s *DB) HasTable(value interface{}) bool
- func (s *DB) Having(query interface{}, values ...interface{}) *DB
- func (s *DB) InlinePreload(column string, options ...*InlinePreloadOptions) *DB
- func (s *DB) InlinePreloadFields(value interface{}, fields ...string) *DB
- func (s *DB) Inside(name ...interface{}) *DB
- func (s *DB) InstantSet(name string, value interface{}) *DB
- func (s *DB) IsEnabledAfterScanCallback(typs ...interface{}) (ok bool)
- func (s *DB) Join(fieldName, mode string, handler func()) *DB
- func (s *DB) Joins(query string, args ...interface{}) *DB
- func (s *DB) Last(out interface{}, where ...interface{}) *DB
- func (s *DB) Limit(limit interface{}) *DB
- func (s *DB) LogMode(enable bool) *DB
- func (s *DB) Loggers(tableName string, set ...bool) (clone *DB, sl *ScopeLoggers, ok bool)
- func (s *DB) Model(value interface{}) *DB
- func (s *DB) ModelStructStorage() *ModelStructStorage
- func (s *DB) ModifyColumn(column string, typ string) *DB
- func (s *DB) New() *DB
- func (s *DB) NewScope(value interface{}) *Scope
- func (s *DB) Not(query interface{}, args ...interface{}) *DB
- func (s *DB) Offset(offset interface{}) *DB
- func (s *DB) Omit(columns ...string) *DB
- func (s *DB) Or(query interface{}, args ...interface{}) *DB
- func (s *DB) Order(value interface{}, reorder ...bool) *DB
- func (s *DB) Path() []interface{}
- func (s *DB) PathString() string
- func (s *DB) Pluck(column string, value interface{}) *DB
- func (s *DB) PluckFirst(column string, value interface{}) *DB
- func (s *DB) Preload(column string, options ...*InlinePreloadOptions) *DB
- func (s *DB) QueryExpr() *Query
- func (s *DB) Raw(sql string, values ...interface{}) *DB
- func (s *DB) RawTransaction(f func(tx *sql.Tx) (err error)) (err error)
- func (s *DB) RecordNotFound() bool
- func (s *DB) RegisterAssigner(assigners ...Assigner) *DB
- func (s *DB) Related(value interface{}, foreignKeys ...string) *DB
- func (s *DB) RemoveForeignKey(field string, dest string) *DB
- func (s *DB) RemoveIndex(indexName string) *DB
- func (s *DB) Rollback() *DB
- func (s *DB) Row() *sql.Row
- func (s *DB) Rows() (*sql.Rows, error)
- func (s *DB) Save(value interface{}) *DB
- func (s *DB) Scan(dest interface{}) *DB
- func (s *DB) ScanRows(rows *sql.Rows, result interface{}) error
- func (s *DB) ScopeErrorCallback(cb func(scope *Scope, err error)) *DB
- func (s *DB) Scopes(funcs ...func(*DB) *DB) *DB
- func (s *DB) Select(query interface{}, args ...interface{}) *DB
- func (s *DB) Set(name string, value interface{}) *DB
- func (s *DB) SetCommonDB(db SQLCommon) *DB
- func (s *DB) SetCurrentUser(user interface{}) *DB
- func (s *DB) SetJoinTableHandler(source interface{}, column string, handler JoinTableHandlerInterface)
- func (s *DB) SetLogger(log logging.Logger)
- func (s *DB) SetSingleUpdate(v bool) *DB
- func (db *DB) SetTableNameResolver(resolver TableNameResolver) *DB
- func (s *DB) SingleUpdate() bool
- func (s *DB) SingularTable(enable bool)
- func (s *DB) StoreBlankField() *DB
- func (s *DB) StructOf(value ...interface{}) *ModelStruct
- func (s *DB) SubQuery() *Query
- func (s *DB) Table(name string) *DB
- func (s *DB) Take(out interface{}, where ...interface{}) *DB
- func (s *DB) Transaction(f func(db *DB) (err error)) (err error)
- func (s *DB) Unscoped() *DB
- func (s *DB) Update(attrs ...interface{}) *DB
- func (s *DB) UpdateColumn(attrs ...interface{}) *DB
- func (s *DB) UpdateColumns(values interface{}) *DB
- func (s *DB) Updates(values interface{}, ignoreProtectedAttrs ...bool) *DB
- func (s *DB) Value(key interface{}) interface{}
- func (s *DB) Where(query interface{}, args ...interface{}) *DB
- type DBNamer
- type DbDataTyper
- type DefaultKeyNamer
- type DefinedID
- type Dialector
- type DuplicateUniqueIndexError
- type Errors
- type ExecState
- type ExtraResult
- type ExtraSelectFieldsSetter
- type ExtraSelectInterface
- type ExtraSelectModel
- type Field
- func (this *Field) CallMethodCallback(name string, object reflect.Value, in ...reflect.Value)
- func (this *Field) CallMethodCallbackArgs(name string, object reflect.Value, in []reflect.Value)
- func (this *Field) ID() (IDValuer, error)
- func (this *Field) Scaner(dialect Dialector) Scanner
- func (this *Field) Set(value interface{}) (err error)
- type FieldAssigner
- type FieldSelectWraper
- type FieldSelector
- type FieldSelectorFunc
- type FieldStructure
- type FieldTypeTagSettinger
- type FieldsForCreateAcceptor
- type FieldsForCreateExcluder
- type FieldsForUpdateAcceptor
- type FieldsForUpdateExcluder
- type Generator
- type ID
- type IDSlicer
- type IDValueRawConverter
- type IDValuer
- type Id
- func (this Id) Bytes() (b []byte)
- func (this Id) Exclude() ID
- func (this Id) Field() *StructField
- func (this Id) Fields() []*StructField
- func (this Id) IsZero() bool
- func (this Id) Raw() interface{}
- func (this Id) SetTo(recorde interface{}) interface{}
- func (this Id) SetValue(value ...interface{}) (_ ID, err error)
- func (this Id) String() string
- func (this Id) Value() IDValuer
- func (this Id) Values() []IDValuer
- func (this Id) WhereClause(scope *Scope) (result Query)
- type IndexMap
- type InlinePreloadBuilder
- type InlinePreloadFields
- type InlinePreloadFieldsWithScope
- type InlinePreloadInfo
- type InlinePreloadOptions
- type InlinePreloader
- type InlinePreloads
- type InlineQueries
- type Instance
- type IntId
- type IteratorHeader
- type JoinTableForeignKey
- type JoinTableHandler
- func (this JoinTableHandler) Add(handler JoinTableHandlerInterface, db *DB, source interface{}, ...) (err error)
- func (this JoinTableHandler) Delete(handler JoinTableHandlerInterface, db *DB, sources ...interface{}) error
- func (this *JoinTableHandler) Destination() JoinTableSource
- func (this *JoinTableHandler) DestinationForeignKeys() []JoinTableForeignKey
- func (this JoinTableHandler) JoinWith(handler JoinTableHandlerInterface, db *DB, source interface{}) *DB
- func (this *JoinTableHandler) Setup(relationship *Relationship, tableName string, source, destination *ModelStruct)
- func (this *JoinTableHandler) Source() JoinTableSource
- func (this *JoinTableHandler) SourceForeignKeys() []JoinTableForeignKey
- func (this JoinTableHandler) Table(db *DB) string
- func (this *JoinTableHandler) TableName() string
- type JoinTableHandlerInterface
- type JoinTableSource
- type JoinType
- type KVStorager
- type KeyNamer
- type KeyNamerFunc
- type Method
- type Model
- type ModelStruct
- func (this *ModelStruct) AutoInlinePreload(virtualFieldName ...string)
- func (this *ModelStruct) BeforeRelatedCallback(cb ...func(fromScope *Scope, toScope *Scope, db *DB, fromField *Field) *DB)
- func (this *ModelStruct) CreateFieldByName(value interface{}, fieldName string) (field *Field, ok bool)
- func (this *ModelStruct) DefaultID() ID
- func (this *ModelStruct) FieldByName(name string) (field *StructField, ok bool)
- func (this *ModelStruct) FieldByPath(pth string) (field *StructField)
- func (this *ModelStruct) FieldDiscovery(pth string) (field *StructField, virtualField *VirtualField)
- func (this *ModelStruct) FirstFieldValue(value interface{}, names ...string) (field *Field)
- func (this *ModelStruct) Fqn() string
- func (this *ModelStruct) GetID(record interface{}) ID
- func (this *ModelStruct) GetVirtualField(fieldName string) *VirtualField
- func (this *ModelStruct) HasID() bool
- func (this *ModelStruct) InstanceOf(value interface{}, fieldsNames ...string) (fields *Instance)
- func (this *ModelStruct) IsSoftDelete() bool
- func (this *ModelStruct) MustCreateFieldByName(value interface{}, fieldName string) (field *Field)
- func (this *ModelStruct) NonIgnoredStructFields() []*StructField
- func (this *ModelStruct) NonRelatedStructFields() []*StructField
- func (this *ModelStruct) NormalStructFields() (fields []*StructField)
- func (this *ModelStruct) ParseIDBytes(b []byte) (_ ID, err error)
- func (this *ModelStruct) ParseIDString(s string) (_ ID, err error)
- func (this *ModelStruct) PrimaryField() *StructField
- func (this *ModelStruct) PrimaryFieldsInstance(value interface{}) (fields []*Field)
- func (this *ModelStruct) RealTableName(ctx context.Context, singular bool) (name string)
- func (this *ModelStruct) SetIdFromString(record interface{}, idstr string) (err error)
- func (this *ModelStruct) SetVirtualField(fieldName string, value interface{}) *VirtualField
- func (this *ModelStruct) TableName(ctx context.Context, singular bool) string
- func (this *ModelStruct) UniqueIdexesNamesMap(namer KeyNamer, tableName string) map[string]*StructIndex
- type ModelStructStorage
- type ModelTS
- type ModelWithVirtualFields
- type OnRelated
- type OnRelatedField
- type Operation
- type PathError
- type Query
- type QueryError
- type QueryInfo
- type QuoteRuner
- type Quoter
- type RecordsIterator
- type RecordsIteratorOpener
- type Relationship
- func (this *Relationship) AssoctiationFields() []*StructField
- func (this *Relationship) DefaultRelatedID() (id ID)
- func (this *Relationship) ForeignFields() []*StructField
- func (this *Relationship) GetRelatedID(record interface{}) (id ID)
- func (this *Relationship) InstanceToRelatedID(instance *Instance) (id ID)
- func (this *Relationship) RelatedFields() []*StructField
- func (this *Relationship) SetRelatedID(record interface{}, id ID)
- type Reseter
- type RowQueryResult
- type RowsQueryResult
- type SQLCommon
- type SQLSizer
- type SafeNameBuilder
- type Scanner
- type Scope
- func (scope *Scope) AddToVars(value interface{}) (replacement string)
- func (s *Scope) AutoInlinePreload() *Scope
- func (scope *Scope) Begin() *Scope
- func (scope *Scope) CallMethod(methodName string)
- func (scope *Scope) Clause(clause interface{}) string
- func (scope *Scope) ClauseToSql(clause interface{}) (string, bool)
- func (scope *Scope) CombinedConditionSql() string
- func (scope *Scope) CommitOrRollback() *Scope
- func (scope *Scope) Context() context.Context
- func (scope *Scope) DB() *DB
- func (scope *Scope) Dialect() Dialector
- func (scope *Scope) Err(err error) error
- func (scope *Scope) Error() error
- func (s *Scope) ErrorCallbacks() (callbacks []func(scope *Scope, err error))
- func (scope *Scope) Exec() *Scope
- func (scope *Scope) ExecResult() sql.Result
- func (scope *Scope) FieldByName(name string) (field *Field, ok bool)
- func (scope *Scope) Get(name string) (interface{}, bool)
- func (scope *Scope) GetBool(name string, defaul ...bool) bool
- func (scope *Scope) GetCurrentUserID() (id interface{})
- func (scope *Scope) GetNonIgnoredStructFields() []*StructField
- func (scope *Scope) GetNonRelatedStructFields() []*StructField
- func (scope *Scope) GetStructFields() (fields []*StructField)
- func (s *Scope) GetVirtualField(fieldName string) *VirtualField
- func (scope *Scope) HasColumn(column string) bool
- func (scope *Scope) HasError() bool
- func (scope *Scope) HasPrimaryFields() (ok bool)
- func (scope *Scope) ID() ID
- func (scope *Scope) IndirectValue() reflect.Value
- func (s *Scope) InlinePreloadFields(value interface{}, fields ...string) *Scope
- func (scope *Scope) InlinePreloads() *InlinePreloads
- func (scope *Scope) Instance() *Instance
- func (scope *Scope) InstanceGet(name string) (interface{}, bool)
- func (scope *Scope) InstanceGetBool(name string, defaul ...bool) bool
- func (scope *Scope) InstanceID() string
- func (scope *Scope) InstanceSet(name string, value interface{}) *Scope
- func (scope *Scope) Log(v ...interface{})
- func (s *Scope) Loggers(set ...bool) (sl *ScopeLoggers, ok bool)
- func (scope *Scope) MustFieldByName(name string) (field *Field)
- func (s *Scope) MustLoggers(set ...bool) (sl *ScopeLoggers)
- func (scope *Scope) New(value interface{}) *Scope
- func (scope *Scope) NewDB() *DB
- func (scope *Scope) OmitAttrs() []string
- func (scope *Scope) PrimaryField() *Field
- func (scope *Scope) PrimaryFields() (fields []*Field)
- func (scope *Scope) PrimaryKey() interface{}
- func (scope *Scope) PrimaryKeyDbName() string
- 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) RealTableName() (name string)
- func (scope *Scope) ResultSender() (dest reflect.Value, send func(el reflect.Value))
- func (scope *Scope) SQLDB() SQLCommon
- func (scope *Scope) ScopeOfField(fieldName string) *Scope
- func (scope *Scope) SelectAttrs() []string
- func (scope *Scope) Set(name string, value interface{}) *Scope
- func (scope *Scope) SetColumn(column interface{}, value interface{}) error
- func (s *Scope) SetVirtualField(fieldName string, value interface{}, options ...map[interface{}]interface{}) (vf *VirtualField)
- func (scope *Scope) SkipLeft()
- func (scope *Scope) Struct() *ModelStruct
- func (scope *Scope) StructOf(value interface{}) *ModelStruct
- func (scope *Scope) TableName() string
- func (scope *Scope) ValuesFields(structFields []*StructField) []*Field
- type ScopeLoggers
- func (s *ScopeLoggers) All(callback func(action string, scope *Scope)) *ScopeLoggers
- func (s *ScopeLoggers) Call(action string, scope *Scope)
- func (s *ScopeLoggers) Create(callback func(action string, scope *Scope)) *ScopeLoggers
- func (s *ScopeLoggers) Crud(callback func(action string, scope *Scope)) *ScopeLoggers
- func (s *ScopeLoggers) Delete(callback func(action string, scope *Scope)) *ScopeLoggers
- func (s *ScopeLoggers) Exec(callback func(action string, scope *Scope)) *ScopeLoggers
- func (s *ScopeLoggers) Many(callback func(action string, scope *Scope), actions ...string) *ScopeLoggers
- func (s *ScopeLoggers) Query(callback func(action string, scope *Scope)) *ScopeLoggers
- func (s *ScopeLoggers) Register(action string, callback func(action string, scope *Scope)) *ScopeLoggers
- func (s *ScopeLoggers) Update(callback func(action string, scope *Scope)) *ScopeLoggers
- type Selector
- type SimpleAssigner
- type SoftDelete
- type SoftDeleteAudited
- type SoftDeleteAuditor
- type SoftDeleter
- type SqlClauser
- type StrId
- type StringParser
- type Strings
- type StructField
- func (this *StructField) CallMethodCallback(name string, object reflect.Value, in ...reflect.Value)
- func (this *StructField) CallMethodCallbackArgs(name string, object reflect.Value, in []reflect.Value)
- func (this StructField) DefaultID() (IDValuer, error)
- func (this StructField) IDOf(v interface{}) (IDValuer, error)
- func (this *StructField) Select(scope *Scope, tableName string) Query
- func (this *StructField) SelectWrap(scope *Scope, expr string) Query
- func (this *StructField) String() string
- func (this *StructField) Structure() *FieldStructure
- type StructFieldMethodCallback
- type StructFieldMethodCallbacksRegistrator
- func (registrator *StructFieldMethodCallbacksRegistrator) DisableFieldType(typs ...interface{})
- func (registrator *StructFieldMethodCallbacksRegistrator) EnableFieldType(typs ...interface{})
- func (registrator *StructFieldMethodCallbacksRegistrator) IsEnabledFieldType(typ interface{}) bool
- func (registrator *StructFieldMethodCallbacksRegistrator) RegisterFieldType(typs ...interface{})
- func (registrator *StructFieldMethodCallbacksRegistrator) RegisteredFieldType(typ interface{}) bool
- func (registrator *StructFieldMethodCallbacksRegistrator) UnregisterFieldType(typ interface{}) (ok bool)
- type StructFieldSetuper
- type StructIndex
- func (this *StructIndex) BuildName(d KeyNamer, tableName string) (name string)
- func (this *StructIndex) Columns() []string
- func (this *StructIndex) FieldsNames() []string
- func (this *StructIndex) SqlCreate(d Dialector, tableName string) (sql string)
- func (this *StructIndex) SqlDrop(d interface{ ... }, tableName string) (sql string)
- func (this *StructIndex) String() (s string)
- type TableNamePlurabler
- type TableNameResolver
- type TableNameResolverFunc
- type TableNamer
- type TagSetting
- type Timestamper
- type Timestamps
- type ToVarsAppender
- type UintId
- type ValueScanner
- type Vars
- type VirtualField
- type VirtualFieldValue
- type VirtualFields
- type VirtualFieldsGetter
- type VirtualFieldsSetter
- type WhereClauser
- type WithInlineQuery
- type Zeroer
Examples ¶
Constants ¶
const ( AuditedFieldCreatedByID = "CreatedByID" AuditedFieldUpdatedByID = "UpdatedByID" AuditedColumnCreatedByID = "created_by_id" AuditedColumnUpdatedByID = "updated_by_id" AuditedFieldCreatedAt = "CreatedAt" AuditedFieldUpdatedAt = "UpdatedAt" AuditedColumnCreatedAt = "created_at" AuditedColumnUpdatedAt = "updated_at" )
const ( OptSkipPreload = "aorm:skip_preload" OptAutoPreload = "aorm:auto_preload" )
const ( DefaultQuoter = QuoteRuner('`') QuoteCharS = string(DefaultQuoter) )
const ( LOG_CREATE = "create" LOG_READ = "read" LOG_UPDATE = "update" LOG_DELETE = "delete" LOG_QUERY = "query" LOG_EXEC = "exec" )
const ( SoftDeleteFieldDeletedByID = "DeletedByID" SoftDeleteFieldDeletedAt = "DeletedAt" SoftDeletedColumnDeletedByID = "deleted_by_id" SoftDeleteColumnDeletedAt = "deleted_at" )
const ( TimestampFieldCreatedAt = "CreatedAt" TimestampFieldUpdatedAt = "UpdatedAt" TimestampColumnCreatedAt = "created_at" TimestampColumnUpdatedAt = "updated_at" )
const (
CbGenId = ""
)
const (
StoreBlankField = "aorm:store_blank_field"
)
Variables ¶
var ( AuditedFieldsByID = []string{ AuditedFieldCreatedByID, AuditedFieldUpdatedByID, } AuditedFieldsAt = append([]string{ AuditedFieldCreatedAt, AuditedFieldUpdatedAt, }, TimestampFields...) AuditedColumnsByID = []string{ AuditedColumnCreatedByID, AuditedColumnUpdatedByID, } AuditedColumnsAt = append([]string{ AuditedColumnCreatedAt, AuditedColumnUpdatedAt, }, TimestampColumns...) AuditedFields = append(AuditedFieldsByID, AuditedFieldsAt...) AuditedColumns = append(AuditedColumnsByID, AuditedColumnsAt...) )
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") // ErrSingleUpdateKey single UPDATE require primary key value ErrSingleUpdateKey = errors.New("Single UPDATE require primary key value.") )
var ( SoftDeleteFields = []string{ SoftDeleteFieldDeletedByID, SoftDeleteFieldDeletedAt, } AuditedSDFields = append(append([]string{}, AuditedFields...), SoftDeleteFields...) )
var ( SqlConvertAssign = sql.GithubComMoisespsenaGoAormConvertAssign SqlConvertAssignRows = sql.GithubComMoisespsenaGoAormConvertAssignRows )
var ( TimestampFields = []string{ TimestampFieldCreatedAt, TimestampFieldUpdatedAt, } TimestampColumns = []string{ TimestampColumnCreatedAt, TimestampColumnUpdatedAt, } )
var DefaultCallback = &Callback{}
DefaultCallback default callbacks defined by gorm
var DefaultLogger = &ScopeLoggers{}
var DefaultTableNameHandler = func(ctx context.Context, singular bool, modelStruct *ModelStruct) (tableName string) {
if singular {
return modelStruct.SingularTableName
}
return modelStruct.PluralTableName
}
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 } return values }
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:
aorm.NowFunc = func() time.Time { return time.Now().UTC() }
var ParseFieldStructForDialect = func(field *FieldStructure, dialect Dialector) (fieldValue reflect.Value, sqlType string, size int, additionalType string) { // Get redirected field type var ( reflectType = field.Type dataType = field.TagSettings["TYPE"] ) for reflectType.Kind() == reflect.Ptr { reflectType = reflectType.Elem() } if dataType != "" { switch reflectType.Kind() { case reflect.String: dataType = AbbrToTextType(dataType) } } if dataType == "" && field.Assigner != nil { dataType = field.Assigner.SQLType(dialect) } fieldValue = reflect.Indirect(reflect.New(reflectType)) if dataTyper, ok := fieldValue.Interface().(DbDataTyper); ok { dataType = dataTyper.AormDataType(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 if sizer, ok := field.Assigner.(SQLSizer); ok { size = sizer.SQLSize(dialect) } else { size = 255 } additionalType = field.TagSettings["NOT NULL"] + " " + field.TagSettings["UNIQUE"] if value, ok := field.TagSettings["DEFAULT"]; ok { if value != "DEFAULT" { additionalType = additionalType + " DEFAULT " + value } } return fieldValue, dataType, size, strings.TrimSpace(additionalType) }
ParseFieldStructForDialect get field's sql data type
var StructFieldMethodCallbacks = NewStructFieldMethodCallbacksRegistrator()
StructFieldMethodCallbacks is a default registrator for model fields callbacks where the field type is a struct and have a callback method. Default methods callbacks: AfterScan: Call method `AfterScanMethodCallback` after scan field from sql row.
Functions ¶
func AbbrToTextType ¶
func AcceptTypeForModelStruct ¶
func AcceptTypeForModelStruct(typ interface{}) (ok bool)
func AfterScanMethodCallback ¶
Example ¶
package main import () func main() { println(` package main import ( "reflect" "github.com/moisespsena-go/aorm" "database/sql/driver" _ "github.com/moisespsena-go/aorm/dialects/sqlite" "strconv" "strings" ) type Media struct { Name string baseUrl *string modelType reflect.Type model interface { GetID() int } fieldName *string } func (image *Media) Scan(value interface{}) error { image.Name = string(value.([]byte)) return nil } func (image *Media) Value() (driver.Value, error) { return image.Name, nil } func (image *Media) AfterScan(scope *aorm.Scope, field *aorm.Field) { image.fieldName, image.model = &field.StructField.Name, scope.Val.(interface { GetID() int }) baseUrl, _ := scope.DB().Get("base_url") image.baseUrl = baseUrl.(*string) image.modelType = reflect.TypeOf(scope.Val) for image.modelType.Kind() == reflect.Ptr { image.modelType = image.modelType.Elem() } } func (image *Media) URL() string { return strings.Join([]string{*image.baseUrl, image.modelType.Name(), strconv.Itoa(image.model.GetID()), *image.fieldName, image.Name}, "/") } type User struct { BID int MainImage Media } func (user *User) GetID() int { return user.BID } func main() { // register media type aorm.StructFieldMethodCallbacks.RegisterFieldType(&Media{}) db, err := aorm.Open("sqlite3", "db.db") if err != nil { panic(err) } db.AutoMigrate(&User{}) baseUrl := "http://example.com/media" db = db.Set("base_url", &baseUrl) var model User db_ := db.Where("id = ?", 1).First(&model) if db_.RecordNotFound() { db.Save(&User{MainImage: Media{Name: "picture.jpg"}}) err = db.Where("id = ?", 1).First(&model).error if err != nil { panic(err) } } else if db_.error != nil { panic(db_.error) } println("Media URL:", model.MainImage.URL()) } `) }
Output:
func BindVarStructure ¶
func BindVarStructure(dialect Dialector, field *FieldStructure, replacement string) string
func ExcludeTypeForModelStruct ¶
func ExcludeTypeForModelStruct(typ ...interface{})
func IDValueRawConverterRegister ¶
func IDValueRawConverterRegister(typ reflect.Type, converter IDValueRawConverter)
func IdStringTo ¶
IdStringTo parses id from strign and set it to model value
func InIDNamedTable ¶
func InlinePreloadCallback ¶
func InlinePreloadCallback(scope *Scope)
func InlinePreloadFieldsKeyOf ¶
func InlinePreloadFieldsKeyOf(value interface{}) string
func IsByteArrayOrSlice ¶
IsByteArrayOrSlice returns true of the reflected value is an array or slice
func IsManyResult ¶
func IsManyResult(dst interface{}) (many bool)
func IsQueryError ¶
func IsRecordNotFoundError ¶
IsRecordNotFoundError returns current error has record not found error or not
func Iterate ¶
func Iterate(it RecordsIterator) (err error)
func M2MNameOfString ¶
func OpenIterate ¶
func OpenIterate(opener RecordsIteratorOpener) (err error)
func PathsFromQuery ¶
func Quote ¶
Quote quotes field name to avoid SQL parsing exceptions by using a reserved word as a field name
func QuoteConvert ¶
QuoteConvert converts all characters equals QuoteChar in string to quote char
func QuoteConvertChar ¶
QuoteConvertChar converts all characters equals fromChar in string to quote char
func RegisterDialect ¶
RegisterDialect register new dialect
func SetIdCallback ¶
func SetIdCallback(scope *Scope)
func SetNonZero ¶
func StructTypeOfInterface ¶
func TupleQueryArgs ¶
TupleQueryArgs create tuple args from argCount
Types ¶
type AfterInlinePreloadScanner ¶
type AfterInlinePreloadScanner interface {
AormAfterInlinePreloadScan(ip *InlinePreloader, recorde, value interface{})
}
type AormNonFieldStructor ¶
type AormNonFieldStructor interface {
AormNonFieldStructor()
}
type AssignArgBinder ¶
type AssignerRegistrator ¶
type AssignerRegistrator struct {
// contains filtered or unexported fields
}
func Assigners ¶
func Assigners() *AssignerRegistrator
func (*AssignerRegistrator) ApplyToDialect ¶
func (a *AssignerRegistrator) ApplyToDialect(dialect Dialector)
func (*AssignerRegistrator) Get ¶
func (a *AssignerRegistrator) Get(typ reflect.Type) (assigner Assigner)
func (*AssignerRegistrator) Of ¶
func (a *AssignerRegistrator) Of(value interface{}) (assigner Assigner)
func (*AssignerRegistrator) Register ¶
func (a *AssignerRegistrator) Register(assigners ...Assigner)
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 (this *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 (this *Association) Clear() *Association
Clear remove relationship between source & current associations, won'T delete those associations
func (*Association) Count ¶
func (this *Association) Count() int
Count return the count of current associations
func (*Association) Delete ¶
func (this *Association) Delete(values ...interface{}) *Association
Delete remove relationship between source & passed arguments, but won'T delete those arguments
func (*Association) Error ¶
func (this *Association) Error() error
func (*Association) Find ¶
func (this *Association) Find(value interface{}) *Association
Find find out all related associations
func (*Association) HasError ¶
func (this *Association) HasError() bool
func (*Association) Replace ¶
func (this *Association) Replace(values ...interface{}) *Association
Replace replace current associations with new one
type Audited ¶
type Audited struct { CreatedByID bid.BID UpdatedByID bid.BID Timestamps }
func (*Audited) GetCreatedBy ¶
func (*Audited) GetUpdatedBy ¶
func (*Audited) SetCreatedBy ¶
func (*Audited) SetUpdatedBy ¶
type AuditedModel ¶
type AuditedSD ¶
type AuditedSD struct { Audited SoftDeleteAudited }
type AuditedSDModel ¶
type Auditor ¶
type Auditor interface { Timestamper SetCreatedBy(createdBy IDValuer) GetCreatedBy() IDValuer SetUpdatedBy(updatedBy IDValuer) GetUpdatedBy() IDValuer }
type BIDAssigner ¶
type BIDAssigner struct { }
func (BIDAssigner) DbBindVar ¶
func (a BIDAssigner) DbBindVar(dialect Dialector, argVar string) string
func (BIDAssigner) FromRaw ¶
func (BIDAssigner) FromRaw(raw interface{}) IDValuer
func (BIDAssigner) SQLSize ¶
func (BIDAssigner) SQLSize(_ Dialector) int
func (BIDAssigner) SQLType ¶
func (BIDAssigner) SQLType(dialect Dialector) string
func (BIDAssigner) ToRaw ¶
func (BIDAssigner) ToRaw(value IDValuer) interface{}
func (BIDAssigner) Type ¶
func (BIDAssigner) Type() reflect.Type
type BIDIdValuer ¶
type BIDIdValuer BytesId
func (BIDIdValuer) Bytes ¶
func (this BIDIdValuer) Bytes() []byte
func (BIDIdValuer) IsZero ¶
func (this BIDIdValuer) IsZero() bool
func (BIDIdValuer) ParseBytes ¶
func (BIDIdValuer) ParseBytes(b []byte) (IDValuer, error)
func (BIDIdValuer) ParseString ¶
func (BIDIdValuer) ParseString(s string) (_ IDValuer, err error)
func (BIDIdValuer) Raw ¶
func (this BIDIdValuer) Raw() interface{}
func (BIDIdValuer) String ¶
func (this BIDIdValuer) String() string
type BytesParser ¶
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("aorm: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("aorm: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("aorm: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("aorm:update_time_stamp_when_create", func(*Scope) { scope.SetColumn("Created", now) scope.SetColumn("Updated", now) })
type ClauseScoper ¶
type ClauseScoper interface { TableNamer ToVarsAppender QuotedTableName() string Struct() *ModelStruct Instance() *Instance ScopeOfField(fieldName string) *Scope }
type ColumnDismissibleTypeScaner ¶
type ColumnDismissibleTypeScaner struct {
// contains filtered or unexported fields
}
type Conditions ¶
type Conditions struct { Args Vars // contains filtered or unexported fields }
func NewConditions ¶
func NewConditions() *Conditions
func (*Conditions) MergeTo ¶
func (this *Conditions) MergeTo(db *DB) *DB
func (*Conditions) Not ¶
func (this *Conditions) Not(query interface{}, values ...interface{}) *Conditions
func (*Conditions) Or ¶
func (this *Conditions) Or(query interface{}, values ...interface{}) *Conditions
func (*Conditions) Prepare ¶
func (this *Conditions) Prepare(cb func(c *Conditions, query interface{}, args []interface{}, replace func(query interface{}, args ...interface{})))
func (*Conditions) Where ¶
func (this *Conditions) Where(query interface{}, values ...interface{}) *Conditions
func (*Conditions) WhereClause ¶
func (this *Conditions) WhereClause(scope *Scope) (result Query)
type DB ¶
type DB struct { Val interface{} Error error RowsAffected int64 Context context.Context Query *Query // contains filtered or unexported fields }
DB contains information for current db connection
func CreateFakeDB ¶
CreateFakeDB create a new fake db with dialect
func Open ¶
Open initialize a new db connection, need to import driver first, e.g:
import _ "github.com/go-sql-driver/mysql" func main() { db, err := aorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local") }
AORM has wrapped some drivers, for easier to remember driver's import path, so you could import the mysql driver with
import _ "github.com/moisespsena-go/aorm/dialects/mysql" // import _ "github.com/moisespsena-go/aorm/dialects/postgres" // import _ "github.com/moisespsena-go/aorm/dialects/sqlite" // import _ "github.com/moisespsena-go/aorm/dialects/mssql"
func (*DB) AddForeignKey ¶
AddForeignKey Add foreign key to the given scope, e.g:
db.Model(&User{}).AddForeignKey("city_id", "cities(id)", "RESTRICT", "RESTRICT")
func (*DB) AddUniqueIndex ¶
AddUniqueIndex add unique index for columns with given name
func (*DB) Assign ¶
Assigner assign result with argument regardless it is found or not with `FirstOrInit` https://jinzhu.github.io/gorm/crud.html#firstorinit or `FirstOrCreate` https://jinzhu.github.io/gorm/crud.html#firstorcreate
func (*DB) Association ¶
func (s *DB) Association(relatedFieldName string) *Association
Association start `Association Mode` to handler relations things easir in that mode, refer: https://jinzhu.github.io/gorm/associations.html#association-mode
func (*DB) Attrs ¶
Attrs initialize struct with argument if record not found with `FirstOrInit` https://jinzhu.github.io/gorm/crud.html#firstorinit or `FirstOrCreate` https://jinzhu.github.io/gorm/crud.html#firstorcreate
func (*DB) AutoInlinePreload ¶
AutoInlinePreload preload associations
func (*DB) AutoMigrate ¶
AutoMigrate run auto migration for given models, will only add missing fields, won'T delete/change current data
func (*DB) BlockGlobalUpdate ¶
BlockGlobalUpdate if true, generates an error on update/delete without where clause. This is to prevent eventual error with empty objects updates/deletions
func (*DB) Callback ¶
Callback return `Callbacks` container, you could add/change/delete callbacks with it
db.Callback().Create().Register("update_created_at", updateCreated)
Refer https://jinzhu.github.io/gorm/development.html#callbacks
func (*DB) Close ¶
Close close current db connection. If database connection is not an io.Closer, returns an error.
func (*DB) ColumnsScannerCallback ¶
func (*DB) CommonDB ¶
CommonDB return the underlying `*sql.DB` or `*sql.Tx` instance, mainly intended to allow coexistence with legacy non-AORM code.
func (*DB) CreateTable ¶
CreateTable create table for models
func (*DB) DB ¶
DB get `*sql.DB` from current connection If the underlying database connection is not a *sql.DB, returns nil
func (*DB) DefaultColumnValue ¶
func (*DB) Delete ¶
Delete delete value match given conditions, if the value has primary key, then will including the primary key as condition
func (*DB) DisableAfterScanCallback ¶
Disable after scan callback. If typs not is empty, disable for typs, other else, disable for all
func (*DB) DropTableIfExists ¶
DropTableIfExists drop table if it is exist
func (*DB) EnableAfterScanCallback ¶
Enable after scan callback. If typs not is empty, enable for typs, other else, enable for all. The disabled types will not be enabled unless they are specifically informed.
func (*DB) Exists ¶
Exists used to query single column from a first model result as a map
var createAt time.Time db.Model(&User{}).Exists()
func (*DB) ExistsValue ¶
ExistsValue used to query single column from a first model result as a map
var createAt time.Time db.ExistsValue(&User{Name:"user name"})
func (*DB) ExtraSelect ¶
func (s *DB) ExtraSelect(key string, values []interface{}, query interface{}, args ...interface{}) *DB
ExtraSelect specify extra fields that you want to retrieve from database when querying
func (*DB) ExtraSelectCallback ¶
func (s *DB) ExtraSelectCallback(f ...func(recorde interface{}, data map[string]*ExtraResult)) *DB
ExtraSelectCalback specify extra select callbacks that you want to retrieve from database when querying
func (*DB) ExtraSelectFields ¶
func (s *DB) ExtraSelectFields(key string, value interface{}, names []string, callback func(scope *Scope, record interface{}), query interface{}, args ...interface{}) *DB
ExtraSelectFields specify extra fields that you want to retrieve from database when querying
func (*DB) ExtraSelectFieldsSetter ¶
func (s *DB) ExtraSelectFieldsSetter(key string, setter ExtraSelectFieldsSetter, structFields []*StructField, query interface{}, args ...interface{}) *DB
ExtraSelectFieldsSetter specify extra fields that you want to retrieve from database when querying
func (*DB) FirstOrCreate ¶
FirstOrCreate find first matched record or create a new one with given conditions (only works with struct, map conditions) https://jinzhu.github.io/gorm/crud.html#firstorcreate
func (*DB) FirstOrInit ¶
FirstOrInit find first matched record or initialize a new one with given conditions (only works with struct, map conditions) https://jinzhu.github.io/gorm/crud.html#firstorinit
func (*DB) GetArgVariabler ¶
func (*DB) GetCurrentUser ¶
func (*DB) GetCurrentUserID ¶
func (s *DB) GetCurrentUserID() (id interface{})
func (*DB) HasBlockGlobalUpdate ¶
HasBlockGlobalUpdate return state of block
func (*DB) InlinePreload ¶
func (s *DB) InlinePreload(column string, options ...*InlinePreloadOptions) *DB
Preload preload associations with given conditions
db.Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users)
func (*DB) InlinePreloadFields ¶
InlinePreloadFields set inline preload fields of value type
func (*DB) InstantSet ¶
InstantSet instant set setting, will affect current db
func (*DB) IsEnabledAfterScanCallback ¶
Return if after scan callbacks has be enable. If typs is empty, return default, other else, return for informed typs.
func (*DB) Join ¶
Join specify Join field conditions
db.Model(&User{}).Join("INNER", "Email") // INNER JOIN emails ON emails.user_id = user.id
func (*DB) Joins ¶
Joins specify Joins conditions
db.Joins("JOIN emails ON emails.user_id = users.id AND emails.email = ?", "jinzhu@example.org").Find(&user)
func (*DB) LogMode ¶
LogMode set log mode, `true` for detailed logs, `false` for no log, default, will only print error logs
func (*DB) Model ¶
Model specify the model you would like to run db operations
// update all users's name to `hello` db.Model(&User{}).Update("name", "hello") // if user's primary key is non-blank, will use it as condition, then will only update the user's name to `hello` db.Model(&user).Update("name", "hello")
func (*DB) ModelStructStorage ¶
func (s *DB) ModelStructStorage() *ModelStructStorage
ModelStructStorage get the model struct storage fom DB
func (*DB) ModifyColumn ¶
ModifyColumn modify column to type
func (*DB) Offset ¶
Offset specify the number of records to skip before starting to return the records
func (*DB) Omit ¶
Omit specify fields that you want to ignore when saving to database for creating, updating
func (*DB) Order ¶
Order specify order when retrieve records from database, set reorder to `true` to overwrite defined conditions
db.Order("name DESC") db.Order("name DESC", true) // reorder db.Order(aorm.Expr("name = ? DESC", "first")) // sql expression
func (*DB) PathString ¶
func (*DB) Pluck ¶
Pluck used to query single column from a model as a map
var ages []int64 db.Find(&users).Pluck("age", &ages)
func (*DB) PluckFirst ¶
PluckFirst used to query single column from a first model result as a map
var createAt time.Time db.Model(&User{}).Pluck("created_at", &createdAt)
func (*DB) Preload ¶
func (s *DB) Preload(column string, options ...*InlinePreloadOptions) *DB
Preload preload associations with given conditions
db.Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users)
func (*DB) Raw ¶
Raw use raw sql as conditions, won'T run it unless invoked by other methods
db.Raw("SELECT name, age FROM users WHERE name = ?", 3).Scan(&result)
func (*DB) RawTransaction ¶
RawTransaction execute func `f` into sql.Tx
func (*DB) RecordNotFound ¶
RecordNotFound check if returning ErrRecordNotFound error
func (*DB) RegisterAssigner ¶
func (*DB) RemoveForeignKey ¶
RemoveForeignKey Remove foreign key from the given scope, e.g:
db.Model(&User{}).RemoveForeignKey("city_id", "cities(id)")
func (*DB) RemoveIndex ¶
RemoveIndex remove index with name
func (*DB) Save ¶
Save update value in database, if the value doesn'T have primary key, will insert it
func (*DB) ScopeErrorCallback ¶
ScopeErrorCallback register error callback for scope
func (*DB) Scopes ¶
Scopes pass current database connection to arguments `func(*DB) *DB`, which could be used to add conditions dynamically
func AmountGreaterThan1000(db *aorm.DB) *aorm.DB { return db.Where("amount > ?", 1000) } func OrderStatus(status []string) func (db *aorm.DB) *aorm.DB { return func (db *aorm.DB) *aorm.DB { return db.Scopes(AmountGreaterThan1000).Where("status in (?)", status) } } db.Scopes(AmountGreaterThan1000, OrderStatus([]string{"paid", "shipped"})).Find(&orders)
func (*DB) Select ¶
Select specify fields that you want to retrieve from database when querying, by default, will select all fields; When creating/updating, specify fields that you want to save to database
func (*DB) Set ¶
Set set setting by name, which could be used in callbacks, will clone a new db, and update its setting
func (*DB) SetCommonDB ¶
SetCommonDB set the underlying `*sql.DB` or `*sql.Tx` instance, mainly intended to allow coexistence with legacy non-AORM code.
func (*DB) SetCurrentUser ¶
func (*DB) SetJoinTableHandler ¶
func (s *DB) SetJoinTableHandler(source interface{}, column string, handler JoinTableHandlerInterface)
SetJoinTableHandler set a model's join table handler for a relation
func (*DB) SetSingleUpdate ¶
func (*DB) SetTableNameResolver ¶
func (db *DB) SetTableNameResolver(resolver TableNameResolver) *DB
func (*DB) SingleUpdate ¶
func (*DB) SingularTable ¶
SingularTable use singular table by default
func (*DB) StoreBlankField ¶
StoreBlankField set aorm:store_blank_field as true
func (*DB) StructOf ¶
func (s *DB) StructOf(value ...interface{}) *ModelStruct
StructOf get value's model struct, relationships based on struct and tag definition fom DB
func (*DB) Take ¶
Take return a record that match given conditions, the order will depend on the database implementation
func (*DB) Transaction ¶
Transaction execute func `f` into transaction
func (*DB) Unscoped ¶
Unscoped return all record including deleted record, refer Soft Delete https://jinzhu.github.io/gorm/crud.html#soft-delete
func (*DB) Update ¶
Update update attributes with callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update
func (*DB) UpdateColumn ¶
UpdateColumn update attributes without callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update
func (*DB) UpdateColumns ¶
UpdateColumns update attributes without callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update
func (*DB) Updates ¶
Updates update attributes with callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update
func (*DB) Where ¶
Where return a new relation, filter records with given conditions, accepts `map`, `struct` or `string` as conditions, refer http://jinzhu.github.io/gorm/crud.html#query
type DbDataTyper ¶
type DefaultKeyNamer ¶
type DefaultKeyNamer struct{}
DefaultKeyNamer contains the default foreign key name generator method
func (DefaultKeyNamer) BuildKeyName ¶
func (DefaultKeyNamer) 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 Dialector ¶
type Dialector interface { Quoter KeyNamer // Init the dialect Init() // Cast sql cast's from to Cast(from, to string) string // 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 // DataTypeOf return data's sql type DataTypeOf(field *FieldStructure) 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 // CurrentDatabase return current database name CurrentDatabase() string Assigners() map[reflect.Type]Assigner RegisterAssigner(assigner ...Assigner) GetAssigner(typ reflect.Type) (assigner Assigner) DuplicateUniqueIndexError(indexes IndexMap, tableName string, sqlErr error) (err error) }
Dialector interface contains behaviors that differ across SQL database
func GetDialect ¶
GetDialect gets the dialect for the specified dialect name
func MustGetDialect ¶
MustGetDialect gets the dialect for the specified dialect name
type DuplicateUniqueIndexError ¶
type DuplicateUniqueIndexError struct {
// contains filtered or unexported fields
}
func GetDuplicateUniqueIndexError ¶
func GetDuplicateUniqueIndexError(err ...error) *DuplicateUniqueIndexError
func (DuplicateUniqueIndexError) Cause ¶
func (d DuplicateUniqueIndexError) Cause() error
func (DuplicateUniqueIndexError) Error ¶
func (d DuplicateUniqueIndexError) Error() string
func (DuplicateUniqueIndexError) Index ¶
func (d DuplicateUniqueIndexError) Index() *StructIndex
type ExtraResult ¶
type ExtraResult struct { Select *extraSelect Values []interface{} Names []string Map map[string]int }
func (*ExtraResult) Get ¶
func (er *ExtraResult) Get(name string) (v interface{}, ok bool)
type ExtraSelectFieldsSetter ¶
type ExtraSelectFieldsSetter func(result interface{}, values []interface{}, set func(result interface{}, low, hight int) interface{})
type ExtraSelectInterface ¶
type ExtraSelectInterface interface { SetAormExtraScannedValues(extra map[string]*ExtraResult) GetAormExtraScannedValue(name string) (result *ExtraResult, ok bool) GetAormExtraScannedValues() map[string]*ExtraResult }
type ExtraSelectModel ¶
type ExtraSelectModel struct {
ExtraScannedValues map[string]*ExtraResult `sql:"-"`
}
func (*ExtraSelectModel) GetAormExtraScannedValue ¶
func (es *ExtraSelectModel) GetAormExtraScannedValue(name string) (result *ExtraResult, ok bool)
func (*ExtraSelectModel) GetAormExtraScannedValues ¶
func (es *ExtraSelectModel) GetAormExtraScannedValues() map[string]*ExtraResult
func (*ExtraSelectModel) SetAormExtraScannedValues ¶
func (es *ExtraSelectModel) SetAormExtraScannedValues(extra map[string]*ExtraResult)
type Field ¶
type Field struct { *StructField IsBlank bool Field reflect.Value // contains filtered or unexported fields }
Field model field definition
func PrimaryFieldsOf ¶
func PrimaryFieldsOf(value interface{}) []*Field
PrimaryFieldsOf get the primary fields instance of value
func (*Field) CallMethodCallback ¶
Call the method callback
func (*Field) CallMethodCallbackArgs ¶
type FieldAssigner ¶
type FieldAssigner interface {
AormAssigner() Assigner
}
type FieldSelectWraper ¶
type FieldSelectWraper interface {
SelectWrap(field *StructField, scope *Scope, expr string) Query
}
type FieldSelector ¶
type FieldSelector interface {
Select(field *StructField, scope *Scope, table string) Query
}
func NewFieldSelector ¶
func NewFieldSelector(selectorFunc FieldSelectorFunc) FieldSelector
type FieldSelectorFunc ¶
type FieldSelectorFunc = func(field *StructField, scope *Scope, expr string) Query
type FieldStructure ¶
type FieldTypeTagSettinger ¶
type FieldTypeTagSettinger interface {
TagSetting(field reflect.StructField) TagSetting
}
type FieldsForCreateAcceptor ¶
type FieldsForCreateExcluder ¶
type FieldsForUpdateAcceptor ¶
type FieldsForUpdateExcluder ¶
type ID ¶
type ID interface { Zeroer WhereClauser fmt.Stringer Bytes() []byte Fields() []*StructField Field() *StructField Values() []IDValuer Value() IDValuer Raw() interface{} SetValue(value ...interface{}) (ID, error) SetTo(recorde interface{}) interface{} Exclude() ID }
type IDValueRawConverter ¶
type IDValueRawConverter interface { FromRaw(raw interface{}) IDValuer ToRaw(value IDValuer) interface{} }
func IDValueRawConverterGet ¶
func IDValueRawConverterGet(typ reflect.Type) (converter IDValueRawConverter)
type Id ¶
type Id struct { TableName string // contains filtered or unexported fields }
func NewId ¶
func NewId(fields []*StructField, values []IDValuer) *Id
func (Id) Field ¶
func (this Id) Field() *StructField
func (Id) Fields ¶
func (this Id) Fields() []*StructField
func (Id) WhereClause ¶
type IndexMap ¶
type IndexMap map[string]*StructIndex
func (IndexMap) FromColumns ¶
func (this IndexMap) FromColumns(columns ...string) (ix *StructIndex)
FromColumns return index from db column names
func (IndexMap) FromDbName ¶
func (this IndexMap) FromDbName(namer KeyNamer, tableName, indexDbName string) (ix *StructIndex)
FromDbName return index from db name
type InlinePreloadBuilder ¶
type InlinePreloadBuilder struct { *Conditions *InlinePreloadInfo }
type InlinePreloadFields ¶
type InlinePreloadFields interface {
GetAormInlinePreloadFields() []string
}
type InlinePreloadInfo ¶
type InlinePreloadInfo struct {
RootScope, ParentScope, Scope *Scope
Preloader *InlinePreloader
Conditions *Conditions
}
type InlinePreloadOptions ¶
type InlinePreloadOptions struct { Conditions RelatedConditions []interface{} Select []interface{} Join JoinType Prepare func(builder *InlinePreloadBuilder) }
type InlinePreloader ¶
type InlinePreloader struct { RootScope, Scope, ParentScope *Scope DB *DB ID string Field *StructField VirtualField *VirtualField Index [][]int RelationFields []*StructField StructFields []*StructField Query string }
func (*InlinePreloader) Apply ¶
func (p *InlinePreloader) Apply()
func (*InlinePreloader) Fields ¶
func (p *InlinePreloader) Fields(fields ...interface{})
func (*InlinePreloader) GetFields ¶
func (p *InlinePreloader) GetFields() []*StructField
func (*InlinePreloader) GetQuery ¶
func (p *InlinePreloader) GetQuery() string
func (*InlinePreloader) Scan ¶
func (p *InlinePreloader) Scan(result interface{}, values []interface{}, set func(result interface{}, low, hight int) interface{})
type InlinePreloads ¶
type InlinePreloads struct { Count uint // map of field path -> alias_name DBNames map[string]string }
func (*InlinePreloads) GetDBName ¶
func (c *InlinePreloads) GetDBName(path string) (dbName string, ok bool)
func (*InlinePreloads) Next ¶
func (c *InlinePreloads) Next(fieldPath ...string) string
type InlineQueries ¶
type InlineQueries []*WithInlineQuery
func (InlineQueries) Join ¶
func (iq InlineQueries) Join(sep ...string) (result *WithInlineQuery)
type Instance ¶
type Instance struct { Struct *ModelStruct ReflectValue reflect.Value Value interface{} FieldsMap map[string]*Field Fields []*Field Primary []*Field }
func InstanceOf ¶
InstanceOf get instance of model value
func (*Instance) FieldByName ¶
FieldByName find `aorm.Field` with field name or db name
func (*Instance) MustFieldByName ¶
MustFieldByName find `aorm.Field` with field name or db name
func (*Instance) PrimaryField ¶
PrimaryField return main primary field, if defined more that one primary fields, will return the one having column name `id` or the first one
func (*Instance) RelatedFields ¶
type IteratorHeader ¶
type IteratorHeader struct {
Value interface{}
}
type JoinTableForeignKey ¶
type JoinTableForeignKey struct { DBName string AssociationField *StructField }
JoinTableForeignKey join table foreign key struct
type JoinTableHandler ¶
type JoinTableHandler struct {
// contains filtered or unexported fields
}
JoinTableHandler default join table handler
func NewJoinTableHandler ¶
func NewJoinTableHandler(tableName string, source JoinTableSource, destination JoinTableSource) *JoinTableHandler
func (JoinTableHandler) Add ¶
func (this JoinTableHandler) Add(handler JoinTableHandlerInterface, db *DB, source interface{}, destination interface{}) (err error)
Add create relationship in join table for source and destination
func (JoinTableHandler) Delete ¶
func (this JoinTableHandler) Delete(handler JoinTableHandlerInterface, db *DB, sources ...interface{}) error
Delete delete relationship in join table for sources
func (*JoinTableHandler) Destination ¶
func (this *JoinTableHandler) Destination() JoinTableSource
func (*JoinTableHandler) DestinationForeignKeys ¶
func (this *JoinTableHandler) DestinationForeignKeys() []JoinTableForeignKey
DestinationForeignKeys return destination foreign keys
func (JoinTableHandler) JoinWith ¶
func (this JoinTableHandler) JoinWith(handler JoinTableHandlerInterface, db *DB, source interface{}) *DB
JoinWith query with `Join` conditions
func (*JoinTableHandler) Setup ¶
func (this *JoinTableHandler) Setup(relationship *Relationship, tableName string, source, destination *ModelStruct)
Setup initialize a default join table handler
func (*JoinTableHandler) Source ¶
func (this *JoinTableHandler) Source() JoinTableSource
func (*JoinTableHandler) SourceForeignKeys ¶
func (this *JoinTableHandler) SourceForeignKeys() []JoinTableForeignKey
SourceForeignKeys return source foreign keys
func (JoinTableHandler) Table ¶
func (this JoinTableHandler) Table(db *DB) string
Table return join table's table name
func (*JoinTableHandler) TableName ¶
func (this *JoinTableHandler) TableName() string
type JoinTableHandlerInterface ¶
type JoinTableHandlerInterface interface { TableNamer // initialize join table handler Setup(relationship *Relationship, tableName string, source, destination *ModelStruct) // Table return join table's table name Table(db *DB) string // Add create relationship in join table for source and destination Add(handler JoinTableHandlerInterface, db *DB, source interface{}, destination interface{}) error // Delete delete relationship in join table for sources Delete(handler JoinTableHandlerInterface, db *DB, sources ...interface{}) error // JoinWith query with `Join` conditions JoinWith(handler JoinTableHandlerInterface, db *DB, source interface{}) *DB // SourceForeignKeys return source foreign keys SourceForeignKeys() []JoinTableForeignKey // DestinationForeignKeys return destination foreign keys DestinationForeignKeys() []JoinTableForeignKey Source() JoinTableSource Destination() JoinTableSource }
JoinTableHandlerInterface is an interface for how to handle many2many relations
type JoinTableSource ¶
type JoinTableSource struct { ModelStruct *ModelStruct ForeignKeys []JoinTableForeignKey }
JoinTableSource is a struct that contains model type and foreign keys
type KVStorager ¶
type KeyNamer ¶
type KeyNamer interface { // BuildKeyName returns a valid key name (foreign key, index key) for the given table, field and reference BuildKeyName(kind, tableName string, fields ...string) string }
func KeyNameBuilderOf ¶
func KeyNameBuilderOf(f KeyNamerFunc) KeyNamer
type KeyNamerFunc ¶
type Model ¶
Model base model definition, including fields `BID`, `CreatedAt`, `UpdatedAt`, `DeletedAt`, which could be embedded in your models
type User struct { aorm.Model }
type ModelStruct ¶
type ModelStruct struct { TableNameResolver func(ctx context.Context, singular bool) (tableName string) Value interface{} PrimaryFields []*StructField Fields []*StructField RelatedFields []*StructField ReadOnlyFields []*StructField DynamicFieldsByName map[string]*StructField Type reflect.Type PluralTableName string SingularTableName string FieldsByName map[string]*StructField IgnoredFieldsCount int BeforeRelatedCallbacks []func(fromScope *Scope, toScope *Scope, db *DB, fromField *Field) *DB Indexes IndexMap UniqueIndexes IndexMap // contains filtered or unexported fields }
ModelStruct model definition
func StructOf ¶
func StructOf(value interface{}) *ModelStruct
StructOf get value's model struct, relationships based on struct and tag definition for value
func (*ModelStruct) AutoInlinePreload ¶
func (this *ModelStruct) AutoInlinePreload(virtualFieldName ...string)
AutoInlinePreload set default auto inline preload virtual field names
func (*ModelStruct) BeforeRelatedCallback ¶
func (*ModelStruct) CreateFieldByName ¶
func (this *ModelStruct) CreateFieldByName(value interface{}, fieldName string) (field *Field, ok bool)
func (*ModelStruct) DefaultID ¶
func (this *ModelStruct) DefaultID() ID
func (*ModelStruct) FieldByName ¶
func (this *ModelStruct) FieldByName(name string) (field *StructField, ok bool)
FieldByName find `aorm.StructField` with field name or db name
func (*ModelStruct) FieldByPath ¶
func (this *ModelStruct) FieldByPath(pth string) (field *StructField)
FieldByPath return field byte path
func (*ModelStruct) FieldDiscovery ¶
func (this *ModelStruct) FieldDiscovery(pth string) (field *StructField, virtualField *VirtualField)
FieldDiscovery discovery field from name or path
func (*ModelStruct) FirstFieldValue ¶
func (this *ModelStruct) FirstFieldValue(value interface{}, names ...string) (field *Field)
func (*ModelStruct) Fqn ¶
func (this *ModelStruct) Fqn() string
func (*ModelStruct) GetID ¶
func (this *ModelStruct) GetID(record interface{}) ID
func (*ModelStruct) GetVirtualField ¶
func (this *ModelStruct) GetVirtualField(fieldName string) *VirtualField
func (*ModelStruct) HasID ¶
func (this *ModelStruct) HasID() bool
HasID returns if has main primary field
func (*ModelStruct) InstanceOf ¶
func (this *ModelStruct) InstanceOf(value interface{}, fieldsNames ...string) (fields *Instance)
func (*ModelStruct) IsSoftDelete ¶
func (this *ModelStruct) IsSoftDelete() bool
func (*ModelStruct) MustCreateFieldByName ¶
func (this *ModelStruct) MustCreateFieldByName(value interface{}, fieldName string) (field *Field)
func (*ModelStruct) NonIgnoredStructFields ¶
func (this *ModelStruct) NonIgnoredStructFields() []*StructField
GetNonIgnoredStructFields get non ignored model's field structs
func (*ModelStruct) NonRelatedStructFields ¶
func (this *ModelStruct) NonRelatedStructFields() []*StructField
NonRelatedStructFields get non ignored model's field structs
func (*ModelStruct) NormalStructFields ¶
func (this *ModelStruct) NormalStructFields() (fields []*StructField)
GetNonIgnoredStructFields get non ignored model's field structs
func (*ModelStruct) ParseIDBytes ¶
func (this *ModelStruct) ParseIDBytes(b []byte) (_ ID, err error)
func (*ModelStruct) ParseIDString ¶
func (this *ModelStruct) ParseIDString(s string) (_ ID, err error)
func (*ModelStruct) PrimaryField ¶
func (this *ModelStruct) PrimaryField() *StructField
PrimaryField return main primary field, if defined more that one primary fields, will return the one having column name `id` or the first one
func (*ModelStruct) PrimaryFieldsInstance ¶
func (this *ModelStruct) PrimaryFieldsInstance(value interface{}) (fields []*Field)
func (*ModelStruct) RealTableName ¶
func (this *ModelStruct) RealTableName(ctx context.Context, singular bool) (name string)
RealTableName get real table name
func (*ModelStruct) SetIdFromString ¶
func (this *ModelStruct) SetIdFromString(record interface{}, idstr string) (err error)
func (*ModelStruct) SetVirtualField ¶
func (this *ModelStruct) SetVirtualField(fieldName string, value interface{}) *VirtualField
func (*ModelStruct) TableName ¶
func (this *ModelStruct) TableName(ctx context.Context, singular bool) string
tableName get model's table name
func (*ModelStruct) UniqueIdexesNamesMap ¶
func (this *ModelStruct) UniqueIdexesNamesMap(namer KeyNamer, tableName string) map[string]*StructIndex
UniqueIdexesNamesMap return unique idexes by index name map
type ModelStructStorage ¶
type ModelStructStorage struct { ModelStructsMap *safeModelStructsMap TableNameResolvers []TableNameResolver GetAssigner func(typ reflect.Type) Assigner }
func NewModelStructStorage ¶
func NewModelStructStorage() *ModelStructStorage
func (*ModelStructStorage) GetOrNew ¶
func (this *ModelStructStorage) GetOrNew(value interface{}, callback ...func(modelStruct *ModelStruct)) (modelStruct *ModelStruct, err error)
type ModelTS ¶
type ModelTS struct { Model Timestamps }
type ModelWithVirtualFields ¶
type ModelWithVirtualFields interface { VirtualFieldsGetter VirtualFieldsSetter }
type OnRelatedField ¶
type Query ¶
type QueryError ¶
type QueryError struct { QueryInfo // contains filtered or unexported fields }
Represents Query error
func GetQueryError ¶
func GetQueryError(err ...error) *QueryError
func NewQueryError ¶
func NewQueryError(cause error, q Query, varBinder func(i int) string) *QueryError
func (*QueryError) Error ¶
func (e *QueryError) Error() string
type QueryInfo ¶
type QueryInfo struct { Query // contains filtered or unexported fields }
Represents Query with args Info
type QuoteRuner ¶
type QuoteRuner rune
func (QuoteRuner) QuoteChar ¶
func (this QuoteRuner) QuoteChar() rune
type Quoter ¶
type Quoter interface { // DefaultQuoter quotes char for field name to avoid SQL parsing exceptions by using a reserved word as a field name QuoteChar() rune }
type RecordsIterator ¶
type RecordsIteratorOpener ¶
type RecordsIteratorOpener interface {
Open() (header interface{}, it RecordsIterator, err error)
}
type Relationship ¶
type Relationship struct {
Model, AssociationModel *ModelStruct
Kind string
FieldName string
PolymorphicType string
PolymorphicDBName string
PolymorphicValue func(ctx context.Context, singular bool) string
ForeignFieldNames []string
ForeignDBNames []string
AssociationForeignFieldNames []string
AssociationForeignDBNames []string
JoinTableHandler JoinTableHandlerInterface
}
Relationship described the relationship between models
func (*Relationship) AssoctiationFields ¶
func (this *Relationship) AssoctiationFields() []*StructField
func (*Relationship) DefaultRelatedID ¶
func (this *Relationship) DefaultRelatedID() (id ID)
func (*Relationship) ForeignFields ¶
func (this *Relationship) ForeignFields() []*StructField
func (*Relationship) GetRelatedID ¶
func (this *Relationship) GetRelatedID(record interface{}) (id ID)
func (*Relationship) InstanceToRelatedID ¶
func (this *Relationship) InstanceToRelatedID(instance *Instance) (id ID)
func (*Relationship) RelatedFields ¶
func (this *Relationship) RelatedFields() []*StructField
func (*Relationship) SetRelatedID ¶
func (this *Relationship) SetRelatedID(record interface{}, id ID)
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 SafeNameBuilder ¶
type SafeNameBuilder struct { Cache KVStorager PreFormat, Format func(v string) string }
func NewSafeNameBuilder ¶
func NewSafeNameBuilder(cache KVStorager, format ...func(v string) string) *SafeNameBuilder
func (*SafeNameBuilder) Build ¶
func (this *SafeNameBuilder) Build(name string) string
func (*SafeNameBuilder) BuildParts ¶
func (this *SafeNameBuilder) BuildParts(name string, sep string) string
type Scanner ¶
func ScannerFunc ¶
type Scope ¶
type Scope struct { Query Search *search Value interface{} ExecTime time.Time Operation Operation // contains filtered or unexported fields }
Scope contain current operation's information when you perform any operation on the database
func (*Scope) AutoInlinePreload ¶
AutoInlinePreload preload associations
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) ClauseToSql ¶
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) ErrorCallbacks ¶
func (*Scope) ExecResult ¶
ExecResult perform generated SQL and return result
func (*Scope) FieldByName ¶
CreateFieldByName find `aorm.Field` with field name or db name
func (*Scope) GetCurrentUserID ¶
func (scope *Scope) GetCurrentUserID() (id interface{})
func (*Scope) GetNonIgnoredStructFields ¶
func (scope *Scope) GetNonIgnoredStructFields() []*StructField
GetNonIgnoredStructFields get non ignored model's field structs
func (*Scope) GetNonRelatedStructFields ¶
func (scope *Scope) GetNonRelatedStructFields() []*StructField
GetNonIgnoredStructFields get non ignored model's field structs
func (*Scope) GetStructFields ¶
func (scope *Scope) GetStructFields() (fields []*StructField)
GetStructFields get model's field structs
func (*Scope) GetVirtualField ¶
func (s *Scope) GetVirtualField(fieldName string) *VirtualField
func (*Scope) HasPrimaryFields ¶
HasPrimaryFields return if scope's has primary fields
func (*Scope) IndirectValue ¶
IndirectValue return scope's reflect value's indirect value
func (*Scope) InlinePreloadFields ¶
InlinePreloadFields set inline preload fields of value type
func (*Scope) InlinePreloads ¶
func (scope *Scope) InlinePreloads() *InlinePreloads
func (*Scope) InstanceGet ¶
InstanceGet get instance setting from current operation
func (*Scope) InstanceGetBool ¶
InstanceGetBool get boolean 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) MustFieldByName ¶
MustFieldByName find `aorm.Field` with field name or db name
func (*Scope) MustLoggers ¶
func (s *Scope) MustLoggers(set ...bool) (sl *ScopeLoggers)
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 ¶
func (scope *Scope) PrimaryKey() interface{}
PrimaryKey get the primary key's value
func (*Scope) PrimaryKeyDbName ¶
PrimaryKeyDbName get main primary field's db name
func (*Scope) PrimaryKeyZero ¶
PrimaryKeyZero check main primary field's value is blank or not
func (*Scope) QuotedTableName ¶
QuotedTableName return quoted table name
func (*Scope) RealTableName ¶
tableName return table name
func (*Scope) ResultSender ¶
ResultSender return scope's value's result sender
func (*Scope) ScopeOfField ¶
func (*Scope) SelectAttrs ¶
SelectAttrs return selected attributes
func (*Scope) SetColumn ¶
SetColumn to set the column's value, column could be field or field's name/dbname
func (*Scope) SetVirtualField ¶
func (s *Scope) SetVirtualField(fieldName string, value interface{}, options ...map[interface{}]interface{}) (vf *VirtualField)
func (*Scope) Struct ¶
func (scope *Scope) Struct() *ModelStruct
Struct get value's model struct, relationships based on struct and tag definition
func (*Scope) StructOf ¶
func (scope *Scope) StructOf(value interface{}) *ModelStruct
StructOf get value's model struct, relationships based on struct and tag definition for value
func (*Scope) ValuesFields ¶
func (scope *Scope) ValuesFields(structFields []*StructField) []*Field
ValuesFields create value's fields from structFields
type ScopeLoggers ¶
type ScopeLoggers struct { Async bool // contains filtered or unexported fields }
func (*ScopeLoggers) All ¶
func (s *ScopeLoggers) All(callback func(action string, scope *Scope)) *ScopeLoggers
func (*ScopeLoggers) Call ¶
func (s *ScopeLoggers) Call(action string, scope *Scope)
func (*ScopeLoggers) Create ¶
func (s *ScopeLoggers) Create(callback func(action string, scope *Scope)) *ScopeLoggers
func (*ScopeLoggers) Crud ¶
func (s *ScopeLoggers) Crud(callback func(action string, scope *Scope)) *ScopeLoggers
func (*ScopeLoggers) Delete ¶
func (s *ScopeLoggers) Delete(callback func(action string, scope *Scope)) *ScopeLoggers
func (*ScopeLoggers) Exec ¶
func (s *ScopeLoggers) Exec(callback func(action string, scope *Scope)) *ScopeLoggers
func (*ScopeLoggers) Many ¶
func (s *ScopeLoggers) Many(callback func(action string, scope *Scope), actions ...string) *ScopeLoggers
func (*ScopeLoggers) Query ¶
func (s *ScopeLoggers) Query(callback func(action string, scope *Scope)) *ScopeLoggers
func (*ScopeLoggers) Register ¶
func (s *ScopeLoggers) Register(action string, callback func(action string, scope *Scope)) *ScopeLoggers
func (*ScopeLoggers) Update ¶
func (s *ScopeLoggers) Update(callback func(action string, scope *Scope)) *ScopeLoggers
type SimpleAssigner ¶
type SimpleAssigner struct { ValuerFunc func(dialect Dialector, value interface{}) driver.Valuer ScanerFunc func(dialect Dialector, dest reflect.Value) Scanner Typ reflect.Type SQLtype string SQLtypeFunc func(dialect Dialector) string }
func (*SimpleAssigner) SQLType ¶
func (assigner *SimpleAssigner) SQLType(dialect Dialector) string
func (*SimpleAssigner) Scaner ¶
func (assigner *SimpleAssigner) Scaner(dialect Dialector, dest reflect.Value) Scanner
func (*SimpleAssigner) Type ¶
func (assigner *SimpleAssigner) Type() reflect.Type
type SoftDelete ¶
func (*SoftDelete) GetDeletedAt ¶
func (d *SoftDelete) GetDeletedAt() *time.Time
type SoftDeleteAudited ¶
type SoftDeleteAudited struct { SoftDelete DeletedByID bid.BID }
func (*SoftDeleteAudited) GetDeletedBy ¶
func (a *SoftDeleteAudited) GetDeletedBy() interface{}
func (*SoftDeleteAudited) SetDeletedBy ¶
func (a *SoftDeleteAudited) SetDeletedBy(deletedBy interface{})
type SoftDeleteAuditor ¶
type SoftDeleteAuditor interface { SoftDeleter SetDeletedBy(deletedBy interface{}) GetDeletedBy() *string }
type SoftDeleter ¶
type SqlClauser ¶
type StringParser ¶
type StructField ¶
type StructField struct { DBName string Name string Names []string IsPrimaryKey bool IsNormal bool IsIgnored bool IsScanner bool IsReadOnly bool HasDefaultValue bool Tag reflect.StructTag TagSettings TagSetting Struct reflect.StructField BaseModel *ModelStruct IsForeignKey bool Relationship *Relationship MethodCallbacks map[string]StructFieldMethodCallback StructIndex []int Index int Assigner Assigner Data map[interface{}]interface{} Selector FieldSelector SelectWraper FieldSelectWraper }
StructField model field's struct definition
func (*StructField) CallMethodCallback ¶
Call the method callback if exists by name. the
func (*StructField) CallMethodCallbackArgs ¶
func (this *StructField) CallMethodCallbackArgs(name string, object reflect.Value, in []reflect.Value)
Call the method callback if exists by name.
func (StructField) DefaultID ¶
func (this StructField) DefaultID() (IDValuer, error)
func (StructField) IDOf ¶
func (this StructField) IDOf(v interface{}) (IDValuer, error)
func (*StructField) SelectWrap ¶
func (this *StructField) SelectWrap(scope *Scope, expr string) Query
func (*StructField) String ¶
func (this *StructField) String() string
func (*StructField) Structure ¶
func (this *StructField) Structure() *FieldStructure
type StructFieldMethodCallbacksRegistrator ¶
type StructFieldMethodCallbacksRegistrator struct { Callbacks map[string]reflect.Value FieldTypes safeEnabledFieldTypes // contains filtered or unexported fields }
func NewStructFieldMethodCallbacksRegistrator ¶
func NewStructFieldMethodCallbacksRegistrator() *StructFieldMethodCallbacksRegistrator
func (*StructFieldMethodCallbacksRegistrator) DisableFieldType ¶
func (registrator *StructFieldMethodCallbacksRegistrator) DisableFieldType(typs ...interface{})
Disable all callbacks for field type
Example ¶
package main import ( "fmt" ) func main() { fmt.Println(`if registrator.IsEnabledFieldType(&Media{}) { registrator.DisableFieldType(&Media{}) }`) }
Output:
func (*StructFieldMethodCallbacksRegistrator) EnableFieldType ¶
func (registrator *StructFieldMethodCallbacksRegistrator) EnableFieldType(typs ...interface{})
Enable all callbacks for field type
Example ¶
package main import ( "fmt" ) func main() { fmt.Println(`if !registrator.IsEnabledFieldType(&Media{}) { registrator.EnableFieldType(&Media{}) }`) }
Output:
func (*StructFieldMethodCallbacksRegistrator) IsEnabledFieldType ¶
func (registrator *StructFieldMethodCallbacksRegistrator) IsEnabledFieldType(typ interface{}) bool
Return if all callbacks for field type is enabled
func (*StructFieldMethodCallbacksRegistrator) RegisterFieldType ¶
func (registrator *StructFieldMethodCallbacksRegistrator) RegisterFieldType(typs ...interface{})
Register new field type and enable all available callbacks for here
Example ¶
package main import ( "fmt" ) func main() { fmt.Println("registrator.RegisterFieldType(&Media{})") }
Output:
func (*StructFieldMethodCallbacksRegistrator) RegisteredFieldType ¶
func (registrator *StructFieldMethodCallbacksRegistrator) RegisteredFieldType(typ interface{}) bool
Return if field type is registered
Example ¶
package main import ( "fmt" ) func main() { fmt.Println(` if registrator.RegisteredFieldType(&Media{}) { println("not registered") }`) }
Output:
func (*StructFieldMethodCallbacksRegistrator) UnregisterFieldType ¶
func (registrator *StructFieldMethodCallbacksRegistrator) UnregisterFieldType(typ interface{}) (ok bool)
Unregister field type and return if ok
type StructFieldSetuper ¶
type StructFieldSetuper interface {
AormStructFieldSetup(model *ModelStruct, field *StructField)
}
type StructIndex ¶
type StructIndex struct { Model *ModelStruct Unique bool NameTemplate string Fields []*StructField WhereTemplate string Where string }
func (*StructIndex) BuildName ¶
func (this *StructIndex) BuildName(d KeyNamer, tableName string) (name string)
func (*StructIndex) Columns ¶
func (this *StructIndex) Columns() []string
func (*StructIndex) FieldsNames ¶
func (this *StructIndex) FieldsNames() []string
func (*StructIndex) SqlCreate ¶
func (this *StructIndex) SqlCreate(d Dialector, tableName string) (sql string)
func (*StructIndex) SqlDrop ¶
func (this *StructIndex) SqlDrop(d interface { Quoter KeyNamer }, tableName string) (sql string)
func (*StructIndex) String ¶
func (this *StructIndex) String() (s string)
type TableNamePlurabler ¶
type TableNameResolver ¶
type TableNameResolver interface {
TableName(singular bool, value interface{}) (tableName string, ok bool)
}
func TableNameResolverOf ¶
func TableNameResolverOf(f func(singular bool, value interface{}) (tableName string, ok bool)) TableNameResolver
type TableNameResolverFunc ¶
type TableNamer ¶
type TableNamer interface {
TableName() string
}
type TagSetting ¶
func (TagSetting) Enable ¶
func (this TagSetting) Enable(key string)
func (TagSetting) Flag ¶
func (this TagSetting) Flag(name string) bool
func (TagSetting) Set ¶
func (this TagSetting) Set(key, value string)
func (TagSetting) Update ¶
func (this TagSetting) Update(setting ...map[string]string)
type Timestamps ¶
func (*Timestamps) GetCreatedAt ¶
func (t *Timestamps) GetCreatedAt() time.Time
func (*Timestamps) GetUpdatedAt ¶
func (t *Timestamps) GetUpdatedAt() time.Time
type ToVarsAppender ¶
type ToVarsAppender interface {
AddToVars(value interface{}) (replacement string)
}
type ValueScanner ¶
type ValueScanner struct { Field *Field Typ reflect.Type Data interface{} NotNil bool IsValid bool Ptr bool Set func(f *ValueScanner) MakePtr func() interface{} }
func NewFieldScanner ¶
func NewFieldScanner(field *Field) *ValueScanner
func NewValueScanner ¶
func NewValueScanner(typ reflect.Type) *ValueScanner
func (*ValueScanner) IsNil ¶
func (f *ValueScanner) IsNil() bool
func (*ValueScanner) IsPtr ¶
func (f *ValueScanner) IsPtr() bool
func (*ValueScanner) Scan ¶
func (f *ValueScanner) Scan(src interface{}) error
type VirtualField ¶
type VirtualField struct { ModelStruct *ModelStruct FieldName string StructIndex int Value interface{} Options map[interface{}]interface{} Setter func(vf *VirtualField, recorde, value interface{}) Getter func(vf *VirtualField, recorde interface{}) (value interface{}, ok bool) LocalFieldName string InlinePreloadOptions InlinePreloadOptions }
func (*VirtualField) Get ¶
func (vf *VirtualField) Get(recorde interface{}) (value interface{}, ok bool)
func (*VirtualField) Set ¶
func (vf *VirtualField) Set(recorde, value interface{})
type VirtualFieldValue ¶
type VirtualFieldValue struct {
Value interface{}
}
type VirtualFields ¶
type VirtualFields struct {
// contains filtered or unexported fields
}
func (*VirtualFields) GetVirtualField ¶
func (m *VirtualFields) GetVirtualField(fieldName string) (value interface{}, ok bool)
func (*VirtualFields) SetVirtualField ¶
func (m *VirtualFields) SetVirtualField(fieldName string, value interface{})
type VirtualFieldsGetter ¶
type VirtualFieldsSetter ¶
type VirtualFieldsSetter interface {
SetVirtualField(fieldName string, value interface{})
}
type WhereClauser ¶
type WithInlineQuery ¶
type WithInlineQuery struct {
// contains filtered or unexported fields
}
func IQ ¶
func IQ(query string, args ...interface{}) *WithInlineQuery
func (*WithInlineQuery) Paths ¶
func (iq *WithInlineQuery) Paths() []string
func (*WithInlineQuery) Query ¶
func (iq *WithInlineQuery) Query() string
func (*WithInlineQuery) String ¶
func (iq *WithInlineQuery) String() string
func (*WithInlineQuery) WhereClause ¶
func (iq *WithInlineQuery) WhereClause(scope *Scope) Query
Source Files
¶
- aorm.go
- api.go
- assign.go
- assign_api.go
- assigner_slice_string.go
- assigners.go
- association.go
- audited.go
- audited_api.go
- bid.go
- bid_assigner.go
- callback.go
- callback_create.go
- callback_delete.go
- callback_query.go
- callback_query_inline_preload.go
- callback_query_preload.go
- callback_row_query.go
- callback_save.go
- callback_update.go
- clause.go
- clause_api.go
- conditions.go
- dialect.go
- dialect_api.go
- dialect_common.go
- dialect_helper.go
- dialect_mysql.go
- dialect_postgres.go
- dialect_sqlite3.go
- errors.go
- extraselect.go
- extraselect_api.go
- extraselect_fields.go
- fake.go
- field.go
- field_api.go
- helper.go
- helper_api.go
- helper_m2mnamer.go
- id.go
- id_api.go
- id_fake.go
- id_helpers.go
- id_value_bytes.go
- id_value_int.go
- id_value_str.go
- id_value_uint.go
- inlinepreload.go
- inlinepreload_api.go
- inlinequery.go
- iterator.go
- join.go
- jointable.go
- jointable_api.go
- keynamebuilder.go
- logger.go
- main.go
- main_context.go
- main_migration.go
- main_modelstruct.go
- methodcallback.go
- model.go
- modelstruct.go
- modelstruct_api.go
- modelstruct_field.go
- modelstruct_field_api.go
- modelstruct_helpers.go
- modelstruct_idparse.go
- modelstruct_instance.go
- modelstruct_map.go
- modelstruct_setup.go
- modelstruct_setup_index.go
- modelstruct_storage.go
- modelstruct_storage_excludes.go
- noexec.go
- options.go
- query.go
- queryinfo.go
- quote.go
- related_api.go
- relationship.go
- scandismissible.go
- scandismissible_api.go
- scaner.go
- scope.go
- scope_clause.go
- scope_inline_preload.go
- scope_logger.go
- scope_migration.go
- scope_modelstruct.go
- scope_scaner.go
- scope_sqlbuild.go
- scope_utils.go
- scope_vars.go
- search.go
- softdelete.go
- softdelete_api.go
- sqlconvert.go
- struct_index.go
- struct_index_builder.go
- sync.go
- tablename.go
- tablename_api.go
- tagsetting.go
- timestamps.go
- timestamps_api.go
- typevar.go
- utils.go
- vars.go
- virtualfield.go
- virtualfield_api.go