From ebb636437c9af9de4c914b782926d6d829fe4fcb Mon Sep 17 00:00:00 2001 From: qqxhb <30866940+qqxhb@users.noreply.github.com> Date: Wed, 21 Aug 2024 11:07:01 +0800 Subject: [PATCH] feat: add substring and substr for field String (#1194) * feat: add substring and substr for field String * feat: add comment for substring --- do_test.go | 18 ++++++++++++++++++ field/string.go | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/do_test.go b/do_test.go index d1bd6812..00e52f44 100644 --- a/do_test.go +++ b/do_test.go @@ -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}, diff --git a/field/string.go b/field/string.go index 5fe56742..c587073e 100644 --- a/field/string.go +++ b/field/string.go @@ -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 {