protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                base.OnModelCreating(modelBuilder);

                // IsDate is a built-in SQL Server function, that in the base class is mapped as built-in, which means we
                // don't get any quotes. We remap it as non-built-in by including a (null) schema.
                var isDateMethodInfo = typeof(UDFSqlContext).GetMethod(nameof(IsDateStatic));

                modelBuilder.HasDbFunction(isDateMethodInfo)
                .HasTranslation(args => SqlFunctionExpression.Create((string)null, "IsDate", args, isDateMethodInfo.ReturnType, null));
                var isDateMethodInfo2 = typeof(UDFSqlContext).GetMethod(nameof(IsDateInstance));

                modelBuilder.HasDbFunction(isDateMethodInfo2)
                .HasTranslation(args => SqlFunctionExpression.Create((string)null, "IsDate", args, isDateMethodInfo2.ReturnType, null));

                // Base class maps to len(), but in PostgreSQL it's called length()
                var methodInfo = typeof(UDFSqlContext).GetMethod(nameof(MyCustomLengthStatic));

                modelBuilder.HasDbFunction(methodInfo)
                .HasTranslation(args => SqlFunctionExpression.Create("length", args, methodInfo.ReturnType, null));
                var methodInfo2 = typeof(UDFSqlContext).GetMethod(nameof(MyCustomLengthInstance));

                modelBuilder.HasDbFunction(methodInfo2)
                .HasTranslation(args => SqlFunctionExpression.Create("length", args, methodInfo2.ReturnType, null));
            }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //TODO: Map Composite Keys Entities Here
            //TODO: Set the .HasNoKey() to views and stored procedures

            //This lines map a DB funcion so we can call it inside the linq or lambda function that executes a query to the DB
            modelBuilder.HasDbFunction(typeof(SampleDataContextFunctions).GetMethod(nameof(SampleDataContextFunctions.CalcuateAgeInYearsMonths)))
            .HasTranslation(args => SqlFunctionExpression.Create("dbo",
                                                                 "f_CalcuateAgeInYearsMonths",
                                                                 args,
                                                                 typeof(decimal?),
                                                                 null));

            //Disable the cascade delete behavior
            var cascadeFKs = modelBuilder.Model.GetEntityTypes().SelectMany(t => t.GetForeignKeys())
                             .Where(fk => !fk.IsOwnership && fk.DeleteBehavior == DeleteBehavior.Cascade);

            foreach (var fk in cascadeFKs)
            {
                fk.DeleteBehavior = DeleteBehavior.Restrict;
            }


            modelBuilder.Ignore <ExtensionDataObject>();
            base.OnModelCreating(modelBuilder);
        }
Beispiel #3
0
        public void Transform_TwoArguments()
        {
            var method = typeof(StringExtensions).GetMethod(
                "SqlContainsFulltext",
                BindingFlags.Public | BindingFlags.Static,
                null,
                CallingConventions.Any,
                new[] { typeof(string), typeof(string), typeof(string) },
                null);
            var objectExpression = Expression.Constant("Test");
            var argument1        = Expression.Constant("es");
            var language         = Expression.Constant("language");
            var expression       = Expression.Call(method, objectExpression, argument1, language);
            var transformer      = new ContainsFulltextMethodCallTransformer();

            var result = transformer.Transform(expression);

            var argumentExpression = Expression.Constant(string.Format("{0}", argument1.Value));

            var compositeExpression = new SqlCompositeCustomTextGeneratorExpression(
                typeof(string), new SqlCustomTextExpression("LANGUAGE ", typeof(string)), language);

            var expectedResult =
                new SqlFunctionExpression(typeof(bool), "CONTAINS", objectExpression, argumentExpression, compositeExpression);

            SqlExpressionTreeComparer.CheckAreEqualTrees(expectedResult, result);
        }
        public virtual SqlFunctionExpression Function(
            SqlExpression instance,
            string name,
            IEnumerable<SqlExpression> arguments,
            bool nullResultAllowed,
            bool instancePropagatesNullability,
            IEnumerable<bool> argumentsPropagateNullability,
            Type returnType,
            RelationalTypeMapping typeMapping = null)
        {
            Check.NotEmpty(name, nameof(name));
            Check.NotNull(arguments, nameof(arguments));
            Check.NotNull(returnType, nameof(returnType));

            instance = ApplyDefaultTypeMapping(instance);
            var typeMappedArguments = new List<SqlExpression>();
            foreach (var argument in arguments)
            {
                typeMappedArguments.Add(ApplyDefaultTypeMapping(argument));
            }

            return SqlFunctionExpression.Create(
                instance,
                name,
                typeMappedArguments,
                nullResultAllowed,
                instancePropagatesNullability,
                argumentsPropagateNullability,
                returnType,
                typeMapping);
        }
