OrderBy support args #85

Merged
lunny merged 3 commits from lunny/orderby into master 2022-05-28 02:39:25 +00:00
3 changed files with 26 additions and 7 deletions

View File

@ -66,7 +66,7 @@ type Builder struct {
insertCols []string
insertVals []interface{}
updates []UpdateCond
orderBy string
orderBy interface{}
groupBy string
having string
}
@ -164,7 +164,6 @@ func (b *Builder) Except(distinctType string, cond *Builder) *Builder {
}
func (b *Builder) setOperation(opType, distinctType string, cond *Builder) *Builder {
var builder *Builder
if b.optype != setOpType {
builder = &Builder{cond: NewCond()}
@ -281,7 +280,7 @@ func (b *Builder) ToSQL() (string, []interface{}, error) {
}
}
var sql = w.String()
sql := w.String()
var err error
switch b.dialect {

View File

@ -124,9 +124,23 @@ func (b *Builder) selectWriteTo(w Writer) error {
}
}
if len(b.orderBy) > 0 {
if _, err := fmt.Fprint(w, " ORDER BY ", b.orderBy); err != nil {
return err
if b.orderBy != nil {
switch c := b.orderBy.(type) {
case string:
if len(c) > 0 {
if _, err := fmt.Fprint(w, " ORDER BY ", c); err != nil {
return err
}
}
case expr:
if _, err := fmt.Fprint(w, " ORDER BY "); err != nil {
return err
}
if err := c.WriteTo(w); err != nil {
return err
}
default:
return fmt.Errorf("unknow orderby parameter: %#v", b.orderBy)
}
}
@ -140,7 +154,7 @@ func (b *Builder) selectWriteTo(w Writer) error {
}
// OrderBy orderBy SQL
func (b *Builder) OrderBy(orderBy string) *Builder {
func (b *Builder) OrderBy(orderBy interface{}) *Builder {
b.orderBy = orderBy
return b
}

View File

@ -41,6 +41,12 @@ func TestBuilderSelectOrderBy(t *testing.T) {
assert.EqualValues(t, "SELECT c FROM table1 ORDER BY c DESC", sql)
assert.EqualValues(t, 0, len(args))
fmt.Println(sql, args)
sql, args, err = Select("c").From("table1").OrderBy(Expr("CASE WHEN owner_name LIKE ? THEN 0 ELSE 1 END", "a")).ToSQL()
assert.NoError(t, err)
assert.EqualValues(t, "SELECT c FROM table1 ORDER BY CASE WHEN owner_name LIKE ? THEN 0 ELSE 1 END", sql)
assert.EqualValues(t, 1, len(args))
fmt.Println(sql, args)
}
func TestBuilder_From(t *testing.T) {