mirror of
https://github.com/ent/ent.git
synced 2026-05-22 09:31:45 +03:00
dialect/sql: configure contains-fold per dialect (#666)
This commit is contained in:
@@ -1138,13 +1138,20 @@ func (p *Predicate) Contains(col, sub string) *Predicate {
|
||||
func ContainsFold(col, sub string) *Predicate { return (&Predicate{}).ContainsFold(col, sub) }
|
||||
|
||||
// ContainsFold is a helper predicate that applies the LIKE predicate with case-folding.
|
||||
// The recommendation is to avoid using it, and to use a dialect specific feature, like
|
||||
// `ILIKE` in PostgreSQL, and `COLLATE` clause in MySQL.
|
||||
func (p *Predicate) ContainsFold(col, sub string) *Predicate {
|
||||
return p.append(func(b *Builder) {
|
||||
f := &Func{}
|
||||
f.SetDialect(b.dialect)
|
||||
b.Ident(f.Lower(col)).WriteString(" LIKE ")
|
||||
switch b.dialect {
|
||||
case dialect.MySQL:
|
||||
// We assume the CHARACTER SET is configured to utf8mb4,
|
||||
// because this how it is defined in dialect/sql/schema.
|
||||
b.Ident(col).WriteString(" COLLATE utf8mb4_general_ci LIKE ")
|
||||
case dialect.Postgres:
|
||||
b.Ident(col).WriteString(" ILIKE ")
|
||||
default: // SQLite.
|
||||
b.Ident(f.Lower(col)).WriteString(" LIKE ")
|
||||
}
|
||||
b.Arg("%" + strings.ToLower(sub) + "%")
|
||||
})
|
||||
}
|
||||
|
||||
@@ -802,7 +802,8 @@ func TestBuilder(t *testing.T) {
|
||||
wantArgs: []interface{}{"bar", "baz"},
|
||||
},
|
||||
{
|
||||
input: Select().
|
||||
input: Dialect(dialect.SQLite).
|
||||
Select().
|
||||
From(Table("users")).
|
||||
Where(ContainsFold("name", "Ariel").And().ContainsFold("nick", "Bar")),
|
||||
wantQuery: "SELECT * FROM `users` WHERE LOWER(`name`) LIKE ? AND LOWER(`nick`) LIKE ?",
|
||||
@@ -813,7 +814,15 @@ func TestBuilder(t *testing.T) {
|
||||
Select().
|
||||
From(Table("users")).
|
||||
Where(ContainsFold("name", "Ariel").And().ContainsFold("nick", "Bar")),
|
||||
wantQuery: `SELECT * FROM "users" WHERE LOWER("name") LIKE $1 AND LOWER("nick") LIKE $2`,
|
||||
wantQuery: `SELECT * FROM "users" WHERE "name" ILIKE $1 AND "nick" ILIKE $2`,
|
||||
wantArgs: []interface{}{"%ariel%", "%bar%"},
|
||||
},
|
||||
{
|
||||
input: Dialect(dialect.MySQL).
|
||||
Select().
|
||||
From(Table("users")).
|
||||
Where(ContainsFold("name", "Ariel").And().ContainsFold("nick", "Bar")),
|
||||
wantQuery: "SELECT * FROM `users` WHERE `name` COLLATE utf8mb4_general_ci LIKE ? AND `nick` COLLATE utf8mb4_general_ci LIKE ?",
|
||||
wantArgs: []interface{}{"%ariel%", "%bar%"},
|
||||
},
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user