Beispiel #5
0
        /// <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>
        protected override Expression VisitSqlFunction(SqlFunctionExpression sqlFunctionExpression)
        {
            Check.NotNull(sqlFunctionExpression, nameof(sqlFunctionExpression));

            if (!sqlFunctionExpression.IsBuiltIn &&
                string.IsNullOrEmpty(sqlFunctionExpression.Schema))
            {
                sqlFunctionExpression = sqlFunctionExpression.IsNiladic
                    ? new SqlFunctionExpression(
                    schema: "dbo",
                    sqlFunctionExpression.Name,
                    sqlFunctionExpression.IsNullable,
                    sqlFunctionExpression.Type,
                    sqlFunctionExpression.TypeMapping)
                    : new SqlFunctionExpression(
                    schema: "dbo",
                    sqlFunctionExpression.Name,
                    sqlFunctionExpression.Arguments,
                    sqlFunctionExpression.IsNullable,
                    sqlFunctionExpression.ArgumentsPropagateNullability,
                    sqlFunctionExpression.Type,
                    sqlFunctionExpression.TypeMapping);
            }

            return(base.VisitSqlFunction(sqlFunctionExpression));
        }
        public virtual SqlFunctionExpression Function(string name, bool nullResultAllowed, Type returnType, RelationalTypeMapping typeMapping = null)
        {
            Check.NotEmpty(name, nameof(name));
            Check.NotNull(returnType, nameof(returnType));

            return SqlFunctionExpression.CreateNiladic(name, nullResultAllowed, returnType, typeMapping);
        }
Beispiel #7
0
        protected override Expression VisitSqlFunction(SqlFunctionExpression sqlFunctionExpression)
        {
            if (sqlFunctionExpression.IsBuiltIn)
            {
                if (sqlFunctionExpression.Instance != null)
                {
                    Visit(sqlFunctionExpression.Instance);
                    Sql.Append(".");
                }

                Sql.Append(sqlFunctionExpression.Name);
            }
            else
            {
                if (!string.IsNullOrEmpty(sqlFunctionExpression.Schema))
                {
                    Sql
                    .Append(_sqlGenerationHelper.DelimitIdentifier(sqlFunctionExpression.Schema))
                    .Append(".");
                }

                Sql
                .Append(_sqlGenerationHelper.DelimitIdentifier(sqlFunctionExpression.Name));
            }

            if (!sqlFunctionExpression.IsNiladic)
            {
                Sql.Append("(");
                GenerateList(sqlFunctionExpression.Arguments, e => Visit(e));
                Sql.Append(")");
            }

            return(sqlFunctionExpression);
        }
Beispiel #8
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity <TableA>();

            modelBuilder.HasDbFunction(typeof(TestDataBaseContext).GetMethod(nameof(JsonValue)))
            .HasTranslation(args => SqlFunctionExpression.Create("JSON_VALUE", args, typeof(string), null));
        }
Beispiel #9
0
        public override Expression VisitSqlFunction(SqlFunctionExpression sqlFunctionExpression)
        {
            var expr = base.VisitSqlFunction(sqlFunctionExpression);

            // Note that PostgreSQL COUNT(*) is BIGINT (64-bit). For 32-bit Count() expressions we cast.
            if (sqlFunctionExpression.FunctionName == "COUNT" &&
                sqlFunctionExpression.Type == typeof(int))
            {
                Sql.Append("::INT4");
                return(expr);
            }

            // In PostgreSQL SUM() doesn't return the same type as its argument for smallint, int and bigint.
            // Cast to get the same type.
            // http://www.postgresql.org/docs/current/static/functions-aggregate.html
            if (sqlFunctionExpression.FunctionName == "SUM")
            {
                if (sqlFunctionExpression.Type == typeof(int))
                {
                    Sql.Append("::INT4");
                }
                else if (sqlFunctionExpression.Type == typeof(short))
                {
                    Sql.Append("::INT2");
                }
                return(expr);
            }

            return(expr);
        }
Beispiel #10
0
        public static SqlFunctionExpression Function <TRet>(string schema, string name, IEnumerable <SqlExpression> arguments)
        {
            var returnType  = typeof(TRet);
            var typeMapping = GetTypeMapping(returnType);

            return(SqlFunctionExpression.Create(schema, name, arguments, returnType, typeMapping));
        }
Beispiel #11
0
 public override SelectExpression PreviewSelect(SelectExpression select, LockType lockType)
 {
     select = base.PreviewSelect(select, lockType);
     // Use TOP if there's limit, no offset, and there's no order by - to exclude search queries;
     // searches do have OrderBy, and for searches we want to use standard clause with Skip-Offset
     if (select.Limit != null && (select.Offset == null || Linq.LinqExpressionHelper.IsConstZero(select.Offset)) &&
         select.OrderBy.Count == 0)
     {
         select.Flags |= SelectExpressionFlags.MsSqlUseTop;
         // Fake order-by is needed only with full Fetch Next/Offset syntax
         select.Flags &= ~SelectExpressionFlags.NeedsFakeOrderBy;
     }
     // SQL Server does not allow bool values in SELECT list. For ex, the following results in error:
     //   SELECT (book.Price > 10) AS OverPriced, .....
     //  So we need to find output exprs like this and wrap them like:
     //   SELECT IIF(book.Price > 10, 1, 0) AS OverPriced, ...
     for (int i = 0; i < select.Operands.Count; i++)
     {
         var outExpr = select.Operands[i];
         if (outExpr.Type == typeof(bool) && !(outExpr is ColumnExpression))
         {
             var wrappedExpr = new SqlFunctionExpression(SqlFunctionType.Iif, typeof(int),
                                                         outExpr, ExpressionMaker.Const1Int, ExpressionMaker.Const0Int);
             select.Operands[i] = wrappedExpr;
         }
     }
     return(select);
 }
Beispiel #12
0
        public static ModelBuilder UseCustomDbFunctions(this ModelBuilder builder)
        {
            var jsonvalueMethodInfo = typeof(Json)
                                      .GetRuntimeMethod(
                nameof(Json.Value),
                new[] { typeof(string), typeof(string) }
                );

            builder
            .HasDbFunction(jsonvalueMethodInfo)
            .HasTranslation(args =>
                            SqlFunctionExpression.Create("JSON_VALUE",
                                                         args,
                                                         typeof(string),
                                                         null /* guess */
                                                         )
                            );

            var methodInfo =
                typeof(AnswersToTheUniverse)
                .GetRuntimeMethod(nameof(AnswersToTheUniverse.What), new Type[0]);

            builder.HasDbFunction(methodInfo)
            .HasTranslation(args =>
                            SqlFunctionExpression.Create(
                                builder.Model.GetDefaultSchema(),
                                "FortyTwo",
                                args,
                                typeof(int),
                                null /* guess */
                                ));

            return(builder);
        }
Beispiel #13
0
 private Expression CheckSelectOutputColumn(Expression outCol, SelectExpression select)
 {
     // 1. check precision of decimal column
     // Oracle - old well known bug: InvalidCastException retrieving a high precision decimal
     // ex: 'Select 1.0/3', blows up when trying read: value= reader[0]
     // CLR decimal precision is 28 while OracleDecimal is 38, so it just blows up
     // Workaround - round output values
     if (outCol.Type == typeof(decimal))
     {
         var colExpr = outCol as ColumnExpression;
         if (colExpr != null && colExpr.ColumnInfo.Member.Precision <= 27)
         {
             return(outCol); // no need to wrap
         }
         var roundExpr = new SqlFunctionExpression(SqlFunctionType.Round, typeof(decimal), outCol, Expression.Constant(27));
         return(roundExpr);
     }
     // 2. Oracle does not allow bool value as output, so 'SELECT (1 > 0)' would fail.
     //    we need to convert it to 1/0
     if (outCol.Type == typeof(bool) && !(outCol is ColumnExpression))
     {
         // bools are expressed numeric(1)
         var convExpr = new SqlFunctionExpression(SqlFunctionType.ConvertBoolToBit, typeof(decimal), outCol);
         return(convExpr);
     }
     return(outCol);
 }
        public void Transform_WithTwoArgument_TypeString()
        {
            var method           = typeof(string).GetMethod("IndexOf", new[] { typeof(string), typeof(int) });
            var objectExpression = Expression.Constant("Test");

            var argument1   = Expression.Constant("es");
            var argument2   = Expression.Constant(2);
            var expression  = Expression.Call(objectExpression, method, argument1, argument2);
            var transformer = new IndexOfMethodCallTransformer();
            var result      = transformer.Transform(expression);

            var startIndexExpression = Expression.Add(argument2, new SqlLiteralExpression(1));

            var lenArgExpression  = new SqlLengthExpression(argument1);
            var leftTestPredicate = Expression.Equal(lenArgExpression, new SqlLiteralExpression(0));

            var lenObjectExpression = new SqlLengthExpression(objectExpression);
            var rightTestpredicate  = Expression.LessThanOrEqual(startIndexExpression, lenObjectExpression);
            var testPredicate       = Expression.AndAlso(leftTestPredicate, rightTestpredicate);

            var charIndexExpression = new SqlFunctionExpression(
                expression.Type, "CHARINDEX", argument1, objectExpression, startIndexExpression);

            var elseValue = Expression.Subtract(charIndexExpression, new SqlLiteralExpression(1));

            var expectedResult = Expression.Condition(testPredicate, argument2, elseValue);

            SqlExpressionTreeComparer.CheckAreEqualTrees(expectedResult, result);
        }
Beispiel #15
0
        public virtual Expression Translate(MethodCallExpression methodCallExpression)
        {
            ThrowIf.Argument.IsNull(methodCallExpression, nameof(methodCallExpression));

            if (ReferenceEquals(methodCallExpression.Method, _methodInfo))
            {
                var argument = methodCallExpression.Arguments.Count == 1
                                   ? (methodCallExpression.Arguments[0] as ConstantExpression)?.Value as string
                                   : null;


                var sqlArguments = new List <Expression>();
                sqlArguments.Add(ConstantExpression.Constant("%"));
                if (argument != null)
                {
                    sqlArguments.Add(Expression.Constant(argument));
                }
                else
                {
                    sqlArguments.Add(methodCallExpression.Arguments[0]);
                }

                sqlArguments.Add(ConstantExpression.Constant("%"));

                var concatFunctionExpression = new SqlFunctionExpression("concat", methodCallExpression.Type, sqlArguments);
                return(new LikeExpression(
                           methodCallExpression.Object,
                           concatFunctionExpression));
            }
            return(null);
        }
        public virtual SqlFunctionExpression Coalesce(SqlExpression left, SqlExpression right, RelationalTypeMapping typeMapping = null)
        {
            Check.NotNull(left, nameof(left));
            Check.NotNull(right, nameof(right));

            var resultType = right.Type;
            var inferredTypeMapping = typeMapping
                ?? ExpressionExtensions.InferTypeMapping(left, right)
                ?? _typeMappingSource.FindMapping(resultType);

            var typeMappedArguments = new List<SqlExpression>()
            {
                ApplyTypeMapping(left, inferredTypeMapping),
                ApplyTypeMapping(right, inferredTypeMapping)
            };

            return SqlFunctionExpression.Create(
                "COALESCE",
                typeMappedArguments,
                nullResultAllowed: true,
                // COALESCE is handled separately since it's only nullable if *both* arguments are null
                argumentsPropagateNullability: new[] { false, false },
                resultType,
                inferredTypeMapping);
        }
        private static Expression HandleAverage(HandlerContext handlerContext)
        {
            if (!handlerContext.QueryModelVisitor.RequiresClientProjection &&
                handlerContext.SelectExpression.Projection.Count == 1)
            {
                var expression = handlerContext.SelectExpression.Projection.First();

                if (!(expression.RemoveConvert() is SelectExpression))
                {
                    var inputType  = expression.Type;
                    var outputType = expression.Type;

                    var nonNullableInputType = inputType.UnwrapNullableType();
                    if (nonNullableInputType == typeof(int) ||
                        nonNullableInputType == typeof(long))
                    {
                        outputType = inputType.IsNullableType() ? typeof(double?) : typeof(double);
                    }

                    expression = new ExplicitCastExpression(expression, outputType);
                    var averageExpression = new SqlFunctionExpression("AVG", expression.Type, new [] { expression });

                    handlerContext.SelectExpression.SetProjectionExpression(averageExpression);

                    return((Expression)_transformClientExpressionMethodInfo
                           .MakeGenericMethod(averageExpression.Type)
                           .Invoke(null, new object [] { handlerContext }));
                }
            }

            return(handlerContext.EvalOnClient());
        }
