import "github.com/jinzhu/gorm"
association.go callback.go callback_create.go callback_delete.go callback_query.go callback_query_preload.go callback_row_query.go callback_save.go callback_update.go dialect.go dialect_common.go dialect_mysql.go dialect_postgres.go dialect_sqlite3.go errors.go field.go interface.go join_table_handler.go logger.go main.go model.go model_struct.go naming.go scope.go search.go utils.go
var ( // ErrRecordNotFound returns a "record not found error". Occurs only when attempting to query the database with a struct; querying with a slice won't return this error ErrRecordNotFound = errors.New("record not found") // ErrInvalidSQL occurs when you attempt a query with invalid SQL ErrInvalidSQL = errors.New("invalid SQL") // ErrInvalidTransaction occurs 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") )
DefaultCallback default callbacks defined by gorm
var DefaultTableNameHandler = func(db *DB, defaultTableName string) string { return defaultTableName }
DefaultTableNameHandler default table name handler
var LogFormatter = func(values ...interface{}) (messages []interface{}) { if len(values) > 1 { var ( sql string formattedValues []string level = values[0] currentTime = "\n\033[33m[" + NowFunc().Format("2006-01-02 15:04:05") + "]\033[0m" source = fmt.Sprintf("\033[35m(%v)\033[0m", values[1]) ) messages = []interface{}{source, currentTime} if len(values) == 2 { currentTime = currentTime[1:] source = fmt.Sprintf("\033[35m%v\033[0m", values[1]) messages = []interface{}{currentTime, source} } 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 { if t.IsZero() { formattedValues = append(formattedValues, fmt.Sprintf("'%v'", "0000-00-00 00:00:00")) } else { 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 { switch value.(type) { case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, bool: formattedValues = append(formattedValues, fmt.Sprintf("%v", value)) default: 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 }
NowFunc returns current time, this function is exported in order to be able to give the flexibility to the developer to customize it according to their needs, e.g:
gorm.NowFunc = func() time.Time { return time.Now().UTC() }
var ParseFieldStructForDialect = func(field *StructField, dialect Dialect) (fieldValue reflect.Value, sqlType string, size int, additionalType string) { // Get redirected field type var ( reflectType = field.Struct.Type dataType, _ = field.TagSettingsGet("TYPE") ) for reflectType.Kind() == reflect.Ptr { reflectType = reflectType.Elem() } fieldValue = reflect.Indirect(reflect.New(reflectType)) if gormDataType, ok := fieldValue.Interface().(interface { GormDataType(Dialect) string }); ok { dataType = gormDataType.GormDataType(dialect) } if dataType == "" { var getScannerValue func(reflect.Value) getScannerValue = func(value reflect.Value) { fieldValue = value if _, isScanner := reflect.New(fieldValue.Type()).Interface().(sql.Scanner); isScanner && fieldValue.Kind() == reflect.Struct { getScannerValue(fieldValue.Field(0)) } } getScannerValue(fieldValue) } if num, ok := field.TagSettingsGet("SIZE"); ok { size, _ = strconv.Atoi(num) } else { size = 255 } notNull, _ := field.TagSettingsGet("NOT NULL") unique, _ := field.TagSettingsGet("UNIQUE") additionalType = notNull + " " + unique if value, ok := field.TagSettingsGet("DEFAULT"); ok { additionalType = additionalType + " DEFAULT " + value } if value, ok := field.TagSettingsGet("COMMENT"); ok { additionalType = additionalType + " COMMENT " + value } return fieldValue, dataType, size, strings.TrimSpace(additionalType) }
ParseFieldStructForDialect get field's sql data type
var TheNamingStrategy = &NamingStrategy{ DB: defaultNamer, Table: defaultNamer, Column: defaultNamer, }
TheNamingStrategy is being initialized with defaultNamingStrategy
func AddNamingStrategy(ns *NamingStrategy)
AddNamingStrategy sets the naming strategy
IsByteArrayOrSlice returns true of the reflected value is an array or slice
IsRecordNotFoundError returns true if error contains a RecordNotFound error
RegisterDialect register new dialect
ToColumnName convert string to db name
ToDBName convert string to db name
ToTableName convert string to table name
Association Mode contains some helper methods to handle relationship things easily.
func (association *Association) Append(values ...interface{}) *Association
Append append new associations for many2many, has_many, replace current association for has_one, belongs_to
func (association *Association) Clear() *Association
Clear remove relationship between source & current associations, won't delete those associations
func (association *Association) Count() int
Count return the count of current associations
func (association *Association) Delete(values ...interface{}) *Association
Delete remove relationship between source & passed arguments, but won't delete those arguments
func (association *Association) Find(value interface{}) *Association
Find find out all related associations
func (association *Association) Replace(values ...interface{}) *Association
Replace replace current associations with new one
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 (c *Callback) Create() *CallbackProcessor
Create could be used to register callbacks for creating object
db.Callback().Create().After("gorm:create").Register("plugin:run_after_create", func(*Scope) { // business logic ... // set error if some thing wrong happened, will rollback the creating scope.Err(errors.New("error")) })
func (c *Callback) Delete() *CallbackProcessor
Delete could be used to register callbacks for deleting object, refer `Create` for usage
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 (c *Callback) RowQuery() *CallbackProcessor
RowQuery could be used to register callbacks for querying objects with `Row`, `Rows`, refer `Create` for usage
func (c *Callback) Update() *CallbackProcessor
Update could be used to register callbacks for updating object, refer `Create` for usage
type CallbackProcessor struct {
// contains filtered or unexported fields
}
CallbackProcessor contains callback informations
func (cp *CallbackProcessor) After(callbackName string) *CallbackProcessor
After insert a new callback after callback `callbackName`, refer `Callbacks.Create`
func (cp *CallbackProcessor) Before(callbackName string) *CallbackProcessor
Before insert a new callback before callback `callbackName`, refer `Callbacks.Create`
func (cp *CallbackProcessor) Get(callbackName string) (callback func(scope *Scope))
Get registered callback
db.Callback().Create().Get("gorm:create")
func (cp *CallbackProcessor) Register(callbackName string, callback func(scope *Scope))
Register a new callback, refer `Callbacks.Create`
func (cp *CallbackProcessor) Remove(callbackName string)
Remove a registered callback
db.Callback().Create().Remove("gorm:update_time_stamp_when_create")
func (cp *CallbackProcessor) Replace(callbackName string, callback func(scope *Scope))
Replace a registered callback with new callback
db.Callback().Create().Replace("gorm:update_time_stamp_when_create", func(*Scope) { scope.SetColumn("CreatedAt", now) scope.SetColumn("UpdatedAt", now) })
type DB struct { sync.RWMutex Value interface{} Error error RowsAffected int64 // contains filtered or unexported fields }
DB contains information for current db connection
Open initialize a new db connection, need to import driver first, e.g:
import _ "github.com/go-sql-driver/mysql" func main() { db, err := gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local") }
GORM has wrapped some drivers, for easier to remember driver's import path, so you could import the mysql driver with
import _ "github.com/jinzhu/gorm/dialects/mysql" // import _ "github.com/jinzhu/gorm/dialects/postgres" // import _ "github.com/jinzhu/gorm/dialects/sqlite" // import _ "github.com/jinzhu/gorm/dialects/mssql"
AddError add error to the db
AddForeignKey Add foreign key to the given scope, e.g:
db.Model(&User{}).AddForeignKey("city_id", "cities(id)", "RESTRICT", "RESTRICT")
AddIndex add index for columns with given name
AddUniqueIndex add unique index for columns with given name
Assign assign result with argument regardless it is found or not with `FirstOrInit` https://jinzhu.github.io/gorm/crud.html#firstorinit or `FirstOrCreate` https://jinzhu.github.io/gorm/crud.html#firstorcreate
func (s *DB) Association(column string) *Association
Association start `Association Mode` to handler relations things easir in that mode, refer: https://jinzhu.github.io/gorm/associations.html#association-mode
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
AutoMigrate run auto migration for given models, will only add missing fields, won't delete/change current data
Begin begins a transaction
BeginTx begins a transaction with options
BlockGlobalUpdate if true, generates an error on update/delete without where clause. This is to prevent eventual error with empty objects updates/deletions
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
Close close current db connection. If database connection is not an io.Closer, returns an error.
Commit commit a transaction
CommonDB return the underlying `*sql.DB` or `*sql.Tx` instance, mainly intended to allow coexistence with legacy non-GORM code.
Count get how many records for a model
Create insert the value into database
CreateTable create table for models
DB get `*sql.DB` from current connection If the underlying database connection is not a *sql.DB, returns nil
Debug start debug mode
Delete delete value match given conditions, if the value has primary key, then will including the primary key as condition WARNING If model has DeletedAt field, GORM will only set field DeletedAt's value to current time
Dialect get dialect
DropColumn drop a column
DropTable drop table for models
DropTableIfExists drop table if it is exist
Exec execute raw sql
Find find records that match given conditions
First find first record that match given conditions, order by primary key
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
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
Get get setting by name
GetErrors get happened errors from the db
Group specify the group method on the find
HasBlockGlobalUpdate return state of block
HasTable check has table or not
Having specify HAVING conditions for GROUP BY
InstantSet instant set setting, will affect current db
Joins specify Joins conditions
db.Joins("JOIN emails ON emails.user_id = users.id AND emails.email = ?", "jinzhu@example.org").Find(&user)
Last find last record that match given conditions, order by primary key
Limit specify the number of records to be retrieved
LogMode set log mode, `true` for detailed logs, `false` for no log, default, will only print error logs
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")
ModifyColumn modify column to type
New clone a new db connection without search conditions
NewRecord check if value's primary key is blank
NewScope create a scope for current operation
Not filter records that don't match current conditions, similar to `Where`
Offset specify the number of records to skip before starting to return the records
Omit specify fields that you want to ignore when saving to database for creating, updating
Or filter records that match before conditions or this one, similar to `Where`
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
Pluck used to query single column from a model as a map
var ages []int64 db.Find(&users).Pluck("age", &ages)
Preload preload associations with given conditions
db.Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users)
Preloads preloads relations, don`t touch out
QueryExpr returns the query as SqlExpr object
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)
RecordNotFound check if returning ErrRecordNotFound error
Related get related associations
RemoveForeignKey Remove foreign key from the given scope, e.g:
db.Model(&User{}).RemoveForeignKey("city_id", "cities(id)")
RemoveIndex remove index with name
Rollback rollback a transaction
RollbackUnlessCommitted rollback a transaction if it has not yet been committed.
Row return `*sql.Row` with given conditions
Rows return `*sql.Rows` with given conditions
Save update value in database, if the value doesn't have primary key, will insert it
Scan scan value to a struct
ScanRows scan `*sql.Rows` to give struct
Scopes pass current database connection to arguments `func(*DB) *DB`, which could be used to add conditions dynamically
func AmountGreaterThan1000(db *gorm.DB) *gorm.DB { return db.Where("amount > ?", 1000) } func OrderStatus(status []string) func (db *gorm.DB) *gorm.DB { return func (db *gorm.DB) *gorm.DB { return db.Scopes(AmountGreaterThan1000).Where("status in (?)", status) } } db.Scopes(AmountGreaterThan1000, OrderStatus([]string{"paid", "shipped"})).Find(&orders)
Refer https://jinzhu.github.io/gorm/crud.html#scopes
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
Set set setting by name, which could be used in callbacks, will clone a new db, and update its setting
func (s *DB) SetJoinTableHandler(source interface{}, column string, handler JoinTableHandlerInterface)
SetJoinTableHandler set a model's join table handler for a relation
SetLogger replace default logger
SetNowFuncOverride set the function to be used when creating a new timestamp
SingularTable use singular table by default
SubQuery returns the query as sub query
Table specify the table you would like to run db operations
Take return a record that match given conditions, the order will depend on the database implementation
Transaction start a transaction as a block, return error will rollback, otherwise to commit.
Unscoped return all record including deleted record, refer Soft Delete https://jinzhu.github.io/gorm/crud.html#soft-delete
Update update attributes with callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update WARNING when update with struct, GORM will not update fields that with zero value
UpdateColumn update attributes without callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update
UpdateColumns update attributes without callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update
Updates update attributes with callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update
Where return a new relation, filter records with given conditions, accepts `map`, `struct` or `string` as conditions, refer http://jinzhu.github.io/gorm/crud.html#query
type DefaultForeignKeyNamer struct { }
DefaultForeignKeyNamer contains the default foreign key name generator method
func (DefaultForeignKeyNamer) BuildKeyName(kind, tableName string, fields ...string) string
BuildKeyName returns a valid key name (foreign key, index key) for the given table, field and reference
type Dialect interface { // GetName get dialect's name GetName() string // SetDB set db for dialect SetDB(db SQLCommon) // BindVar return the placeholder for actual values in SQL statements, in many dbs it is "?", Postgres using $1 BindVar(i int) string // Quote quotes field name to avoid SQL parsing exceptions by using a reserved word as a field name Quote(key string) string // DataTypeOf return data's sql type DataTypeOf(field *StructField) string // HasIndex check has index or not HasIndex(tableName string, indexName string) bool // HasForeignKey check has foreign key or not HasForeignKey(tableName string, foreignKeyName string) bool // RemoveIndex remove index RemoveIndex(tableName string, indexName string) error // HasTable check has table or not HasTable(tableName string) bool // HasColumn check has column or not HasColumn(tableName string, columnName string) bool // ModifyColumn modify column's type ModifyColumn(tableName string, columnName string, typ string) error // LimitAndOffsetSQL return generated SQL with Limit and Offset, as mssql has special case LimitAndOffsetSQL(limit, offset interface{}) (string, error) // SelectFromDummyTable return select values, for most dbs, `SELECT values` just works, mysql needs `SELECT value FROM DUAL` SelectFromDummyTable() string // LastInsertIDOutputInterstitial most dbs support LastInsertId, but mssql needs to use `OUTPUT` LastInsertIDOutputInterstitial(tableName, columnName string, columns []string) string // LastInsertIdReturningSuffix most dbs support LastInsertId, but postgres needs to use `RETURNING` LastInsertIDReturningSuffix(tableName, columnName string) string // DefaultValueStr DefaultValueStr() string // BuildKeyName returns a valid key name (foreign key, index key) for the given table, field and reference BuildKeyName(kind, tableName string, fields ...string) string // NormalizeIndexAndColumn returns valid index name and column name depending on each dialect NormalizeIndexAndColumn(indexName, columnName string) (string, string) // CurrentDatabase return current database name CurrentDatabase() string }
Dialect interface contains behaviors that differ across SQL database
GetDialect gets the dialect for the specified dialect name
Errors contains all happened errors
Add adds an error to a given slice of errors
Error takes a slice of all errors that have occurred and returns it as a formatted string
GetErrors gets all errors that have occurred and returns a slice of errors (Error type)
type Field struct { *StructField IsBlank bool Field reflect.Value }
Field model field definition
Set set a value to the field
JoinTableForeignKey join table foreign key struct
type JoinTableHandler struct { TableName string `sql:"-"` Source JoinTableSource `sql:"-"` Destination JoinTableSource `sql:"-"` }
JoinTableHandler default join table handler
func (s JoinTableHandler) Add(handler JoinTableHandlerInterface, db *DB, source interface{}, destination interface{}) error
Add create relationship in join table for source and destination
func (s JoinTableHandler) Delete(handler JoinTableHandlerInterface, db *DB, sources ...interface{}) error
Delete delete relationship in join table for sources
func (s *JoinTableHandler) DestinationForeignKeys() []JoinTableForeignKey
DestinationForeignKeys return destination foreign keys
func (s JoinTableHandler) JoinWith(handler JoinTableHandlerInterface, db *DB, source interface{}) *DB
JoinWith query with `Join` conditions
func (s *JoinTableHandler) Setup(relationship *Relationship, tableName string, source reflect.Type, destination reflect.Type)
Setup initialize a default join table handler
func (s *JoinTableHandler) SourceForeignKeys() []JoinTableForeignKey
SourceForeignKeys return source foreign keys
func (s JoinTableHandler) Table(db *DB) string
Table return join table's table name
type JoinTableHandlerInterface interface { // initialize join table handler Setup(relationship *Relationship, tableName string, source reflect.Type, destination reflect.Type) // Table return join table's table name Table(db *DB) string // Add create relationship in join table for source and destination Add(handler JoinTableHandlerInterface, db *DB, source interface{}, destination interface{}) error // Delete delete relationship in join table for sources Delete(handler JoinTableHandlerInterface, db *DB, sources ...interface{}) error // JoinWith query with `Join` conditions JoinWith(handler JoinTableHandlerInterface, db *DB, source interface{}) *DB // SourceForeignKeys return source foreign keys SourceForeignKeys() []JoinTableForeignKey // DestinationForeignKeys return destination foreign keys DestinationForeignKeys() []JoinTableForeignKey }
JoinTableHandlerInterface is an interface for how to handle many2many relations
type JoinTableSource struct { ModelType reflect.Type ForeignKeys []JoinTableForeignKey }
JoinTableSource is a struct that contains model type and foreign keys
type LogWriter interface {
Println(v ...interface{})
}
LogWriter log writer interface
Logger default logger
Print format & print log
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 struct { PrimaryFields []*StructField StructFields []*StructField ModelType reflect.Type // contains filtered or unexported fields }
ModelStruct model definition
func (s *ModelStruct) TableName(db *DB) string
TableName returns model's table name
Namer is a function type which is given a string and return a string
NamingStrategy represents naming strategies
func (ns *NamingStrategy) ColumnName(name string) string
ColumnName alters the given name by Column
func (ns *NamingStrategy) DBName(name string) string
DBName alters the given name by DB
func (ns *NamingStrategy) TableName(name string) string
TableName alters the given name by Table
type Relationship struct { Kind string PolymorphicType string PolymorphicDBName string PolymorphicValue string ForeignFieldNames []string ForeignDBNames []string AssociationForeignFieldNames []string AssociationForeignDBNames []string JoinTableHandler JoinTableHandlerInterface }
Relationship described the relationship between models
type SQLCommon interface { Exec(query string, args ...interface{}) (sql.Result, error) Prepare(query string) (*sql.Stmt, error) Query(query string, args ...interface{}) (*sql.Rows, error) QueryRow(query string, args ...interface{}) *sql.Row }
SQLCommon is the minimal database connection functionality gorm requires. Implemented by *sql.DB.
type Scope struct { Search *search Value interface{} SQL string SQLVars []interface{} // contains filtered or unexported fields }
Scope contain current operation's information when you perform any operation on the database
AddToVars add value as sql's vars, used to prevent SQL injection
Begin start a transaction
CallMethod call scope value's method, if it is a slice, will call its element's method one by one
CombinedConditionSql return combined condition sql
CommitOrRollback commit current transaction if no error happened, otherwise will rollback it
DB return scope's DB connection
Dialect get dialect
Err add error to Scope
Exec perform generated SQL
FieldByName find `gorm.Field` with field name or db name
Fields get value's fields
Get get setting by name
func (scope *Scope) GetModelStruct() *ModelStruct
GetModelStruct get value's model struct, relationships based on struct and tag definition
func (scope *Scope) GetStructFields() (fields []*StructField)
GetStructFields get model's field structs
HasColumn to check if has column
HasError check if there are any error
IndirectValue return scope's reflect value's indirect value
InstanceGet get instance setting from current operation
InstanceID get InstanceID for scope
InstanceSet set instance setting for current operation, but not for operations in callbacks, like saving associations callback
Log print log message
New create a new Scope without search information
NewDB create a new DB without search information
OmitAttrs return omitted attributes
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
PrimaryFields return scope's primary fields
PrimaryKey get main primary field's db name
PrimaryKeyValue get the primary key's value
PrimaryKeyZero check main primary field's value is blank or not
Quote used to quote string to escape them for database
QuotedTableName return quoted table name
Raw set raw sql
SQLDB return *sql.DB
SelectAttrs return selected attributes
Set set value by name
SetColumn to set the column's value, column could be field or field's name/dbname
SkipLeft skip remaining callbacks
TableName return table name
type SqlExpr struct {
// contains filtered or unexported fields
}
SQL expression
Expr generate raw SQL expression, for example:
DB.Model(&product).Update("price", gorm.Expr("price * ? + ?", 2, 100))
type StructField struct { DBName string Name string Names []string IsPrimaryKey bool IsNormal bool IsIgnored bool IsScanner bool HasDefaultValue bool Tag reflect.StructTag TagSettings map[string]string Struct reflect.StructField IsForeignKey bool Relationship *Relationship // contains filtered or unexported fields }
StructField model field's struct definition
func (sf *StructField) TagSettingsDelete(key string)
TagSettingsDelete deletes a tag
func (sf *StructField) TagSettingsGet(key string) (string, bool)
TagSettingsGet returns a tag from the tag settings
func (sf *StructField) TagSettingsSet(key, val string)
TagSettingsSet Sets a tag in the tag settings map
Path | Synopsis |
---|---|
dialects/mssql | |
dialects/mysql | |
dialects/postgres | |
dialects/sqlite |
Package gorm imports 22 packages (graph) and is imported by 4830 packages. Updated 2020-09-21. Refresh now. Tools for package owners.