private SqlBinaryExpression MakeStartsWithExpressionImpl(
     SqlExpression target,
     SqlExpression prefix,
     SqlExpression originalPrefix = null)
 {
     // BUG: EF Core #17389 will lead to a System.NullReferenceException, if SqlExpressionFactory.Like()
     //      is being called with match and pattern as two expressions, that have not been applied a
     //      TypeMapping yet and no escapeChar (null).
     //      As a workaround, apply/infer the type mapping for the match expression manually for now.
     return(_sqlExpressionFactory.AndAlso(
                _sqlExpressionFactory.Like(
                    target,
                    _sqlExpressionFactory.ApplyDefaultTypeMapping(_sqlExpressionFactory.Function(
                                                                      "CONCAT",
                                                                      // when performing the like it is preferable to use the untransformed prefix
                                                                      // value to ensure the index can be used
                                                                      new[] { originalPrefix ?? prefix, _sqlExpressionFactory.Constant("%") },
                                                                      typeof(string)))),
                _sqlExpressionFactory.Equal(
                    _sqlExpressionFactory.Function(
                        "LEFT",
                        new[]
     {
         target,
         CharLength(prefix)
     },
                        typeof(string)),
                    prefix
                    )));
 }
        public virtual SqlExpression Translate(SqlExpression instance, MethodInfo method, IReadOnlyList <SqlExpression> arguments)
        {
            if (method.DeclaringType != typeof(JsonElement) ||
                !(instance.TypeMapping is MySqlJsonTypeMapping mapping))
            {
                return(null);
            }

            // The root of the JSON expression is a ColumnExpression. We wrap that with an empty traversal
            // expression (col->'$'); subsequent traversals will gradually append the path into that.
            // Note that it's possible to call methods such as GetString() directly on the root, and the
            // empty traversal is necessary to properly convert it to a text.
            instance = instance is ColumnExpression columnExpression
                ? _sqlExpressionFactory.JsonTraversal(
                columnExpression, returnsText : false, typeof(string), mapping)
                : instance;

            if (method == _getProperty)
            {
                return(instance is MySqlJsonTraversalExpression prevPathTraversal
                    ? prevPathTraversal.Append(
                           ApplyPathLocationTypeMapping(arguments[0]),
                           typeof(JsonElement),
                           _typeMappingSource.FindMapping(typeof(JsonElement)))
                    : null);
            }

            if (method == _arrayIndexer)
            {
                return(instance is MySqlJsonTraversalExpression prevPathTraversal
                    ? prevPathTraversal.Append(
                           _sqlExpressionFactory.JsonArrayIndex(ApplyPathLocationTypeMapping(arguments[0])),
                           typeof(JsonElement),
                           _typeMappingSource.FindMapping(typeof(JsonElement)))
                    : null);
            }

            if (_getMethods.Contains(method.Name) &&
                arguments.Count == 0 &&
                instance is MySqlJsonTraversalExpression traversal)
            {
                return(ConvertFromJsonExtract(
                           traversal.Clone(
                               method.Name == nameof(JsonElement.GetString),
                               method.ReturnType,
                               _typeMappingSource.FindMapping(method.ReturnType)
                               ),
                           method.ReturnType));
            }

            if (method == _getArrayLength)
            {
                return(_sqlExpressionFactory.Function(
                           "JSON_LENGTH",
                           new[] { instance },
                           typeof(int)));
            }

            if (method.Name.StartsWith("TryGet") && arguments.Count == 0)
            {
                throw new InvalidOperationException($"The TryGet* methods on {nameof(JsonElement)} aren't translated yet, use Get* instead.'");
            }

            return(null);
        }
        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)
                       // CHECK: Either just not doing this it 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.Function(
                    "JSON_TYPE",
                    new[] { json(args[0]) },
                    typeof(string)),
                nameof(MySqlJsonDbFunctionsExtensions.JsonQuote)
                => _sqlExpressionFactory.Function(
                    "JSON_QUOTE",
                    new[] { args[0] },
                    method.ReturnType),
                nameof(MySqlJsonDbFunctionsExtensions.JsonUnquote)
                => _sqlExpressionFactory.Function(
                    "JSON_UNQUOTE",
                    new[] { args[0] },
                    method.ReturnType),
                nameof(MySqlJsonDbFunctionsExtensions.JsonExtract)
                => _sqlExpressionFactory.Function(
                    "JSON_EXTRACT",
                    Array.Empty <SqlExpression>()
                    .Append(json(args[0]))
                    .Concat(deconstructParamsArray(args[1])),
                    method.ReturnType,
                    _sqlExpressionFactory.FindMapping(method.ReturnType, "json")),
                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(ensureJson(e), _sqlExpressionFactory.FindMapping(e.Type, "json"));
        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"));