Beispiel #18
0
            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                base.OnModelCreating(modelBuilder);

                var isDateMethodInfo = typeof(UDFSqlContext).GetMethod(nameof(IsDateStatic));

                modelBuilder.HasDbFunction(isDateMethodInfo)
                .HasTranslation(args => SqlFunctionExpression.Create((string)null, "IsDate", args, isDateMethodInfo.ReturnType, null));
                var isDateMethodInfo2 = typeof(UDFSqlContext).GetMethod(nameof(IsDateInstance));

                modelBuilder.HasDbFunction(isDateMethodInfo2)
                .HasTranslation(args => SqlFunctionExpression.Create((string)null, "IsDate", args, isDateMethodInfo2.ReturnType, null));

                var methodInfo = typeof(UDFSqlContext).GetMethod(nameof(MyCustomLengthStatic));

                modelBuilder.HasDbFunction(methodInfo)
                .HasTranslation(args => SqlFunctionExpression.Create("char_length", args, methodInfo.ReturnType, null));
                var methodInfo2 = typeof(UDFSqlContext).GetMethod(nameof(MyCustomLengthInstance));

                modelBuilder.HasDbFunction(methodInfo2)
                .HasTranslation(args => SqlFunctionExpression.Create("char_length", args, methodInfo2.ReturnType, null));

                modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(GetCustomerWithMostOrdersAfterDateStatic)))
                .HasName("GetCustWithMostOrdersAfterDate");
                modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(GetCustomerWithMostOrdersAfterDateInstance)))
                .HasName("GetCustWithMostOrdersAfterDate");

                modelBuilder.HasDbFunction(typeof(UDFSqlContext).GetMethod(nameof(IdentityString)))
                .HasSchema(null);
            }
Beispiel #19
0
        public void Transform_AddDays()
        {
            var value      = new CustomExpression(typeof(double));
            var methodInfo = MemberInfoFromExpressionUtility.GetMethod(() => DateTime.Now.AddDays(0.0));
            var expression = Expression.Call(_dateTimeInstance, methodInfo, value);

            var result = _transformer.Transform(expression);

            var expectedResult = new SqlFunctionExpression(
                typeof(DateTime),
                "DATEADD",
                new SqlCustomTextExpression("millisecond", typeof(string)),
                Expression.Modulo(
                    new SqlConvertExpression(typeof(long), Expression.Multiply(value, new SqlLiteralExpression(86400000.0))),
                    new SqlLiteralExpression(86400000L)),
                new SqlFunctionExpression
                (
                    typeof(DateTime),
                    "DATEADD",
                    new SqlCustomTextExpression("day", typeof(string)),
                    Expression.Divide(
                        new SqlConvertExpression(typeof(long), Expression.Multiply(value, new SqlLiteralExpression(86400000.0))),
                        new SqlLiteralExpression(86400000L)),
                    _dateTimeInstance));

            SqlExpressionTreeComparer.CheckAreEqualTrees(expectedResult, result);
        }
