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

use ilike for case insensitive search in PostgreSQL #544

Merged
merged 1 commit into from
Dec 10, 2021
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
11 changes: 11 additions & 0 deletions QueryBuilder.Tests/SelectTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -700,6 +700,17 @@ public void MultipleOrHaving()
Assert.Equal("SELECT * FROM [Table1] HAVING [Column1] > 1 OR [Column2] = 1", c[EngineCodes.SqlServer]);
}

[Fact]
public void ShouldUseILikeOnPostgresWhenNonCaseSensitive()
{
var q = new Query("Table1")
.WhereLike("Column1", "%Upper Word%", false);
var c = Compile(q);

Assert.Equal(@"SELECT * FROM [Table1] WHERE LOWER([Column1]) like '%upper word%'", c[EngineCodes.SqlServer]);
Assert.Equal("SELECT * FROM \"Table1\" WHERE \"Column1\" ilike '%Upper Word%'", c[EngineCodes.PostgreSql]);
}

[Fact]
public void EscapedWhereLike()
{
Expand Down
57 changes: 57 additions & 0 deletions QueryBuilder/Compilers/PostgresCompiler.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
using System;
using System.Linq;

namespace SqlKata.Compilers
{
public class PostgresCompiler : Compiler
Expand All @@ -9,6 +12,60 @@ public PostgresCompiler()

public override string EngineCode { get; } = EngineCodes.PostgreSql;


protected override string CompileBasicStringCondition(SqlResult ctx, BasicStringCondition x)
{

var column = Wrap(x.Column);

var value = Resolve(ctx, x.Value) as string;

if (value == null)
{
throw new ArgumentException("Expecting a non nullable string");
}

var method = x.Operator;

if (new[] { "starts", "ends", "contains", "like", "ilike" }.Contains(x.Operator))
{
method = x.CaseSensitive ? "LIKE" : "ILIKE";

switch (x.Operator)
{
case "starts":
value = $"{value}%";
break;
case "ends":
value = $"%{value}";
break;
case "contains":
value = $"%{value}%";
break;
}
}

string sql;

if (x.Value is UnsafeLiteral)
{
sql = $"{column} {checkOperator(method)} {value}";
}
else
{
sql = $"{column} {checkOperator(method)} {Parameter(ctx, value)}";
}

if (!string.IsNullOrEmpty(x.EscapeCharacter))
{
sql = $"{sql} ESCAPE '{x.EscapeCharacter}'";
}

return x.IsNot ? $"NOT ({sql})" : sql;

}


protected override string CompileBasicDateCondition(SqlResult ctx, BasicDateCondition condition)
{
var column = Wrap(condition.Column);
Expand Down