diff --git a/field/export.go b/field/export.go index aef41a75..7364152d 100644 --- a/field/export.go +++ b/field/export.go @@ -32,6 +32,11 @@ func NewField(table, column string, opts ...Option) Field { return Field{expr: expr{col: toColumn(table, column, opts...)}} } +// NewFieldRaw create new field by native sql +func NewFieldRaw(rawSQL string, vars ...interface{}) Field { + return Field{expr: expr{e: clause.Expr{SQL: rawSQL, Vars: vars}}} +} + // NewSerializer create new field2 func NewSerializer(table, column string, opts ...Option) Serializer { return Serializer{expr: expr{col: toColumn(table, column, opts...)}} diff --git a/field/export_test.go b/field/export_test.go index 30c3d4b6..6157c26f 100644 --- a/field/export_test.go +++ b/field/export_test.go @@ -89,6 +89,56 @@ func TestExpr_Build(t *testing.T) { Expr: field.NewField("", "id").GroupConcat(), Result: "GROUP_CONCAT(`id`)", }, + { + Expr: field.NewFieldRaw("if(column1=?,column2,column3)", "1"), + Result: "if(column1=?,column2,column3)", + ExpectedVars: []interface{}{"1"}, + }, + { + Expr: field.NewFieldRaw("if(column1=?,column2,column3)", "1").Eq(p), + Result: "if(column1=?,column2,column3) = ?", + ExpectedVars: []interface{}{"1", p}, + }, + { + Expr: field.NewFieldRaw("if(column1=?,column2,column3)", field.NewField("", "new_id")).Eq(p), + Result: "if(column1=`new_id`,column2,column3) = ?", + ExpectedVars: []interface{}{p}, + }, + { + Expr: field.NewFieldRaw("if(column1=?,column2,column3)", "1").EqCol(field.NewField("", "new_id")), + Result: "if(column1=?,column2,column3) = `new_id`", + ExpectedVars: []interface{}{"1"}, + }, + { + Expr: field.NewFieldRaw("if(column1=?,column2,column3)", "1").EqCol(field.NewField("", "new_id").WithTable("tableB")), + Result: "if(column1=?,column2,column3) = `tableB`.`new_id`", + ExpectedVars: []interface{}{"1"}, + }, + { + Expr: field.NewFieldRaw("if(column1=?,column2,column3)", "1").IsNull(), + Result: "if(column1=?,column2,column3) IS NULL", + ExpectedVars: []interface{}{"1"}, + }, + { + Expr: field.NewFieldRaw("if(column1=?,column2,column3)", "1").GroupConcat(), + Result: "GROUP_CONCAT(if(column1=?,column2,column3))", + ExpectedVars: []interface{}{"1"}, + }, + { + Expr: field.NewFieldRaw("if(column1=?,column2,column3)", "1").Desc(), + Result: "if(column1=?,column2,column3) DESC", + ExpectedVars: []interface{}{"1"}, + }, + { + Expr: field.NewFieldRaw("if(column1=?,column2,column3)", "1").IfNull(p), + Result: "IFNULL(if(column1=?,column2,column3),?)", + ExpectedVars: []interface{}{"1", p}, + }, + { + Expr: field.NewFieldRaw("if(column1=?,column2,column3)", "1").As("column4"), + Result: "if(column1=?,column2,column3) AS `column4`", + ExpectedVars: []interface{}{"1"}, + }, { Expr: field.Func.UnixTimestamp(), Result: "UNIX_TIMESTAMP()",