Beispiel #20
0
        //public DbSet<DbUnit> Units { get; set; }
        //public DbSet<DbRefinery> Refineries { get; set; }
        //public DbSet<DbUpgrade> Upgrades { get; set; }

        /*
         * protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
         * {
         *  if (String.IsNullOrEmpty(DSdata.ServerConfig.DBConnectionString))
         *      throw new NotSupportedException();
         *
         *  optionsBuilder
         *      //.UseSqlServer(sc2dsstatslib.Config.DBConnectionString)
         *      .UseMySql(DSdata.ServerConfig.DBConnectionString, mySqlOptions => mySqlOptions
         *      .ServerVersion(new ServerVersion(new Version(5, 7, 29), ServerType.MySql)))
         *      //.ServerVersion(new ServerVersion(new Version(8, 0, 17), ServerType.MySql)))
         *      //.UseLoggerFactory(_loggerFactory)
         *      ;
         * }
         */

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder
            .HasDbFunction(typeof(DBFunctions).GetMethod(nameof(DBFunctions.GetOpp)))
            .HasTranslation(args => SqlFunctionExpression.Create("GetOpp", args, typeof(int), null));
            modelBuilder
            .HasDbFunction(typeof(DBFunctions).GetMethod(nameof(DBFunctions.GetPl)))
            .HasTranslation(args => SqlFunctionExpression.Create("GetPl", args, typeof(int), null));

            modelBuilder.Entity <DSReplay>(entity =>
            {
                entity.HasKey(e => e.ID);
                entity.Property(b => b.HASH)
                .HasMaxLength(32)
                .IsFixedLength();
                entity.HasIndex(b => b.HASH);
                //    .IsUnique();
                entity.HasIndex(b => b.REPLAY);
            });

            modelBuilder.Entity <DbMiddle>(entity =>
            {
                entity.HasKey(e => e.ID);
                entity.HasOne(p => p.Replay)
                .WithMany(d => d.Middle);
            });

            modelBuilder.Entity <DSPlayer>(entity =>
            {
                entity.HasKey(e => e.ID);
                entity.Property(p => p.NAME)
                .HasMaxLength(64);
                entity.Property(p => p.RACE)
                .HasMaxLength(64);
                entity.Property(p => p.OPPRACE)
                .HasMaxLength(64);
                entity.HasOne(d => d.DSReplay)
                .WithMany(p => p.DSPlayer);
                entity.HasIndex(b => b.RACE);
                entity.HasIndex(p => new { p.RACE, p.OPPRACE });
            });

            modelBuilder.Entity <DbBreakpoint>(entity =>
            {
                entity.HasKey(p => p.ID);
                entity.HasOne(p => p.Player)
                .WithMany(d => d.Breakpoints);
            });

            modelBuilder.Entity <DSUnit>(entity =>
            {
                entity.HasKey(k => k.ID);
                entity.HasOne(p => p.DSPlayer)
                .WithMany(d => d.DSUnit);
            });
        }
Beispiel #21
0
 public override Expression VisitSqlFunction(SqlFunctionExpression sqlFunctionExpression)
 {
     if (sqlFunctionExpression.FunctionName.StartsWith("@@", StringComparison.Ordinal))
     {
         Sql.Append(sqlFunctionExpression.FunctionName);
         return(sqlFunctionExpression);
     }
     return(base.VisitSqlFunction(sqlFunctionExpression));
 }
