mirror of https://github.com/go-gorm/gorm.git
Use Common Initialisms from golint
This commit is contained in:
parent
672ba4ffc9
commit
5c478b46e1
|
@ -39,7 +39,6 @@ db.Save(&User{Name: "xxx"}) // table "users"
|
||||||
|
|
||||||
* Column name is the snake case of field's name
|
* Column name is the snake case of field's name
|
||||||
* Use `Id` field as primary key
|
* Use `Id` field as primary key
|
||||||
* Use tag `sql` to change field's property, change the tag name with `db.SetTagIdentifier(new_name)`
|
|
||||||
* Use `CreatedAt` to store record's created time if field exists
|
* Use `CreatedAt` to store record's created time if field exists
|
||||||
* Use `UpdatedAt` to store record's updated time if field exists
|
* Use `UpdatedAt` to store record's updated time if field exists
|
||||||
* Use `DeletedAt` to store record's deleted time if field exists [Soft Delete](#soft-delete)
|
* Use `DeletedAt` to store record's deleted time if field exists [Soft Delete](#soft-delete)
|
||||||
|
|
|
@ -157,7 +157,7 @@ func (association *Association) Count() int {
|
||||||
whereSql := fmt.Sprintf("%v.%v = ?", newScope.QuotedTableName(), newScope.Quote(relationship.ForeignDBName))
|
whereSql := fmt.Sprintf("%v.%v = ?", newScope.QuotedTableName(), newScope.Quote(relationship.ForeignDBName))
|
||||||
countScope := scope.db.Model("").Table(newScope.QuotedTableName()).Where(whereSql, association.PrimaryKey)
|
countScope := scope.db.Model("").Table(newScope.QuotedTableName()).Where(whereSql, association.PrimaryKey)
|
||||||
if relationship.ForeignType != "" {
|
if relationship.ForeignType != "" {
|
||||||
countScope = countScope.Where(fmt.Sprintf("%v.%v = ?", newScope.QuotedTableName(), newScope.Quote(ToDBColumnName(relationship.ForeignType))), scope.TableName())
|
countScope = countScope.Where(fmt.Sprintf("%v.%v = ?", newScope.QuotedTableName(), newScope.Quote(ToDBName(relationship.ForeignType))), scope.TableName())
|
||||||
}
|
}
|
||||||
countScope.Count(&count)
|
countScope.Count(&count)
|
||||||
} else if relationship.Kind == "belongs_to" {
|
} else if relationship.Kind == "belongs_to" {
|
||||||
|
|
|
@ -65,11 +65,11 @@ func TestRelated(t *testing.T) {
|
||||||
|
|
||||||
DB.Save(&user)
|
DB.Save(&user)
|
||||||
|
|
||||||
if user.CreditCard.Id == 0 {
|
if user.CreditCard.ID == 0 {
|
||||||
t.Errorf("After user save, credit card should have id")
|
t.Errorf("After user save, credit card should have id")
|
||||||
}
|
}
|
||||||
|
|
||||||
if user.BillingAddress.Id == 0 {
|
if user.BillingAddress.ID == 0 {
|
||||||
t.Errorf("After user save, billing address should have id")
|
t.Errorf("After user save, billing address should have id")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -26,7 +26,7 @@ func Create(scope *Scope) {
|
||||||
var sqls, columns []string
|
var sqls, columns []string
|
||||||
for _, field := range scope.Fields() {
|
for _, field := range scope.Fields() {
|
||||||
if (field.IsNormal && !field.IsPrimaryKey) || (field.IsPrimaryKey && !field.IsBlank) {
|
if (field.IsNormal && !field.IsPrimaryKey) || (field.IsPrimaryKey && !field.IsBlank) {
|
||||||
if !field.IsBlank || field.DefaultValue == nil {
|
if !field.IsBlank || !field.HasDefaultValue {
|
||||||
columns = append(columns, scope.Quote(field.DBName))
|
columns = append(columns, scope.Quote(field.DBName))
|
||||||
sqls = append(sqls, scope.AddToVars(field.Field.Interface()))
|
sqls = append(sqls, scope.AddToVars(field.Field.Interface()))
|
||||||
}
|
}
|
||||||
|
|
|
@ -48,7 +48,7 @@ func Update(scope *Scope) {
|
||||||
} else {
|
} else {
|
||||||
for _, field := range scope.Fields() {
|
for _, field := range scope.Fields() {
|
||||||
if !field.IsPrimaryKey && field.IsNormal {
|
if !field.IsPrimaryKey && field.IsNormal {
|
||||||
if !field.IsBlank || field.DefaultValue == nil {
|
if !field.IsBlank || !field.HasDefaultValue {
|
||||||
sqls = append(sqls, fmt.Sprintf("%v = %v", scope.Quote(field.DBName), scope.AddToVars(field.Field.Interface())))
|
sqls = append(sqls, fmt.Sprintf("%v = %v", scope.Quote(field.DBName), scope.AddToVars(field.Field.Interface())))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -22,14 +22,14 @@ type StructField struct {
|
||||||
Name string
|
Name string
|
||||||
Names []string
|
Names []string
|
||||||
IsPrimaryKey bool
|
IsPrimaryKey bool
|
||||||
IsScanner bool
|
|
||||||
IsTime bool
|
|
||||||
IsNormal bool
|
IsNormal bool
|
||||||
IsIgnored bool
|
IsIgnored bool
|
||||||
DefaultValue *string
|
IsScanner bool
|
||||||
|
HasDefaultValue bool
|
||||||
SqlTag string
|
SqlTag string
|
||||||
Tag reflect.StructTag
|
Tag reflect.StructTag
|
||||||
Struct reflect.StructField
|
Struct reflect.StructField
|
||||||
|
IsForeignKey bool
|
||||||
Relationship *Relationship
|
Relationship *Relationship
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -39,14 +39,14 @@ func (structField *StructField) clone() *StructField {
|
||||||
Name: structField.Name,
|
Name: structField.Name,
|
||||||
Names: structField.Names,
|
Names: structField.Names,
|
||||||
IsPrimaryKey: structField.IsPrimaryKey,
|
IsPrimaryKey: structField.IsPrimaryKey,
|
||||||
IsScanner: structField.IsScanner,
|
|
||||||
IsTime: structField.IsTime,
|
|
||||||
IsNormal: structField.IsNormal,
|
IsNormal: structField.IsNormal,
|
||||||
IsIgnored: structField.IsIgnored,
|
IsIgnored: structField.IsIgnored,
|
||||||
DefaultValue: structField.DefaultValue,
|
IsScanner: structField.IsScanner,
|
||||||
|
HasDefaultValue: structField.HasDefaultValue,
|
||||||
SqlTag: structField.SqlTag,
|
SqlTag: structField.SqlTag,
|
||||||
Tag: structField.Tag,
|
Tag: structField.Tag,
|
||||||
Struct: structField.Struct,
|
Struct: structField.Struct,
|
||||||
|
IsForeignKey: structField.IsForeignKey,
|
||||||
Relationship: structField.Relationship,
|
Relationship: structField.Relationship,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -146,7 +146,7 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
modelStruct.TableName = ToDBColumnName(scopeType.Name())
|
modelStruct.TableName = ToDBName(scopeType.Name())
|
||||||
if scope.db == nil || !scope.db.parent.singularTable {
|
if scope.db == nil || !scope.db.parent.singularTable {
|
||||||
for index, reg := range pluralMapKeys {
|
for index, reg := range pluralMapKeys {
|
||||||
if reg.MatchString(modelStruct.TableName) {
|
if reg.MatchString(modelStruct.TableName) {
|
||||||
|
@ -176,14 +176,14 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
|
||||||
modelStruct.PrimaryKeyField = field
|
modelStruct.PrimaryKeyField = field
|
||||||
}
|
}
|
||||||
|
|
||||||
if value, ok := sqlSettings["DEFAULT"]; ok {
|
if _, ok := sqlSettings["DEFAULT"]; ok {
|
||||||
field.DefaultValue = &value
|
field.HasDefaultValue = true
|
||||||
}
|
}
|
||||||
|
|
||||||
if value, ok := gormSettings["COLUMN"]; ok {
|
if value, ok := gormSettings["COLUMN"]; ok {
|
||||||
field.DBName = value
|
field.DBName = value
|
||||||
} else {
|
} else {
|
||||||
field.DBName = ToDBColumnName(fieldStruct.Name)
|
field.DBName = ToDBName(fieldStruct.Name)
|
||||||
}
|
}
|
||||||
|
|
||||||
fieldType, indirectType := fieldStruct.Type, fieldStruct.Type
|
fieldType, indirectType := fieldStruct.Type, fieldStruct.Type
|
||||||
|
@ -196,7 +196,7 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, isTime := reflect.New(indirectType).Interface().(*time.Time); isTime {
|
if _, isTime := reflect.New(indirectType).Interface().(*time.Time); isTime {
|
||||||
field.IsTime, field.IsNormal = true, true
|
field.IsNormal = true
|
||||||
}
|
}
|
||||||
|
|
||||||
many2many := gormSettings["MANY2MANY"]
|
many2many := gormSettings["MANY2MANY"]
|
||||||
|
@ -238,8 +238,8 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
|
||||||
ForeignType: foreignType,
|
ForeignType: foreignType,
|
||||||
ForeignFieldName: foreignKey,
|
ForeignFieldName: foreignKey,
|
||||||
AssociationForeignFieldName: associationForeignKey,
|
AssociationForeignFieldName: associationForeignKey,
|
||||||
ForeignDBName: ToDBColumnName(foreignKey),
|
ForeignDBName: ToDBName(foreignKey),
|
||||||
AssociationForeignDBName: ToDBColumnName(associationForeignKey),
|
AssociationForeignDBName: ToDBName(associationForeignKey),
|
||||||
Kind: kind,
|
Kind: kind,
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
@ -274,7 +274,7 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
|
||||||
|
|
||||||
field.Relationship = &Relationship{
|
field.Relationship = &Relationship{
|
||||||
ForeignFieldName: foreignKey,
|
ForeignFieldName: foreignKey,
|
||||||
ForeignDBName: ToDBColumnName(foreignKey),
|
ForeignDBName: ToDBName(foreignKey),
|
||||||
ForeignType: foreignType,
|
ForeignType: foreignType,
|
||||||
Kind: kind,
|
Kind: kind,
|
||||||
}
|
}
|
||||||
|
|
2
scope.go
2
scope.go
|
@ -145,7 +145,7 @@ func (scope *Scope) SetColumn(column interface{}, value interface{}) error {
|
||||||
return field.Set(value)
|
return field.Set(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
dbName = ToDBColumnName(dbName)
|
dbName = ToDBName(dbName)
|
||||||
if field, ok := scope.Fields()[dbName]; ok {
|
if field, ok := scope.Fields()[dbName]; ok {
|
||||||
return field.Set(value)
|
return field.Set(value)
|
||||||
}
|
}
|
||||||
|
|
|
@ -316,7 +316,7 @@ func (scope *Scope) updatedAttrsWithValues(values map[string]interface{}, ignore
|
||||||
|
|
||||||
fields := scope.Fields()
|
fields := scope.Fields()
|
||||||
for key, value := range values {
|
for key, value := range values {
|
||||||
if field, ok := fields[ToDBColumnName(key)]; ok && field.Field.IsValid() {
|
if field, ok := fields[ToDBName(key)]; ok && field.Field.IsValid() {
|
||||||
if !reflect.DeepEqual(field.Field, reflect.ValueOf(value)) {
|
if !reflect.DeepEqual(field.Field, reflect.ValueOf(value)) {
|
||||||
if !equalAsString(field.Field.Interface(), value) {
|
if !equalAsString(field.Field.Interface(), value) {
|
||||||
hasUpdate = true
|
hasUpdate = true
|
||||||
|
@ -389,8 +389,8 @@ func (scope *Scope) related(value interface{}, foreignKeys ...string) *Scope {
|
||||||
fromFields := scope.Fields()
|
fromFields := scope.Fields()
|
||||||
toFields := toScope.Fields()
|
toFields := toScope.Fields()
|
||||||
for _, foreignKey := range append(foreignKeys, toScope.typeName()+"Id", scope.typeName()+"Id") {
|
for _, foreignKey := range append(foreignKeys, toScope.typeName()+"Id", scope.typeName()+"Id") {
|
||||||
fromField := fromFields[ToDBColumnName(foreignKey)]
|
fromField := fromFields[ToDBName(foreignKey)]
|
||||||
toField := toFields[ToDBColumnName(foreignKey)]
|
toField := toFields[ToDBName(foreignKey)]
|
||||||
|
|
||||||
if fromField != nil {
|
if fromField != nil {
|
||||||
if relationship := fromField.Relationship; relationship != nil {
|
if relationship := fromField.Relationship; relationship != nil {
|
||||||
|
@ -411,7 +411,7 @@ func (scope *Scope) related(value interface{}, foreignKeys ...string) *Scope {
|
||||||
sql := fmt.Sprintf("%v = ?", scope.Quote(relationship.ForeignDBName))
|
sql := fmt.Sprintf("%v = ?", scope.Quote(relationship.ForeignDBName))
|
||||||
query := toScope.db.Where(sql, scope.PrimaryKeyValue())
|
query := toScope.db.Where(sql, scope.PrimaryKeyValue())
|
||||||
if relationship.ForeignType != "" && toScope.HasColumn(relationship.ForeignType) {
|
if relationship.ForeignType != "" && toScope.HasColumn(relationship.ForeignType) {
|
||||||
query = query.Where(fmt.Sprintf("%v = ?", scope.Quote(ToDBColumnName(relationship.ForeignType))), scope.TableName())
|
query = query.Where(fmt.Sprintf("%v = ?", scope.Quote(ToDBName(relationship.ForeignType))), scope.TableName())
|
||||||
}
|
}
|
||||||
scope.Err(query.Find(value).Error)
|
scope.Err(query.Find(value).Error)
|
||||||
}
|
}
|
||||||
|
|
|
@ -36,7 +36,7 @@ type User struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
type CreditCard struct {
|
type CreditCard struct {
|
||||||
Id int8
|
ID int8
|
||||||
Number string
|
Number string
|
||||||
UserId sql.NullInt64
|
UserId sql.NullInt64
|
||||||
CreatedAt time.Time
|
CreatedAt time.Time
|
||||||
|
@ -53,7 +53,7 @@ type Email struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
type Address struct {
|
type Address struct {
|
||||||
Id int
|
ID int
|
||||||
Address1 string
|
Address1 string
|
||||||
Address2 string
|
Address2 string
|
||||||
Post string
|
Post string
|
||||||
|
|
21
utils.go
21
utils.go
|
@ -5,15 +5,28 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Copied from golint
|
||||||
|
var commonInitialisms = []string{"API", "ASCII", "CPU", "CSS", "DNS", "EOF", "GUID", "HTML", "HTTP", "HTTPS", "ID", "IP", "JSON", "LHS", "QPS", "RAM", "RHS", "RPC", "SLA", "SMTP", "SSH", "TLS", "TTL", "UI", "UID", "UUID", "URI", "URL", "UTF8", "VM", "XML", "XSRF", "XSS"}
|
||||||
|
var commonInitialismsReplacer *strings.Replacer
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
var commonInitialismsForReplacer []string
|
||||||
|
for _, initialism := range commonInitialisms {
|
||||||
|
commonInitialismsForReplacer = append(commonInitialismsForReplacer, initialism, strings.Title(strings.ToLower(initialism)))
|
||||||
|
}
|
||||||
|
commonInitialismsReplacer = strings.NewReplacer(commonInitialismsForReplacer...)
|
||||||
|
}
|
||||||
|
|
||||||
var smap = map[string]string{}
|
var smap = map[string]string{}
|
||||||
|
|
||||||
func ToDBColumnName(u string) string {
|
func ToDBName(name string) string {
|
||||||
if v, ok := smap[u]; ok {
|
if v, ok := smap[name]; ok {
|
||||||
return v
|
return v
|
||||||
}
|
}
|
||||||
|
|
||||||
|
value := commonInitialismsReplacer.Replace(name)
|
||||||
buf := bytes.NewBufferString("")
|
buf := bytes.NewBufferString("")
|
||||||
for i, v := range u {
|
for i, v := range value {
|
||||||
if i > 0 && v >= 'A' && v <= 'Z' {
|
if i > 0 && v >= 'A' && v <= 'Z' {
|
||||||
buf.WriteRune('_')
|
buf.WriteRune('_')
|
||||||
}
|
}
|
||||||
|
@ -21,7 +34,7 @@ func ToDBColumnName(u string) string {
|
||||||
}
|
}
|
||||||
|
|
||||||
s := strings.ToLower(buf.String())
|
s := strings.ToLower(buf.String())
|
||||||
smap[u] = s
|
smap[name] = s
|
||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -44,7 +44,7 @@ func convertInterfaceToMap(values interface{}) map[string]interface{} {
|
||||||
switch value := values.(type) {
|
switch value := values.(type) {
|
||||||
case map[string]interface{}:
|
case map[string]interface{}:
|
||||||
for k, v := range value {
|
for k, v := range value {
|
||||||
attrs[ToDBColumnName(k)] = v
|
attrs[ToDBName(k)] = v
|
||||||
}
|
}
|
||||||
case []interface{}:
|
case []interface{}:
|
||||||
for _, v := range value {
|
for _, v := range value {
|
||||||
|
@ -58,7 +58,7 @@ func convertInterfaceToMap(values interface{}) map[string]interface{} {
|
||||||
switch reflectValue.Kind() {
|
switch reflectValue.Kind() {
|
||||||
case reflect.Map:
|
case reflect.Map:
|
||||||
for _, key := range reflectValue.MapKeys() {
|
for _, key := range reflectValue.MapKeys() {
|
||||||
attrs[ToDBColumnName(key.Interface().(string))] = reflectValue.MapIndex(key).Interface()
|
attrs[ToDBName(key.Interface().(string))] = reflectValue.MapIndex(key).Interface()
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
scope := Scope{Value: values}
|
scope := Scope{Value: values}
|
||||||
|
|
Loading…
Reference in New Issue