Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add substring and substr for field String #1194

Merged
merged 2 commits into from
Aug 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading