Skip to content

Commit ebb6364

Browse files
authored
feat: add substring and substr for field String (#1194)
* feat: add substring and substr for field String * feat: add comment for substring
1 parent 5360707 commit ebb6364

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

do_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,24 @@ func TestDO_methods(t *testing.T) {
141141
ExpectedVars: []interface{}{uint(10)},
142142
Result: "WHERE `id` = ?",
143143
},
144+
{
145+
Expr: u.Where(u.Name.Substring(1)),
146+
Result: "WHERE SUBSTRING(`name`,1)",
147+
},
148+
{
149+
Expr: u.Where(u.Name.Substring(1, 6), u.ID.Eq(10)),
150+
ExpectedVars: []interface{}{uint(10)},
151+
Result: "WHERE SUBSTRING(`name`,1,6) AND `id` = ?",
152+
},
153+
{
154+
Expr: u.Where(u.Name.Substr(1), u.ID.Eq(10)),
155+
ExpectedVars: []interface{}{uint(10)},
156+
Result: "WHERE SUBSTR(`name`,1) AND `id` = ?",
157+
},
158+
{
159+
Expr: u.Where(u.Name.Substr(1, 6)),
160+
Result: "WHERE SUBSTR(`name`,1,6)",
161+
},
144162
{
145163
Expr: u.Where(u.Name.Eq("tom"), u.Age.Gt(18)),
146164
ExpectedVars: []interface{}{"tom", 18},

field/string.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,41 @@ func (field String) SubstringIndex(delim string, count int) String {
147147
}}}
148148
}
149149

150+
// Substring https://dev.mysql.com/doc/refman/8.4/en/string-functions.html#function_substring
151+
func (field String) Substring(params ...int) String {
152+
if len(params) == 0 {
153+
return field
154+
}
155+
if len(params) == 1 {
156+
return String{expr{e: clause.Expr{
157+
SQL: fmt.Sprintf("SUBSTRING(?,%d)", params[0]),
158+
Vars: []interface{}{field.RawExpr()},
159+
}}}
160+
}
161+
return String{expr{e: clause.Expr{
162+
SQL: fmt.Sprintf("SUBSTRING(?,%d,%d)", params[0], params[1]),
163+
Vars: []interface{}{field.RawExpr()},
164+
}}}
165+
}
166+
167+
// Substr SUBSTR is a synonym for SUBSTRING
168+
// https://dev.mysql.com/doc/refman/8.4/en/string-functions.html#function_substring
169+
func (field String) Substr(params ...int) String {
170+
if len(params) == 0 {
171+
return field
172+
}
173+
if len(params) == 1 {
174+
return String{expr{e: clause.Expr{
175+
SQL: fmt.Sprintf("SUBSTR(?,%d)", params[0]),
176+
Vars: []interface{}{field.RawExpr()},
177+
}}}
178+
}
179+
return String{expr{e: clause.Expr{
180+
SQL: fmt.Sprintf("SUBSTR(?,%d,%d)", params[0], params[1]),
181+
Vars: []interface{}{field.RawExpr()},
182+
}}}
183+
}
184+
150185
func (field String) toSlice(values []string) []interface{} {
151186
slice := make([]interface{}, len(values))
152187
for i, v := range values {

0 commit comments

Comments
 (0)