github.com/mitranim/gg@v0.1.17/gsql/gsql_like.go (about) 1 package gsql 2 3 import ( 4 "database/sql/driver" 5 "strings" 6 7 "github.com/mitranim/gg" 8 ) 9 10 /* 11 Variant of `string` intended as an operand for SQL "like" and "ilike" operators. 12 When generating an SQL argument via `.Value`, the string is wrapped in `%` to 13 ensure partial match, escaping any pre-existing `%` and `_`. As a special case, 14 an empty string is used as-is, and doesn't match anything when used with 15 `like` or `ilike`. 16 */ 17 type Like string 18 19 // Implement `fmt.Stringer`. Returns the underlying string unchanged. 20 func (self Like) String() string { return string(self) } 21 22 // Implement `driver.Valuer`, returning the escaped string from `.Esc`. 23 func (self Like) Value() (driver.Value, error) { return self.Esc(), nil } 24 25 // Implement `sql.Scanner`. 26 func (self *Like) Scan(src any) error { 27 str, ok := gg.AnyToText[string](src) 28 if ok { 29 *self = Like(str) 30 return nil 31 } 32 return gg.ErrConv(src, gg.Type[Like]()) 33 } 34 35 /* 36 Returns an escaped string suitable as an operand for SQL "like" or "ilike". 37 As a special case, an empty string is returned as-is. 38 */ 39 func (self Like) Esc() string { 40 if self == `` { 41 return `` 42 } 43 return `%` + replaceLike.Replace(string(self)) + `%` 44 } 45 46 var replaceLike = strings.NewReplacer(`%`, `\%`, `_`, `\_`)