Skip to content
Draft
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
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,31 @@ public static T Greatest<T>(
this DbFunctions _,
[NotParameterized] params T[] values)
=> throw new InvalidOperationException(CoreStrings.FunctionOnClient(nameof(Greatest)));

/// <summary>
/// Checks whether a specified JSON path exists within a JSON string.
/// Typically corresponds to a database function or SQL expression.
/// </summary>
/// <remarks>
/// <para>
/// This method is translated to a database-specific function or expression.
/// The support for this function depends on the database and provider being used.
/// Refer to your database provider's documentation for detailed support information.
/// </para>
/// <para>
/// For more details, see <see href="https://learn.microsoft.com/en-us/ef/core/providers">EF Core database providers</see>.
/// </para>
/// </remarks>
/// <param name="_">The <see cref="DbFunctions"/> instance.</param>
/// <param name="expression">The JSON string or column containing JSON text.</param>
/// <param name="path">The JSON path to check for existence.</param>
/// <returns>
/// A nullable boolean value, <see langword="true"/> if the JSON path exists, <see langword="false"/> if not, and <see langword="null"/>
/// when the JSON string is null.
/// </returns>
public static bool? JsonExists(
this DbFunctions _,
object expression,
[NotParameterized] string path)
=> throw new InvalidOperationException(CoreStrings.FunctionOnClient(nameof(JsonExists)));
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ public SqlServerMethodCallTranslatorProvider(
new SqlServerFullTextSearchFunctionsTranslator(sqlExpressionFactory),
new SqlServerIsDateFunctionTranslator(sqlExpressionFactory),
new SqlServerIsNumericFunctionTranslator(sqlExpressionFactory),
new SqlServerJsonFunctionsTranslator(sqlExpressionFactory, sqlServerSingletonOptions),
new SqlServerMathTranslator(sqlExpressionFactory),
new SqlServerNewGuidTranslator(sqlExpressionFactory),
new SqlServerObjectToStringTranslator(sqlExpressionFactory, typeMappingSource),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
using Microsoft.EntityFrameworkCore.SqlServer.Infrastructure.Internal;
using Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal;

// ReSharper disable once CheckNamespace
namespace Microsoft.EntityFrameworkCore.SqlServer.Query.Internal;

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public class SqlServerJsonFunctionsTranslator : IMethodCallTranslator
{
private static readonly MethodInfo JsonExistsMethodInfo = typeof(RelationalDbFunctionsExtensions)
.GetRuntimeMethod(nameof(RelationalDbFunctionsExtensions.JsonExists), [typeof(DbFunctions), typeof(object), typeof(string)])!;

private readonly ISqlExpressionFactory _sqlExpressionFactory;
private readonly ISqlServerSingletonOptions _sqlServerSingletonOptions;

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public SqlServerJsonFunctionsTranslator(ISqlExpressionFactory sqlExpressionFactory, ISqlServerSingletonOptions sqlServerSingletonOptions)
{
_sqlExpressionFactory = sqlExpressionFactory;
_sqlServerSingletonOptions = sqlServerSingletonOptions;
}

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual SqlExpression? Translate(
SqlExpression? instance,
MethodInfo method,
IReadOnlyList<SqlExpression> arguments,
IDiagnosticsLogger<DbLoggerCategory.Query> logger)
{
if (JsonExistsMethodInfo.Equals(method)
&& (arguments[1].Type.Equals(typeof(string)) || arguments[1].TypeMapping is SqlServerOwnedJsonTypeMapping or StringTypeMapping)
&& _sqlServerSingletonOptions.EngineType == SqlServerEngineType.SqlServer
&& _sqlServerSingletonOptions.SqlServerCompatibilityLevel >= 160)
{
return _sqlExpressionFactory.Function(
"JSON_PATH_EXISTS",
[arguments[1], arguments[2]],
nullable: true,
argumentsPropagateNullability: Statics.TrueArrays[2],
typeof(bool));
}

return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public SqliteMethodCallTranslatorProvider(RelationalMethodCallTranslatorProvider
new SqliteDateTimeMethodTranslator(sqlExpressionFactory),
new SqliteGlobMethodTranslator(sqlExpressionFactory),
new SqliteHexMethodTranslator(sqlExpressionFactory),
new SqliteJsonFunctionsTranslator(sqlExpressionFactory),
new SqliteMathTranslator(sqlExpressionFactory),
new SqliteObjectToStringTranslator(sqlExpressionFactory),
new SqliteRandomTranslator(sqlExpressionFactory),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
using Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal;

// ReSharper disable once CheckNamespace
namespace Microsoft.EntityFrameworkCore.Sqlite.Query.Internal;

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public class SqliteJsonFunctionsTranslator : IMethodCallTranslator
{
private static readonly MethodInfo JsonExistsMethodInfo = typeof(RelationalDbFunctionsExtensions)
.GetRuntimeMethod(nameof(RelationalDbFunctionsExtensions.JsonExists), [typeof(DbFunctions), typeof(object), typeof(string)])!;

private readonly ISqlExpressionFactory _sqlExpressionFactory;

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public SqliteJsonFunctionsTranslator(ISqlExpressionFactory sqlExpressionFactory)
{
_sqlExpressionFactory = sqlExpressionFactory;
}

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual SqlExpression? Translate(
SqlExpression? instance,
MethodInfo method,
IReadOnlyList<SqlExpression> arguments,
IDiagnosticsLogger<DbLoggerCategory.Query> logger)
{
if (JsonExistsMethodInfo.Equals(method)
&& (arguments[1].Type.Equals(typeof(string)) || (arguments[1].TypeMapping is SqliteJsonTypeMapping or StringTypeMapping)))
{
return _sqlExpressionFactory.Case(
[new CaseWhenClause(
_sqlExpressionFactory.IsNotNull(arguments[1]),
_sqlExpressionFactory.IsNotNull(
_sqlExpressionFactory.Function("JSON_TYPE",
[arguments[1], arguments[2]],
nullable: true,
argumentsPropagateNullability: Statics.FalseArrays[2],
returnType: typeof(string))))
],
null);
}

return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Text.Json;
using Microsoft.EntityFrameworkCore.TestModels.JsonQuery;

namespace Microsoft.EntityFrameworkCore.Query;

public abstract class JsonQueryDbFunctionsRelationalTestBase<TFixture>(TFixture fixture) : QueryTestBase<TFixture>(fixture)
where TFixture : JsonQueryRelationalFixture, new()
{
[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual Task JsonExists_With_ConstantValue(bool async)
=> AssertQuery(
async,
ss => ss.Set<JsonEntityBasic>().Where(x => EF.Functions.JsonExists("{\"Name\": \"Test\"}", "$.Name") == true),
ss => ss.Set<JsonEntityBasic>());

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual Task JsonExists_With_StringJsonProperty(bool async)
=> AssertQuery(
async,
ss => ss.Set<JsonEntityStringConversion>().Where(x => EF.Functions.JsonExists(x.StringJsonValue, "$.Name") == true),
ss => ss.Set<JsonEntityStringConversion>().Where(x => HasJsonProperty(x.StringJsonValue, "Name") == true));

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual Task JsonExists_With_StringConversionJsonProperty(bool async)
=> AssertQuery(
async,
ss => ss.Set<JsonEntityStringConversion>().Where(x => EF.Functions.JsonExists(x.ReferenceRoot, "$.Name") == true),
ss => ss.Set<JsonEntityStringConversion>());

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual Task JsonExists_With_OwnedJsonProperty(bool async)
=> AssertQuery(
async,
ss => ss.Set<JsonEntityBasic>().Where(x => EF.Functions.JsonExists(x.OwnedReferenceRoot, "$.Name") == true),
ss => ss.Set<JsonEntityBasic>());

private static bool? HasJsonProperty(string jsonString, string propertyName)
{
if (jsonString is null)
return null;

try
{
using var document = JsonDocument.Parse(jsonString);
return document.RootElement.TryGetProperty(propertyName, out _);
}
catch (JsonException)
{
return false;
}
}
}
51 changes: 51 additions & 0 deletions test/EFCore.Specification.Tests/Query/JsonQueryFixtureBase.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Text.Json;
using Microsoft.EntityFrameworkCore.TestModels.JsonQuery;

namespace Microsoft.EntityFrameworkCore.Query;
Expand All @@ -23,6 +24,7 @@ public virtual ISetSource GetExpectedData()
{ typeof(JsonEntityBasic), e => ((JsonEntityBasic)e)?.Id },
{ typeof(JsonEntityBasicForReference), e => ((JsonEntityBasicForReference)e)?.Id },
{ typeof(JsonEntityBasicForCollection), e => ((JsonEntityBasicForCollection)e)?.Id },
{ typeof(JsonEntityStringConversion), e => ((JsonEntityStringConversion)e)?.Id },
{ typeof(JsonEntityCustomNaming), e => ((JsonEntityCustomNaming)e)?.Id },
{ typeof(JsonEntitySingleOwned), e => ((JsonEntitySingleOwned)e)?.Id },
{ typeof(JsonEntityInheritanceBase), e => ((JsonEntityInheritanceBase)e)?.Id },
Expand Down Expand Up @@ -137,6 +139,29 @@ public virtual ISetSource GetExpectedData()
}
}
},
{
typeof(JsonEntityStringConversion), (e, a) =>
{
Assert.Equal(e == null, a == null);
if (a != null)
{
var ee = (JsonEntityStringConversion)e;
var aa = (JsonEntityStringConversion)a;

Assert.Equal(ee.Id, aa.Id);
Assert.Equal(ee.Name, aa.Name);
Assert.Equal(ee.StringJsonValue, aa.StringJsonValue);

AssertJsonStringConversionRoot(ee.ReferenceRoot, aa.ReferenceRoot);

Assert.Equal(ee.CollectionRoot.Count, aa.CollectionRoot.Count);
for (var i = 0; i < ee.CollectionRoot.Count; i++)
{
AssertJsonStringConversionRoot(ee.CollectionRoot[i], aa.CollectionRoot[i]);
}
}
}
},
{
typeof(JsonEntityCustomNaming), (e, a) =>
{
Expand Down Expand Up @@ -354,6 +379,15 @@ public static void AssertOwnedBranch(JsonOwnedBranch expected, JsonOwnedBranch a
public static void AssertOwnedLeaf(JsonOwnedLeaf expected, JsonOwnedLeaf actual)
=> Assert.Equal(expected.SomethingSomething, actual.SomethingSomething);


public static void AssertJsonStringConversionRoot(JsonStringConversionRoot expected, JsonStringConversionRoot actual)
{
Assert.Equal(expected.Name, actual.Name);
Assert.Equal(expected.Names, actual.Names);
Assert.Equal(expected.Number, actual.Number);
Assert.Equal(expected.Numbers, actual.Numbers);
}

public static void AssertCustomNameRoot(JsonOwnedCustomNameRoot expected, JsonOwnedCustomNameRoot actual)
{
Assert.Equal(expected.Name, actual.Name);
Expand Down Expand Up @@ -506,6 +540,14 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con
});
});


modelBuilder.Ignore<JsonStringConversionRoot>();
modelBuilder.Entity<JsonEntityStringConversion>().Property(x => x.Id).ValueGeneratedNever();
modelBuilder.Entity<JsonEntityStringConversion>().Property(x => x.ReferenceRoot)
.HasConversion(new JsonValueConverter<JsonStringConversionRoot>());
modelBuilder.Entity<JsonEntityStringConversion>().Property(x => x.CollectionRoot)
.HasConversion(new JsonValueConverter<List<JsonStringConversionRoot>>(), new GenaricListComparer<JsonStringConversionRoot>());

modelBuilder.Entity<JsonEntityCustomNaming>().Property(x => x.Id).ValueGeneratedNever();
modelBuilder.Entity<JsonEntityCustomNaming>().OwnsOne(
x => x.OwnedReferenceRoot, b =>
Expand Down Expand Up @@ -664,4 +706,13 @@ public override JsonQueryContext CreateContext()

protected override async Task SeedAsync(JsonQueryContext context)
=> await JsonQueryContext.SeedAsync(context);

protected class JsonValueConverter<T>() : ValueConverter<T, string>(
v => JsonSerializer.Serialize(v, (JsonSerializerOptions)null),
v => JsonSerializer.Deserialize<T>(v, (JsonSerializerOptions)null));

protected class GenaricListComparer<T>() : ValueComparer<List<T>>(
(c1, c2) => (c1 == null && c2 == null) || (c1 != null && c2 != null && c1.SequenceEqual(c2)),
c => c == null ? 0 : c.Aggregate(0, (a, v) => HashCode.Combine(a, v.GetHashCode())),
c => c == null ? null : c.ToList());
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.EntityFrameworkCore.TestModels.JsonQuery;

#nullable disable

public class JsonEntityStringConversion
{
public int Id { get; set; }
public string Name { get; set; }

public string StringJsonValue { get; set; }

public JsonStringConversionRoot ReferenceRoot { get; set; }
public List<JsonStringConversionRoot> CollectionRoot { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ public class JsonQueryContext(DbContextOptions options) : DbContext(options)
public DbSet<JsonEntityBasic> JsonEntitiesBasic { get; set; }
public DbSet<JsonEntityBasicForReference> JsonEntitiesBasicForReference { get; set; }
public DbSet<JsonEntityBasicForCollection> JsonEntitiesBasicForCollection { get; set; }
public DbSet<JsonEntityStringConversion> JsonEntitiesStringConversion { get; set; }
public DbSet<JsonEntityCustomNaming> JsonEntitiesCustomNaming { get; set; }
public DbSet<JsonEntitySingleOwned> JsonEntitiesSingleOwned { get; set; }
public DbSet<JsonEntityInheritanceBase> JsonEntitiesInheritance { get; set; }
Expand All @@ -25,6 +26,7 @@ public static Task SeedAsync(JsonQueryContext context)
var jsonEntitiesBasicForCollection = JsonQueryData.CreateJsonEntitiesBasicForCollection();
JsonQueryData.WireUp(jsonEntitiesBasic, entitiesBasic, jsonEntitiesBasicForReference, jsonEntitiesBasicForCollection);

var jsonEntitiesStringConversion = JsonQueryData.CreateJsonEntitiesStringConversion();
var jsonEntitiesCustomNaming = JsonQueryData.CreateJsonEntitiesCustomNaming();
var jsonEntitiesSingleOwned = JsonQueryData.CreateJsonEntitiesSingleOwned();
var jsonEntitiesInheritance = JsonQueryData.CreateJsonEntitiesInheritance();
Expand All @@ -35,6 +37,7 @@ public static Task SeedAsync(JsonQueryContext context)
context.EntitiesBasic.AddRange(entitiesBasic);
context.JsonEntitiesBasicForReference.AddRange(jsonEntitiesBasicForReference);
context.JsonEntitiesBasicForCollection.AddRange(jsonEntitiesBasicForCollection);
context.JsonEntitiesStringConversion.AddRange(jsonEntitiesStringConversion);
context.JsonEntitiesCustomNaming.AddRange(jsonEntitiesCustomNaming);
context.JsonEntitiesSingleOwned.AddRange(jsonEntitiesSingleOwned);
context.JsonEntitiesInheritance.AddRange(jsonEntitiesInheritance);
Expand Down
Loading
Loading