|
| 1 | +using SqlKata.Compilers; |
| 2 | +using SqlKata.Tests.Infrastructure; |
| 3 | +using System; |
| 4 | +using Xunit; |
| 5 | + |
| 6 | +namespace SqlKata.Tests.PostgreSql |
| 7 | +{ |
| 8 | + public class PostgresJsonTests : TestSupport |
| 9 | + { |
| 10 | + public class JsonAwarePostgresCompiler : PostgresCompiler |
| 11 | + { |
| 12 | + public override string ParameterPlaceholder { get; protected set; } = "$$"; |
| 13 | + } |
| 14 | + |
| 15 | + private readonly JsonAwarePostgresCompiler compiler = new(); |
| 16 | + private PostgresCompiler regularCompiler; |
| 17 | + |
| 18 | + public PostgresJsonTests() |
| 19 | + { |
| 20 | + regularCompiler = Compilers.Get<PostgresCompiler>(EngineCodes.PostgreSql); |
| 21 | + } |
| 22 | + |
| 23 | + [Fact] |
| 24 | + public void LimitWithCustomPlaceHolder() |
| 25 | + { |
| 26 | + var query = new Query("Table").Limit(10); |
| 27 | + var ctx = new SqlResult(compiler) { Query = query }; |
| 28 | + |
| 29 | + Assert.Equal($"LIMIT $$", compiler.CompileLimit(ctx)); |
| 30 | + Assert.Equal(10, ctx.Bindings[0]); |
| 31 | + } |
| 32 | + |
| 33 | + [Fact] |
| 34 | + public void RegularCompilerThrowsExceptionWhereRawJsonContainsQuestionMarkData() |
| 35 | + { |
| 36 | + Assert.Throws<IndexOutOfRangeException>(() => |
| 37 | + { |
| 38 | + Query query = CreateQuestionMarkJsonQuery(out var rawCondition); |
| 39 | + |
| 40 | + SqlResult result = regularCompiler.Compile(query); |
| 41 | + Assert.Equal($"SELECT * FROM \"Table\" WHERE {rawCondition}", result.ToString()); |
| 42 | + }); |
| 43 | + } |
| 44 | + |
| 45 | + private Query CreateQuestionMarkJsonQuery(out string rawCondition) |
| 46 | + { |
| 47 | + rawCondition = "my_json_column @> '{\"json_param\" : \"question mark ? \"}'"; |
| 48 | + var escapedJsonCondition = rawCondition.Replace("{", "\\{").Replace("}", "\\}"); |
| 49 | + return new Query("Table").WhereRaw(escapedJsonCondition); |
| 50 | + } |
| 51 | + |
| 52 | + [Fact] |
| 53 | + public void WhereRawJsonWithQuestionMarkData() |
| 54 | + { |
| 55 | + Query query = CreateQuestionMarkJsonQuery(out var rawCondition); |
| 56 | + SqlResult result = compiler.Compile(query); |
| 57 | + Assert.Equal($"SELECT * FROM \"Table\" WHERE {rawCondition}", result.ToString()); |
| 58 | + } |
| 59 | + |
| 60 | + [Fact] |
| 61 | + public void UsingJsonArray() |
| 62 | + { |
| 63 | + var query = new Query("Table").WhereRaw("[Json]->'address'->>'country' in ($$)", new[] { 1, 2, 3, 4 }); |
| 64 | + |
| 65 | + SqlResult result = compiler.Compile(query); |
| 66 | + |
| 67 | + Assert.Equal("SELECT * FROM \"Table\" WHERE \"Json\"->'address'->>'country' in (1,2,3,4)", result.ToString()); |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments