Skip to content

Commit

Permalink
fix. refactor ORM, refactor repository
Browse files Browse the repository at this point in the history
  • Loading branch information
imperiuse committed Jan 28, 2021
1 parent 2d0b215 commit 7e9b04f
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 57 deletions.
40 changes: 6 additions & 34 deletions reflect/orm/orm.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ type (
Column = string
Table = string
Typ = string
Join = string
JoinCond = string
Alias = string
Argument = interface{}

Expand All @@ -31,8 +31,7 @@ type (

MetaDTO = struct {
ColsMap map[ormUseInTagValue][]Column
Aliases []Alias
Join Join
JoinCond JoinCond
TableName Table
TableAlias Alias
StructName Typ
Expand Down Expand Up @@ -91,9 +90,9 @@ func getMetaDTO(structName string, obj interface{}) *MetaDTO {
return cacheMetaDTO[structName]
}

func GetDataForSelect(obj interface{}) ([]Column, []Alias, Join) {
func GetDataForSelect(obj interface{}) ([]Column, JoinCond) {
meta := GetMetaDTO(obj)
return meta.ColsMap[ormUseInSelect], meta.Aliases, meta.Join
return meta.ColsMap[ormUseInSelect], meta.JoinCond
}

func GetDataForCreate(obj interface{}) ([]Column, []Argument) {
Expand Down Expand Up @@ -124,29 +123,26 @@ func GetTableAlias(obj interface{}) Alias {
func GetTableNameWithAlias(obj interface{}) string {
meta := GetMetaDTO(obj)
if meta.TableName != "" && meta.TableAlias != "" {
return meta.TableName + " as " + meta.TableAlias
return fmt.Sprintf(" %s as %s ", meta.TableName, meta.TableAlias)
}
return ""
}

func getNoneCacheMetaDTO(obj interface{}) *MetaDTO {
meta := &MetaDTO{
ColsMap: map[ormUseInTagValue][]Column{ormUseInSelect: {}, ormUseInCreate: {}, ormUseInUpdate: {}},
Aliases: []Alias{},
StructName: getObjTypeNameByReflect(obj),
}
if obj == nil {
return meta
}

meta.Join = getMetaInfoForOrmTagOnlyOne(tagOrmJoin, obj)
meta.JoinCond = getMetaInfoForOrmTagOnlyOne(tagOrmJoin, obj)

meta.TableName = getMetaInfoForOrmTagOnlyOne(tagOrmTableName, obj)

meta.TableAlias = getMetaInfoForOrmTagOnlyOne(tagOrmAlias, obj)

meta.Aliases = getMetaInfoForOrmAliasTag(obj)

for _, v := range []string{ormUseInSelect, ormUseInCreate, ormUseInUpdate} {
meta.ColsMap[v], _ = getMetaInfoUseInTag(obj, v, emptyRootAlias)
}
Expand Down Expand Up @@ -184,30 +180,6 @@ func isTagEmpty(tag string) bool {
return tag == "" || tag == "-"
}

func getMetaInfoForOrmAliasTag(obj interface{}) []Alias {
aliases := []Alias{}

v := reflect.Indirect(reflect.ValueOf(obj))
t := v.Type()

if t.Kind() != reflect.Struct {
return aliases
}

for i := 0; i < t.NumField(); i++ {
field := t.Field(i)

if v.Field(i).Kind() == reflect.Struct {
aliasTagValue := field.Tag.Get(tagOrmAlias)
if !isTagEmpty(aliasTagValue) {
aliases = append(aliases, aliasTagValue)
}
}
}

return aliases
}

func getMetaInfoUseInTag(obj interface{}, useInTag ormUseInTagValue, alias Alias) ([]Column, []Argument) {
cols, args := []Column{}, []Argument{}

Expand Down
23 changes: 8 additions & 15 deletions reflect/orm/orm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,7 @@ func (suite *OrmTestSuit) Test_GetOrmDataForCreate() {

func (suite *OrmTestSuit) Test_GetOrmDataForSelect() {
t := suite.T()
cols, aliases, join := GetDataForSelect(&C{})
assert.NotNil(t, aliases)
assert.Equal(t, []string{"a", "b"}, aliases)
cols, join := GetDataForSelect(&C{})
assert.Equal(t, "ON a.id = b.id", join)
assert.Equal(t, []string{"a.id as \"a.id\"", "a.created_at as \"a.created_at\"", "a.updated_at as \"a.updated_at\"", "a.select_field as \"a.select_field\"", "b.id as \"b.id\"", "b.created_at as \"b.created_at\"", "b.updated_at as \"b.updated_at\"", "b.cus_field as \"b.cus_field\"", "b.cus2_field as \"b.cus2_field\""}, cols)
}
Expand Down Expand Up @@ -144,29 +142,24 @@ func (suite *OrmTestSuit) Test_BadGetOrmDataForCreate() {

func (suite *OrmTestSuit) Test_BadGetOrmDataForSelect() {
t := suite.T()
col, args, join := GetDataForSelect(&BadStruct{})
col, join := GetDataForSelect(&BadStruct{})
assert.Equal(t, []string{}, col)
assert.Equal(t, []string{}, args)
assert.Equal(t, "", join)

col, args, join = GetDataForSelect(nil)
col, join = GetDataForSelect(nil)
assert.Equal(t, []string{}, col)
assert.Equal(t, []string{}, args)
assert.Equal(t, "", join)

col, args, join = GetDataForSelect(new(interface{}))
col, join = GetDataForSelect(new(interface{}))
assert.Equal(t, []string{}, col)
assert.Equal(t, []string{}, args)
assert.Equal(t, "", join)

col, args, join = GetDataForSelect(1234)
col, join = GetDataForSelect(1234)
assert.Equal(t, []string{}, col)
assert.Equal(t, []string{}, args)
assert.Equal(t, "", join)

col, args, join = GetDataForSelect("")
col, join = GetDataForSelect("")
assert.Equal(t, []string{}, col)
assert.Equal(t, []string{}, args)
assert.Equal(t, "", join)

}
Expand Down Expand Up @@ -196,8 +189,8 @@ func (suite *OrmTestSuit) Test_GetTableNameWithAlias() {

_ = BadStruct{}.bad_name_field

assert.Equal(t, "A as a", GetTableNameWithAlias(&A{}))
assert.Equal(t, "B as b", GetTableNameWithAlias(&B{}))
assert.Equal(t, " A as a ", GetTableNameWithAlias(&A{}))
assert.Equal(t, " B as b ", GetTableNameWithAlias(&B{}))
assert.Equal(t, "", GetTableNameWithAlias(&C{}))
assert.Equal(t, "", GetTableNameWithAlias(nil))
assert.Equal(t, "", GetTableNameWithAlias(&BadStruct{}))
Expand Down
4 changes: 2 additions & 2 deletions sqlx/repository/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,14 +232,14 @@ func (r *repository) FindBy(ctx context.Context, columns []string, condition squ
return sqlx.SelectContext(ctx, r.db, target, query, args...)
}

func (r *repository) FindByWithInnerJoin(ctx context.Context, columns []string, alias string, join string, condition squirrel.Eq, target interface{}) error {
func (r *repository) FindByWithInnerJoin(ctx context.Context, columns []string, fromWithAlias string, join string, condition squirrel.Eq, target interface{}) error {
r.logger.Info("[repo.FindByWithInnerJoin]", r.zapFieldRepo(),
zap.Any("columns", columns),
zap.Any("join", join),
zap.Any("condition", condition))

query, args, err := squirrel.Select(columns...).
From(r.name + " as " + alias).
From(fromWithAlias).
InnerJoin(join).
Where(condition).
PlaceholderFormat(squirrel.Dollar).
Expand Down
13 changes: 7 additions & 6 deletions sqlx/repository/repository_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,14 @@ type (
Email string `db:"email" orm_use_in:"select,create,update"`
Password string `db:"password" orm_use_in:"select,create,update"`
RoleID Integer `db:"role_id" orm_use_in:"select,create,update"`
_ bool `orm_table_name:"Users"`
_ bool `orm_table_name:"Users" orm_alias:"u"`
}

Role struct {
BaseDTO
Name string `db:"name" orm_use_in:"select,create,update"`
Rights int `db:"rights" orm_use_in:"select,create,update"`
_ bool `orm_table_name:"Roles"`
_ bool `orm_table_name:"Roles" orm_alias:"r"`
}

UsersRole struct {
Expand Down Expand Up @@ -261,7 +261,7 @@ func (suite *RepositoryTestSuit) Test_EmptyRepo_NotPanic() {
assert.NotNil(t, err)
assert.Equal(t, uint64(0), ucnt)

err = r.FindByWithInnerJoin(suite.ctx, []Column{"*"}, "al", "ON al.id = p.id", squirrel.Eq{"id": 1}, &temp)
err = r.FindByWithInnerJoin(suite.ctx, []Column{"*"}, "al as al", "ON al.id = p.id", squirrel.Eq{"id": 1}, &temp)
assert.NotNil(t, err)

rows1, err := r.GetRowsByQuery(suite.ctx, squirrel.Select("*").From("unknown"))
Expand Down Expand Up @@ -398,10 +398,11 @@ func (suite *RepositoryTestSuit) Test_Advance_RepoFunc() {
assert.Nil(t, err)
assert.NotNil(t, userID)

cols, aliases, join := orm.GetDataForSelect(&UsersRole{})
join = orm.GetTableName(&Role{}) + " as " + aliases[1] + " " + join
cols, joinCond := orm.GetDataForSelect(&UsersRole{})
nameWithAlias := orm.GetTableNameWithAlias(&user)
joinCond = orm.GetTableNameWithAlias(&Role{}) + " " + joinCond
var ur UsersRole
err = suite.repos.AutoRepo(&user).FindByWithInnerJoin(ctx, cols, aliases[0], join, squirrel.Eq{"u.id": userID}, &ur)
err = suite.repos.AutoRepo(&user).FindByWithInnerJoin(ctx, cols, nameWithAlias, joinCond, squirrel.Eq{"u.id": userID}, &ur)
assert.Nil(t, err)
assert.NotNil(t, ur)
assert.Equal(t, userID, ur.User.ID)
Expand Down

0 comments on commit 7e9b04f

Please sign in to comment.