Skip to content

Commit

Permalink
feat: add substring and substr for field String (#1194)
Browse files Browse the repository at this point in the history
* feat: add substring and substr for field String

* feat: add comment for substring
  • Loading branch information
qqxhb authored Aug 21, 2024
1 parent 5360707 commit ebb6364
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
18 changes: 18 additions & 0 deletions do_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,24 @@ func TestDO_methods(t *testing.T) {
ExpectedVars: []interface{}{uint(10)},
Result: "WHERE `id` = ?",
},
{
Expr: u.Where(u.Name.Substring(1)),
Result: "WHERE SUBSTRING(`name`,1)",
},
{
Expr: u.Where(u.Name.Substring(1, 6), u.ID.Eq(10)),
ExpectedVars: []interface{}{uint(10)},
Result: "WHERE SUBSTRING(`name`,1,6) AND `id` = ?",
},
{
Expr: u.Where(u.Name.Substr(1), u.ID.Eq(10)),
ExpectedVars: []interface{}{uint(10)},
Result: "WHERE SUBSTR(`name`,1) AND `id` = ?",
},
{
Expr: u.Where(u.Name.Substr(1, 6)),
Result: "WHERE SUBSTR(`name`,1,6)",
},
{
Expr: u.Where(u.Name.Eq("tom"), u.Age.Gt(18)),
ExpectedVars: []interface{}{"tom", 18},
Expand Down
35 changes: 35 additions & 0 deletions field/string.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,41 @@ func (field String) SubstringIndex(delim string, count int) String {
}}}
}

// Substring https://dev.mysql.com/doc/refman/8.4/en/string-functions.html#function_substring
func (field String) Substring(params ...int) String {
if len(params) == 0 {
return field
}
if len(params) == 1 {
return String{expr{e: clause.Expr{
SQL: fmt.Sprintf("SUBSTRING(?,%d)", params[0]),
Vars: []interface{}{field.RawExpr()},
}}}
}
return String{expr{e: clause.Expr{
SQL: fmt.Sprintf("SUBSTRING(?,%d,%d)", params[0], params[1]),
Vars: []interface{}{field.RawExpr()},
}}}
}

// Substr SUBSTR is a synonym for SUBSTRING
// https://dev.mysql.com/doc/refman/8.4/en/string-functions.html#function_substring
func (field String) Substr(params ...int) String {
if len(params) == 0 {
return field
}
if len(params) == 1 {
return String{expr{e: clause.Expr{
SQL: fmt.Sprintf("SUBSTR(?,%d)", params[0]),
Vars: []interface{}{field.RawExpr()},
}}}
}
return String{expr{e: clause.Expr{
SQL: fmt.Sprintf("SUBSTR(?,%d,%d)", params[0], params[1]),
Vars: []interface{}{field.RawExpr()},
}}}
}

func (field String) toSlice(values []string) []interface{} {
slice := make([]interface{}, len(values))
for i, v := range values {
Expand Down

0 comments on commit ebb6364

Please sign in to comment.