xorm/mapper.go

131 lines
2.5 KiB
Go
Raw Normal View History

2013-05-03 07:26:51 +00:00
package xorm
import (
//"reflect"
//"strings"
)
2013-09-11 08:23:10 +00:00
// name translation between struct, fields names and table, column names
2013-05-03 07:26:51 +00:00
type IMapper interface {
Obj2Table(string) string
Table2Obj(string) string
}
2013-11-22 06:11:07 +00:00
// SameMapper implements IMapper and provides same name between struct and
// database table
2013-09-06 06:32:20 +00:00
type SameMapper struct {
}
func (m SameMapper) Obj2Table(o string) string {
return o
}
func (m SameMapper) Table2Obj(t string) string {
return t
}
2013-11-22 06:11:07 +00:00
// SnakeMapper implements IMapper and provides name transaltion between
// struct and database table
2013-05-03 07:26:51 +00:00
type SnakeMapper struct {
}
func snakeCasedName(name string) string {
newstr := make([]rune, 0)
2013-11-15 03:01:13 +00:00
for idx, chr := range name {
2013-05-03 07:26:51 +00:00
if isUpper := 'A' <= chr && chr <= 'Z'; isUpper {
2013-11-15 03:01:13 +00:00
if idx > 0 {
2013-05-03 07:26:51 +00:00
newstr = append(newstr, '_')
}
chr -= ('A' - 'a')
}
newstr = append(newstr, chr)
}
return string(newstr)
}
2013-11-15 03:01:13 +00:00
/*func pascal2Sql(s string) (d string) {
2013-05-03 07:26:51 +00:00
d = ""
lastIdx := 0
for i := 0; i < len(s); i++ {
if s[i] >= 'A' && s[i] <= 'Z' {
if lastIdx < i {
d += s[lastIdx+1 : i]
}
if i != 0 {
d += "_"
}
d += string(s[i] + 32)
lastIdx = i
}
}
d += s[lastIdx+1:]
return
2013-11-15 03:01:13 +00:00
}*/
2013-05-03 07:26:51 +00:00
func (mapper SnakeMapper) Obj2Table(name string) string {
return snakeCasedName(name)
}
func titleCasedName(name string) string {
newstr := make([]rune, 0)
upNextChar := true
for _, chr := range name {
switch {
case upNextChar:
upNextChar = false
2013-10-12 15:16:51 +00:00
if 'a' <= chr && chr <= 'z' {
chr -= ('a' - 'A')
}
2013-05-03 07:26:51 +00:00
case chr == '_':
upNextChar = true
continue
}
newstr = append(newstr, chr)
}
return string(newstr)
}
func (mapper SnakeMapper) Table2Obj(name string) string {
return titleCasedName(name)
}
2013-11-27 07:53:05 +00:00
// provide prefix table name support
type PrefixMapper struct {
Mapper IMapper
Prefix string
}
func (mapper PrefixMapper) Obj2Table(name string) string {
return mapper.Prefix + mapper.Mapper.Obj2Table(name)
}
func (mapper PrefixMapper) Table2Obj(name string) string {
return mapper.Mapper.Table2Obj(name[len(mapper.Prefix):])
}
func NewPrefixMapper(mapper IMapper, prefix string) PrefixMapper {
return PrefixMapper{mapper, prefix}
}
// provide suffix table name support
type SuffixMapper struct {
Mapper IMapper
Suffix string
}
func (mapper SuffixMapper) Obj2Table(name string) string {
return mapper.Suffix + mapper.Mapper.Obj2Table(name)
}
func (mapper SuffixMapper) Table2Obj(name string) string {
return mapper.Mapper.Table2Obj(name[len(mapper.Suffix):])
}
func NewSuffixMapper(mapper IMapper, suffix string) SuffixMapper {
return SuffixMapper{mapper, suffix}
}