Beispiel #22
0
        public void VisitSqlFunctionExpression()
        {
            var sqlFunctionExpression = new SqlFunctionExpression(typeof(int), "LENFUNC", new SqlLiteralExpression("test"), new SqlLiteralExpression(1));

            SqlGeneratingExpressionVisitor.GenerateSql(
                sqlFunctionExpression, _commandBuilder, _stageMock);

            Assert.That(_commandBuilder.GetCommandText(), Is.EqualTo("LENFUNC('test', 1)"));
        }
 public override Expression VisitSqlFunction(SqlFunctionExpression sqlFunctionExpression)
 {
     if (sqlFunctionExpression.FunctionName.StartsWith("@@"))
     {
         Sql.Append(sqlFunctionExpression.FunctionName);
         return(sqlFunctionExpression);
     }
     return(base.VisitSqlFunction(sqlFunctionExpression));
 }
        /// <inheritdoc />
        public override Expression VisitSqlFunction(SqlFunctionExpression sqlFunctionExpression)
        {
            switch (sqlFunctionExpression.FunctionName)
            {
            case "CAST":
            {
                Sql.Append(sqlFunctionExpression.FunctionName);
                Sql.Append("(");

                Visit(sqlFunctionExpression.Arguments[0]);

                Sql.Append(" AS ");

                Visit(sqlFunctionExpression.Arguments[1]);

                Sql.Append(")");

                return(sqlFunctionExpression);
            }

            case "EXTRACT":
            {
                Sql.Append(sqlFunctionExpression.FunctionName);
                Sql.Append("(");

                Visit(sqlFunctionExpression.Arguments[0]);

                Sql.Append(" FROM CAST(");

                Visit(sqlFunctionExpression.Arguments[1]);

                Sql.Append(" AS TIMESTAMP) AT TIME ZONE '+0')");

                return(sqlFunctionExpression);
            }

            case "LN":
            case "LOG":
            case "LOG10":
                //Since spanner does not attempt any short circuit eval,
                //we make these methods return NaN instead of throw
                //Otherwise, where clauses such as WHERE x > 0 AND LN(x) < [foo]
                //will throws because the protection of "x > 0" does not stop LN(0)
                //from being evaluated.
                Sql.Append("IF(");
                Visit(sqlFunctionExpression.Arguments[0]);
                Sql.Append("<=0, CAST('NaN' AS FLOAT64), ");

                base.VisitSqlFunction(sqlFunctionExpression);

                Sql.Append(")");
                return(sqlFunctionExpression);
            }

            return(base.VisitSqlFunction(sqlFunctionExpression));
        }
        /// <summary>
        /// SQL函数表达式。
        /// </summary>
        /// <param name="sqlFunctionExpression">表达式实例。</param>
        /// <returns>返回访问后的表达式实例对象。</returns>
        public virtual Expression VisitSqlFunction(SqlFunctionExpression sqlFunctionExpression)
        {
            _builder.Append(sqlFunctionExpression.FunctionName);
            _builder.Append("(");

            VisitJoin(sqlFunctionExpression.Arguments.ToList());

            _builder.Append(")");
            return(sqlFunctionExpression);
        }
Beispiel #26
0
        public virtual Expression VisitSqlFunctionExpression(SqlFunctionExpression expression)
        {
            ArgumentUtility.CheckNotNull("expression", expression);

            _commandBuilder.Append(expression.SqlFunctioName);
            _commandBuilder.Append("(");
            _commandBuilder.AppendSeparated(", ", expression.Args, (cb, exp) => VisitExpression(exp));
            _commandBuilder.Append(")");
            return(expression);
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            foreach (var relacao in modelBuilder.Model.GetEntityTypes().SelectMany(ent => ent.GetForeignKeys()))
            {
                relacao.DeleteBehavior = DeleteBehavior.Restrict;
            }

            modelBuilder.HasDbFunction(typeof(Context).GetMethod(nameof(SoundsLike)))
            .HasTranslation(args => SqlFunctionExpression.Create("SOUNDEX", args, typeof(string), null));
        }
    protected internal virtual Expression VisitSqlFunction(SqlFunctionExpression sqlFunction)
    {
        Expression?obj = Visit(sqlFunction.Object);
        ReadOnlyCollection <Expression> args = Visit(sqlFunction.Arguments);

        if (args != sqlFunction.Arguments || obj != sqlFunction.Object)
        {
            return(new SqlFunctionExpression(sqlFunction.Type, obj, sqlFunction.SqlFunction, args));
        }
        return(sqlFunction);
    }