Ejemplo n.º 5
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public SqlExpression Translate(SqlExpression instance, MethodInfo method, IReadOnlyList <SqlExpression> arguments)
        {
            if (_likeMethodInfos.Any(m => Equals(method, m)))
            {
                var match = _sqlExpressionFactory.ApplyDefaultTypeMapping(arguments[1]);

                var pattern = InferStringTypeMappingOrApplyDefault(
                    arguments[2],
                    match.TypeMapping);

                var excapeChar = arguments.Count == 4
                    ? InferStringTypeMappingOrApplyDefault(
                    arguments[3],
                    match.TypeMapping)
                    : null;

                return(_sqlExpressionFactory.Like(
                           match,
                           pattern,
                           excapeChar));
            }

            if (Equals(method, _matchMethodInfo))
            {
                if (arguments[3] is SqlConstantExpression constant)
                {
                    return(_sqlExpressionFactory.MakeMatch(
                               arguments[1],
                               arguments[2],
                               (MySqlMatchSearchMode)constant.Value));
                }

                if (arguments[3] is SqlParameterExpression parameter)
                {
                    // Use nested OR clauses here, because MariaDB does not support MATCH...AGAINST from inside of
                    // CASE statements and the nested OR clauses use the fulltext index, while using CASE does not:
                    // <search_mode_1> = @p AND MATCH ... AGAINST ... OR
                    // <search_mode_2> = @p AND MATCH ... AGAINST ... OR [...]
                    var andClauses = Enum.GetValues(typeof(MySqlMatchSearchMode))
                                     .Cast <MySqlMatchSearchMode>()
                                     .OrderByDescending(m => m)
                                     .Select(m => _sqlExpressionFactory.AndAlso(
                                                 _sqlExpressionFactory.Equal(parameter, _sqlExpressionFactory.Constant(m)),
                                                 _sqlExpressionFactory.MakeMatch(arguments[1], arguments[2], m)))
                                     .ToArray();

                    return(andClauses
                           .Skip(1)
                           .Aggregate(
                               andClauses.First(),
                               (currentAnd, previousExpression) => _sqlExpressionFactory.OrElse(previousExpression, currentAnd)));
                }
            }

            if (_hexMethodInfos.Any(m => Equals(method, m)))
            {
                return(_sqlExpressionFactory.Function(
                           "HEX",
                           new[] { arguments[1] },
                           typeof(string)));
            }

            if (method == _unhexMethodInfo)
            {
                return(_sqlExpressionFactory.Function(
                           "UNHEX",
                           new[] { arguments[1] },
                           typeof(string)));
            }

            return(null);
        }
Ejemplo n.º 6
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public SqlExpression Translate(SqlExpression instance, MethodInfo method, IReadOnlyList <SqlExpression> arguments)
        {
            if (Equals(method, _spatialDistancePlanarMethodInfo))
            {
                // MySQL 8 uses the Andoyer algorithm by default for `ST_Distance()`, if an SRID of 4326 has been
                // associated with the geometry.
                // Since this call explicitly asked for a planar distance calculation, we need to ensure that
                // MySQL actually does that.
                // MariaDB ignores SRIDs and always calculates the planar distance.
                // CHECK: It could be faster to just manually apply the Pythagoras Theorem instead of changing the
                //        SRID in the case where ST_SRID() does not support a second parameter yet (see
                //        SetSrid()).
                if (_options.ServerVersion.SupportsSpatialSupportFunctionAdditions &&
                    _options.ServerVersion.SupportsSpatialDistanceFunctionImplementsAndoyer)
                {
                    return(_sqlExpressionFactory.Case(
                               new[]
                    {
                        new CaseWhenClause(
                            _sqlExpressionFactory.Equal(
                                _sqlExpressionFactory.Function(
                                    "ST_SRID",
                                    new[] { arguments[1] },
                                    typeof(int)),
                                _sqlExpressionFactory.Constant(0)),
                            GetStDistanceFunctionCall(
                                arguments[1],
                                arguments[2],
                                method.ReturnType,
                                _sqlExpressionFactory.FindMapping(method.ReturnType),
                                _sqlExpressionFactory))
                    },
                               GetStDistanceFunctionCall(
                                   SetSrid(arguments[1], 0, _sqlExpressionFactory, _options),
                                   SetSrid(arguments[2], 0, _sqlExpressionFactory, _options),
                                   method.ReturnType,
                                   _sqlExpressionFactory.FindMapping(method.ReturnType),
                                   _sqlExpressionFactory)));
                }

                return(GetStDistanceFunctionCall(
                           arguments[1],
                           arguments[2],
                           method.ReturnType,
                           _sqlExpressionFactory.FindMapping(method.ReturnType),
                           _sqlExpressionFactory));
            }

            if (Equals(method, _spatialDistanceSphere))
            {
                if (!(arguments[3] is SqlConstantExpression algorithm))
                {
                    throw new InvalidOperationException("The 'algorithm' parameter must be supplied as a constant.");
                }

                return(GetStDistanceSphereFunctionCall(
                           arguments[1],
                           arguments[2],
                           (SpatialDistanceAlgorithm)algorithm.Value,
                           method.ReturnType,
                           _sqlExpressionFactory.FindMapping(method.ReturnType),
                           _sqlExpressionFactory,
                           _options));
            }

            return(null);
        }
        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.Function(
                           startsWith
                        ? "LEFT"
                        : "RIGHT",
                           new[] { targetTransform(target), CharLength(prefixSuffix) },
                           typeof(string),
                           stringTypeMapping),
                       prefixSuffixTransform(prefixSuffix)));
        }