Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make beedb map structs to tables/columns by tags instead of putting underlines before capital letters #47

Merged
merged 3 commits into from Feb 9, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 7 additions & 11 deletions README.md
Expand Up @@ -63,20 +63,16 @@ Model a struct after a table in the db

```go
type Userinfo struct {
Uid int `beedb:"PK"` //if the table's PrimaryKey is not "Id", use this tag
Username string
Departname string
Created time.Time
Uid int `beedb:"PK" slq:"UID" tname:"USER_INFO"` //if the table's PrimaryKey is not "Id", use this tag
Username string `slq:"USERNAME"`
Departname string `slq:"DEPARTNAME"`
Created time.Time `slq:"CREATED"`
}
```

###***Caution***
The structs Name 'UserInfo' will turn into the table name 'user_info', the same as the keyname.
If the keyname is 'UserName' will turn into the select colum 'user_name'
If you want table names to be pluralized so that 'UserInfo' struct was treated as 'user_infos' table, just set following option:
```go
beedb.PluralizeTableNames=true
```
The structs Name 'UserInfo' will turn into the table name 'USER_INFO', as defined by the **tname** tag.
If the key 'UserName' will turn into the select colum 'USERNAME' because of the **sql** tag.


Create an object and save it
Expand Down Expand Up @@ -201,4 +197,4 @@ a, _ := orm.SetTable("userinfo").GroupBy("username").Having("username='astaxie'"
## LICENSE

BSD License
[http://creativecommons.org/licenses/BSD/](http://creativecommons.org/licenses/BSD/)
[http://creativecommons.org/licenses/BSD/](http://creativecommons.org/licenses/BSD/)
21 changes: 11 additions & 10 deletions beedb.go
Expand Up @@ -32,7 +32,7 @@ type Model struct {
}

/**
* Add New sql.DB in the future i will add ConnectionPool.Get()
* Add New sql.DB in the future i will add ConnectionPool.Get()
*/
func New(db *sql.DB, options ...interface{}) (m Model) {
if len(options) == 0 {
Expand Down Expand Up @@ -148,7 +148,7 @@ func (orm *Model) Find(output interface{}) error {
}

if orm.TableName == "" {
orm.TableName = getTableName(StructName(output))
orm.TableName = getTableName(output)
}
// If we've already specific columns with Select(), use that
if orm.ColumnStr == "*" {
Expand Down Expand Up @@ -275,15 +275,15 @@ func (orm *Model) FindMap() (resultsSlice []map[string][]byte, err error) {
case reflect.String:
str = vv.String()
result[key] = []byte(str)
//时间类型
//时间类型
case reflect.Struct:
str = rawValue.Interface().(time.Time).Format("2006-01-02 15:04:05.000 -0700")
result[key] = []byte(str)
case reflect.Bool:
if (vv.Bool()) {
result[key] = []byte("1")
if vv.Bool() {
result[key] = []byte("1")
} else {
result[key] = []byte("0")
result[key] = []byte("0")
}
}
}
Expand Down Expand Up @@ -386,10 +386,10 @@ func (orm *Model) Save(output interface{}) error {
}

if orm.TableName == "" {
orm.TableName = getTableName(StructName(output))
orm.TableName = getTableName(output)
}
id := results[snakeCasedName(orm.PrimaryKey)]
delete(results, snakeCasedName(orm.PrimaryKey))
id := results[orm.PrimaryKey]
delete(results, orm.PrimaryKey)
if reflect.ValueOf(id).Int() == 0 {
structPtr := reflect.ValueOf(output)
structVal := structPtr.Elem()
Expand Down Expand Up @@ -552,7 +552,7 @@ func (orm *Model) Delete(output interface{}) (int64, error) {
}

if orm.TableName == "" {
orm.TableName = getTableName(StructName(output))
orm.TableName = getTableName(output)
}
id := results[strings.ToLower(orm.PrimaryKey)]
condition := fmt.Sprintf("%v%v%v='%v'", orm.QuoteIdentifier, strings.ToLower(orm.PrimaryKey), orm.QuoteIdentifier, id)
Expand Down Expand Up @@ -581,6 +581,7 @@ func (orm *Model) DeleteAll(rowsSlicePtr interface{}) (int64, error) {
defer orm.InitModel()
orm.ScanPK(rowsSlicePtr)
if orm.TableName == "" {
//TODO: fix table name
orm.TableName = getTableName(getTypeName(rowsSlicePtr))
}
var ids []string
Expand Down
52 changes: 45 additions & 7 deletions util.go
Expand Up @@ -2,7 +2,6 @@ package beedb

import (
"errors"
"github.com/grsmv/inflect"
"reflect"
"strconv"
"strings"
Expand Down Expand Up @@ -155,10 +154,20 @@ func scanStructIntoMap(obj interface{}) (map[string]interface{}, error) {
field := dataStructType.Field(i)
fieldName := field.Name
bb := field.Tag
if bb.Get("beedb") == "-" || reflect.ValueOf(bb).String() == "-" {
sqlTag := bb.Get("sql")
var mapKey string
if bb.Get("beedb") == "-" || sqlTag == "-" || reflect.ValueOf(bb).String() == "-" {
continue
} else if len(sqlTag) > 0 {
sqtags := strings.Split(sqlTag, ",")
//TODO: support tags that are common in json like omitempty
if sqtags[0] == "-" || sqtags[0] == "" {
continue
}
mapKey = sqtags[0]
} else {
mapKey = snakeCasedName(fieldName)
}
mapKey := snakeCasedName(fieldName)
value := dataStruct.FieldByName(fieldName).Interface()

mapped[mapKey] = value
Expand All @@ -175,9 +184,38 @@ func StructName(s interface{}) string {
return v.Name()
}

func getTableName(name string) string {
if PluralizeTableNames {
return inflect.Pluralize(snakeCasedName(name))
func getTableName(s interface{}) string {
v := reflect.TypeOf(s)
if v.Kind() == reflect.String {
s2, _ := s.(string)
return snakeCasedName(s2)
}
tn := scanTableName(s)
if len(tn) > 0 {
return tn
}
return snakeCasedName(name)
return getTableName(StructName(s))
}

func scanTableName(s interface{}) string {
if reflect.TypeOf(reflect.Indirect(reflect.ValueOf(s)).Interface()).Kind() == reflect.Slice {
sliceValue := reflect.Indirect(reflect.ValueOf(s))
sliceElementType := sliceValue.Type().Elem()
for i := 0; i < sliceElementType.NumField(); i++ {
bb := sliceElementType.Field(i).Tag
if len(bb.Get("tname")) > 0 {
return bb.Get("tname")
}
}
} else {
tt := reflect.TypeOf(reflect.Indirect(reflect.ValueOf(s)).Interface())
for i := 0; i < tt.NumField(); i++ {
bb := tt.Field(i).Tag
if len(bb.Get("tname")) > 0 {
return bb.Get("tname")
}
}
}
return ""

}