private SqlExpression InferStringTypeMappingOrApplyDefault(SqlExpression expression, RelationalTypeMapping inferenceSourceTypeMapping) { if (expression == null) { return(null); } if (expression.TypeMapping != null) { return(expression); } if (expression.Type == typeof(string) && inferenceSourceTypeMapping?.ClrType == typeof(string)) { return(_sqlExpressionFactory.ApplyTypeMapping(expression, inferenceSourceTypeMapping)); } return(_sqlExpressionFactory.ApplyDefaultTypeMapping(expression)); }
public virtual SqlExpression Translate( SqlExpression instance, MethodInfo method, IReadOnlyList <SqlExpression> arguments, IDiagnosticsLogger <DbLoggerCategory.Query> logger) { if (method.DeclaringType != typeof(MySqlJsonDbFunctionsExtensions)) { return(null); } var args = arguments // Skip useless DbFunctions instance .Skip(1) // JSON extensions accept object parameters for JSON, since they must be able to handle POCOs, strings or DOM types. // This means they come wrapped in a convert node, which we need to remove. // Convert nodes may also come from wrapping JsonTraversalExpressions generated through POCO traversal. .Select(RemoveConvert) // CHECK: Either just not doing this at all is fine, or not applying it to JsonQuote and JsonUnquote // (as already implemented below) is needed. An alternative would be to move the check into the local // json() function. // // If a function is invoked over a JSON traversal expression, that expression may come with // returnText: true (i.e. operator ->> and not ->). Since the functions below require a json object and // not text, we transform it. // .Select( // a => a is MySqlJsonTraversalExpression traversal && // method.Name != nameof(MySqlJsonDbFunctionsExtensions.JsonQuote) && // method.Name != nameof(MySqlJsonDbFunctionsExtensions.JsonUnquote) // ? withReturnsText(traversal, false) // : a) .ToArray(); var result = method.Name switch { nameof(MySqlJsonDbFunctionsExtensions.AsJson) => _sqlExpressionFactory.ApplyTypeMapping( args[0], _sqlExpressionFactory.FindMapping(method.ReturnType, "json")), nameof(MySqlJsonDbFunctionsExtensions.JsonType) => _sqlExpressionFactory.NullableFunction( "JSON_TYPE", new[] { Json(args[0]) }, typeof(string)), nameof(MySqlJsonDbFunctionsExtensions.JsonQuote) => _sqlExpressionFactory.NullableFunction( "JSON_QUOTE", new[] { args[0] }, method.ReturnType), nameof(MySqlJsonDbFunctionsExtensions.JsonUnquote) => _sqlExpressionFactory.NullableFunction( "JSON_UNQUOTE", new[] { args[0] }, method.ReturnType), nameof(MySqlJsonDbFunctionsExtensions.JsonExtract) => _sqlExpressionFactory.NullableFunction( "JSON_EXTRACT", Array.Empty <SqlExpression>() .Append(Json(args[0])) .Concat(DeconstructParamsArray(args[1])), method.ReturnType, _sqlExpressionFactory.FindMapping(method.ReturnType, "json"), false), nameof(MySqlJsonDbFunctionsExtensions.JsonContains) => _sqlExpressionFactory.NullableFunction( "JSON_CONTAINS", args.Length >= 3 ? new[] { Json(args[0]), args[1], args[2] } : new[] { Json(args[0]), args[1] }, typeof(bool)), nameof(MySqlJsonDbFunctionsExtensions.JsonContainsPath) => _sqlExpressionFactory.NullableFunction( "JSON_CONTAINS_PATH", new[] { Json(args[0]), _sqlExpressionFactory.Constant("one"), args[1] }, typeof(bool)), nameof(MySqlJsonDbFunctionsExtensions.JsonContainsPathAny) => _sqlExpressionFactory.NullableFunction( "JSON_CONTAINS_PATH", Array.Empty <SqlExpression>() .Append(Json(args[0])) .Append(_sqlExpressionFactory.Constant("one")) .Concat(DeconstructParamsArray(args[1])), typeof(bool)), nameof(MySqlJsonDbFunctionsExtensions.JsonContainsPathAll) => _sqlExpressionFactory.NullableFunction( "JSON_CONTAINS_PATH", Array.Empty <SqlExpression>() .Append(Json(args[0])) .Append(_sqlExpressionFactory.Constant("all")) .Concat(DeconstructParamsArray(args[1])), typeof(bool)), nameof(MySqlJsonDbFunctionsExtensions.JsonSearchAny) => _sqlExpressionFactory.IsNotNull( _sqlExpressionFactory.NullableFunction( "JSON_SEARCH", Array.Empty <SqlExpression>() .Append(Json(args[0])) .Append(_sqlExpressionFactory.Constant("one")) .Append(args[1]) .AppendIfTrue( args.Length >= 3, () => args.Length >= 4 ? args[3] : _sqlExpressionFactory.Constant(null, RelationalTypeMapping.NullMapping)) .AppendIfTrue(args.Length >= 3, () => args[2]), typeof(bool), null, false)), // JSON_SEARCH can return null even if all arguments are not null _ => null }; return(result); SqlExpression Json(SqlExpression e) => _sqlExpressionFactory.ApplyTypeMapping(EnsureJson(e), _sqlExpressionFactory.FindMapping(e.Type, "json"));
private SqlExpression MakeStartsWithEndsWithExpressionImpl( SqlExpression target, [NotNull] Func <SqlExpression, SqlExpression> targetTransform, SqlExpression prefixSuffix, [NotNull] Func <SqlExpression, SqlExpression> prefixSuffixTransform, bool startsWith) { var stringTypeMapping = ExpressionExtensions.InferTypeMapping(target, prefixSuffix); target = _sqlExpressionFactory.ApplyTypeMapping(target, stringTypeMapping); prefixSuffix = _sqlExpressionFactory.ApplyTypeMapping(prefixSuffix, stringTypeMapping); if (prefixSuffix is SqlConstantExpression constantPrefixSuffixExpression) { // The prefix is constant. Aside from null or empty, we escape all special characters (%, _, \) // in C# and send a simple LIKE. if (constantPrefixSuffixExpression.Value is string constantPrefixSuffixString) { // TRUE (pattern == "") // something LIKE 'foo%' (pattern != "", StartsWith()) // something LIKE '%foo' (pattern != "", EndsWith()) return(constantPrefixSuffixString == string.Empty ? (SqlExpression)_sqlExpressionFactory.Constant(true) : _sqlExpressionFactory.Like( targetTransform(target), prefixSuffixTransform( _sqlExpressionFactory.Constant( (startsWith ? string.Empty : "%") + EscapeLikePattern(constantPrefixSuffixString) + (startsWith ? "%" : string.Empty))))); } // https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql/issues/996#issuecomment-607876040 // Can return NULL in .NET 5 after https://github.com/dotnet/efcore/issues/20498 has been fixed. // `something LIKE NULL` always returns `NULL`. We will return `false`, to indicate, that no match // could be found, because returning a constant of `NULL` will throw later in EF Core when used as // a predicate. // return _sqlExpressionFactory.Constant(null, RelationalTypeMapping.NullMapping); // This results in NULL anyway, but works around EF Core's inability to handle predicates that are // constant null values. return(_sqlExpressionFactory.Like(target, _sqlExpressionFactory.Constant(null, stringTypeMapping))); } // TODO: Generally, LEFT & compare is faster than escaping potential pattern characters with REPLACE(). // However, this might not be the case, if the pattern is constant after all (e.g. `LCASE('fo%o')`), in // which case, `something LIKE CONCAT(REPLACE(REPLACE(LCASE('fo%o'), '%', '\\%'), '_', '\\_'), '%')` should // be faster than `LEFT(something, CHAR_LENGTH('fo%o')) = LCASE('fo%o')`. // See https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql/issues/996#issuecomment-607733553 // The prefix is non-constant, we use LEFT to extract the substring and compare. return(_sqlExpressionFactory.Equal( _sqlExpressionFactory.NullableFunction( startsWith ? "LEFT" : "RIGHT", new[] { targetTransform(target), CharLength(prefixSuffix) }, typeof(string), stringTypeMapping), prefixSuffixTransform(prefixSuffix))); }
public virtual SqlExpression Translate(SqlExpression instance, MethodInfo method, IReadOnlyList <SqlExpression> arguments) { if (method.DeclaringType != typeof(MySqlJsonDbFunctionsExtensions)) { return(null); } var args = arguments // Skip useless DbFunctions instance .Skip(1) // JSON extensions accept object parameters for JSON, since they must be able to handle POCOs, strings or DOM types. // This means they come wrapped in a convert node, which we need to remove. // Convert nodes may also come from wrapping JsonTraversalExpressions generated through POCO traversal. .Select(removeConvert) // If a function is invoked over a JSON traversal expression, that expression may come with // returnText: true (i.e. operator ->> and not ->). Since the functions below require a json object and // not text, we transform it. .Select(a => a is MySqlJsonTraversalExpression traversal ? withReturnsText(traversal, false) : a) .ToArray(); if (!args.Any(a => a.TypeMapping is MySqlJsonTypeMapping || a is MySqlJsonTraversalExpression)) { throw new InvalidOperationException("The EF JSON methods require a JSON parameter but none was found."); } var result = method.Name switch { nameof(MySqlJsonDbFunctionsExtensions.JsonType) => _sqlExpressionFactory.Function( "JSON_TYPE", new[] { args[0] }, typeof(string)), nameof(MySqlJsonDbFunctionsExtensions.JsonContains) => _sqlExpressionFactory.Function( "JSON_CONTAINS", args.Length >= 3 ? new[] { json(args[0]), args[1], args[2] } : new[] { json(args[0]), args[1] }, typeof(bool)), nameof(MySqlJsonDbFunctionsExtensions.JsonContainsPath) => _sqlExpressionFactory.Function( "JSON_CONTAINS_PATH", new[] { json(args[0]), _sqlExpressionFactory.Constant("one"), args[1] }, typeof(bool)), nameof(MySqlJsonDbFunctionsExtensions.JsonContainsPathAny) => _sqlExpressionFactory.Function( "JSON_CONTAINS_PATH", Array.Empty <SqlExpression>() .Append(json(args[0])) .Append(_sqlExpressionFactory.Constant("one")) .Concat(deconstructParamsArray(args[1])), typeof(bool)), nameof(MySqlJsonDbFunctionsExtensions.JsonContainsPathAll) => _sqlExpressionFactory.Function( "JSON_CONTAINS_PATH", Array.Empty <SqlExpression>() .Append(json(args[0])) .Append(_sqlExpressionFactory.Constant("all")) .Concat(deconstructParamsArray(args[1])), typeof(bool)), nameof(MySqlJsonDbFunctionsExtensions.JsonSearchAny) => _sqlExpressionFactory.IsNotNull( _sqlExpressionFactory.Function( "JSON_SEARCH", Array.Empty <SqlExpression>() .Append(json(args[0])) .Append(_sqlExpressionFactory.Constant("one")) .Append(args[1]) .AppendIfTrue(args.Length >= 3, () => args.Length >= 4 ? args[3] : _sqlExpressionFactory.Constant(null, RelationalTypeMapping.NullMapping)) .AppendIfTrue(args.Length >= 3, () => args[2]), typeof(bool))), nameof(MySqlJsonDbFunctionsExtensions.JsonSearchAll) => _sqlExpressionFactory.IsNotNull( _sqlExpressionFactory.Function( "JSON_SEARCH", Array.Empty <SqlExpression>() .Append(json(args[0])) .Append(_sqlExpressionFactory.Constant("all")) .Append(args[1]) .AppendIfTrue(args.Length >= 3, () => args.Length >= 4 ? args[3] : _sqlExpressionFactory.Constant(null, RelationalTypeMapping.NullMapping)) .AppendIfTrue(args.Length >= 3, () => args[2]), typeof(bool))) as SqlExpression, _ => null }; return(result); SqlExpression json(SqlExpression e) => _sqlExpressionFactory.ApplyTypeMapping(e, _sqlExpressionFactory.FindMapping(e.Type, "json"));