Skip to content

Commit

Permalink
feat: field build without quote
Browse files Browse the repository at this point in the history
  • Loading branch information
tr1v3r committed Sep 15, 2021
1 parent eb2e3d9 commit b97e691
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
9 changes: 9 additions & 0 deletions field/expr.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,22 @@ var (

// WithAll build column with table and alias
WithAll BuildOpt = func(col clause.Column) interface{} { return col }

// WithoutQuote
WithoutQuote BuildOpt = func(col clause.Column) interface{} {
col.Raw = true
return col
}
)

func (e expr) BuildColumn(stmt *gorm.Statement, opts ...BuildOpt) sql {
var col interface{} = e.col.Name
for _, opt := range opts {
col = opt(e.col)
}
if col, ok := col.(clause.Column); ok && col.Raw {
return sql(col.Table + "." + col.Name)
}
return sql(stmt.Quote(col))
}

Expand Down
18 changes: 18 additions & 0 deletions field/external_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,24 @@ func TestExpr_Build(t *testing.T) {
}
}

func TestExpr_BuildColumn(t *testing.T) {
stmt := field.GetStatement()
id := field.NewUint("user", "id")
expectColumnStr := "`id`"
expectColumnStrWithTable := "`user`.`id`"
expectColumnStrWithoutQuote := "user.id"

if colStr := id.BuildColumn(stmt).String(); colStr != expectColumnStr {
t.Errorf("id.BuildColumn(stmt).String() got: %q, except: %q", colStr, expectColumnStr)
}
if colStr := id.BuildColumn(stmt, field.WithTable).String(); colStr != expectColumnStrWithTable {
t.Errorf("id.BuildColumn(stmt, field.WithTable).String() got: %q, except: %q", colStr, expectColumnStrWithTable)
}
if colStr := id.BuildColumn(stmt, field.WithoutQuote).String(); colStr != expectColumnStrWithoutQuote {
t.Errorf("id.BuildColumn(stmt, field.WithoutQuote).String() got: %q, except: %q", colStr, expectColumnStrWithoutQuote)
}
}

func BenchmarkExpr_Count(b *testing.B) {
id := field.NewUint("", "id")
for i := 0; i < b.N; i++ {
Expand Down

0 comments on commit b97e691

Please sign in to comment.