Beispiel #29
0
        /// <summary>
        /// Translates a SpecialExpression to standard Expression equivalent
        /// </summary>
        /// <param name="sqlFunction"></param>
        /// <returns></returns>
        protected virtual Expression Translate(SqlFunctionExpression sqlFunction)
        {
            var operands = sqlFunction.Operands.ToList();

            switch (sqlFunction.FunctionType)  // SETuse
            {
            case SqlFunctionType.IsNull:
                return(TranslateIsNull(operands));

            case SqlFunctionType.IsNotNull:
                return(TranslateIsNotNull(operands));

            case SqlFunctionType.Concat:
                return(sqlFunction);

            case SqlFunctionType.StringLength:
                return(TranslateStringLength(operands));

            case SqlFunctionType.ToUpper:
                return(GetStandardCallInvoke("ToUpper", operands));

            case SqlFunctionType.ToLower:
                return(GetStandardCallInvoke("ToLower", operands));

            case SqlFunctionType.StringInsert:
                return(GetStandardCallInvoke("Insert", operands));

            case SqlFunctionType.Substring:
            case SqlFunctionType.Trim:
            case SqlFunctionType.LTrim:
            case SqlFunctionType.RTrim:
            case SqlFunctionType.Replace:
            case SqlFunctionType.Remove:
            case SqlFunctionType.IndexOf:
            case SqlFunctionType.Year:
            case SqlFunctionType.Month:
            case SqlFunctionType.Day:
            case SqlFunctionType.Hour:
            case SqlFunctionType.Minute:
            case SqlFunctionType.Millisecond:
            case SqlFunctionType.Date:
                return(GetStandardCallInvoke(sqlFunction.FunctionType.ToString(), operands));

            case SqlFunctionType.Now:
                return(GetDateTimeNowCall(operands));

            case SqlFunctionType.DateDiffInMilliseconds:
                return(GetCallDateDiffInMilliseconds(operands));

            default:
                Util.Throw("S0078: Implement translator for {0}", sqlFunction.FunctionType);
                return(null);
            }
        }
Beispiel #30
0
        public static SqlFunctionExpression GetFunctionCriteria(MethodCallExpression call, ICriterion criterion,
                                                                SqlFunctionExpression rightFunction)
        {
            System.Type[] paramTypes  = null;
            object[]      paramValues = GetMethodParameterValues(call, out paramTypes);

            int    propertyPosition = 0;
            string methodName       = QueryUtil.GetMethodName(call, out propertyPosition);

            return(new SqlFunctionExpression(methodName, call.Method.ReturnType, paramValues, paramTypes, criterion,
                                             propertyPosition, rightFunction));
        }
 protected virtual Expression VisitSqlFunction(SqlFunctionExpression sqlFunction)
 {
     Expression obj = Visit(sqlFunction.Object);
     ReadOnlyCollection<Expression> args = sqlFunction.Arguments.NewIfChange(a => Visit(a));
     if (args != sqlFunction.Arguments || obj != sqlFunction.Object)
         return new SqlFunctionExpression(sqlFunction.Type, obj, sqlFunction.SqlFunction, args); 
     return sqlFunction;
 }
Beispiel #32
0
        protected override Expression VisitSqlFunction(SqlFunctionExpression sqlFunction)
        {
            if (sqlFunction.Object != null)
            {
                Visit(sqlFunction.Object);
                sb.Append(".");
            }
            sb.Append(sqlFunction.SqlFunction);
            sb.Append("(");
            for (int i = 0, n = sqlFunction.Arguments.Count; i < n; i++)
            {
                Expression exp = sqlFunction.Arguments[i];
                if (i > 0)
                    sb.Append(", ");
                this.Visit(exp);
            }
            sb.Append(")");

            return sqlFunction;
        }
Beispiel #33
0
 protected override Expression VisitSqlFunction(SqlFunctionExpression sqlFunction)
 {
     Expression obj = MakeSqlValue(Visit(sqlFunction.Object));
     ReadOnlyCollection<Expression> args = sqlFunction.Arguments.NewIfChange(a => MakeSqlValue(Visit(a)));
     if (args != sqlFunction.Arguments || obj != sqlFunction.Object)
         return new SqlFunctionExpression(sqlFunction.Type, obj, sqlFunction.SqlFunction, args);
     return sqlFunction;
 }