Ejemplo n.º 1
0
        public SelectExpression([NotNull] IQuerySqlGeneratorFactory querySqlGeneratorFactory)
            : base(null, null)
        {
            Check.NotNull(querySqlGeneratorFactory, nameof(querySqlGeneratorFactory));

            _querySqlGeneratorFactory = querySqlGeneratorFactory;
        }
            public QueryingEnumerable(
                CosmosQueryContext cosmosQueryContext,
                ISqlExpressionFactory sqlExpressionFactory,
                IQuerySqlGeneratorFactory querySqlGeneratorFactory,
                SelectExpression selectExpression,
                Func <CosmosQueryContext, JObject, T> shaper,
                Type contextType,
                string partitionKeyFromExtension,
                bool performIdentityResolution)
            {
                _cosmosQueryContext       = cosmosQueryContext;
                _sqlExpressionFactory     = sqlExpressionFactory;
                _querySqlGeneratorFactory = querySqlGeneratorFactory;
                _selectExpression         = selectExpression;
                _shaper      = shaper;
                _contextType = contextType;
                _queryLogger = cosmosQueryContext.QueryLogger;
                _performIdentityResolution = performIdentityResolution;

                var partitionKey = selectExpression.GetPartitionKey(cosmosQueryContext.ParameterValues);

                if (partitionKey != null && partitionKeyFromExtension != null && partitionKeyFromExtension != partitionKey)
                {
                    throw new InvalidOperationException(CosmosStrings.PartitionKeyMismatch(partitionKeyFromExtension, partitionKey));
                }

                _partitionKey = partitionKey ?? partitionKeyFromExtension;
            }
 /// <summary>
 ///     From IncludeExpressionVisitor in EF core
 /// </summary>
 public ReplaceIncludeExpressionVisitor(
     ISelectExpressionFactory selectExpressionFactory,
     ICompositePredicateExpressionVisitorFactory compositePredicateExpressionVisitorFactory,
     IMaterializerFactory materializerFactory,
     IShaperCommandContextFactory shaperCommandContextFactory,
     IRelationalAnnotationProvider relationalAnnotationProvider,
     IQuerySqlGeneratorFactory querySqlGeneratorFactory,
     IQuerySource querySource,
     IReadOnlyList <INavigation> navigationPath,
     RelationalQueryCompilationContext queryCompilationContext,
     IReadOnlyList <int> queryIndexes,
     bool querySourceRequiresTracking,
     INavigationExpressionCollection collection)
 {
     _selectExpressionFactory = selectExpressionFactory;
     _compositePredicateExpressionVisitorFactory = compositePredicateExpressionVisitorFactory;
     _materializerFactory          = materializerFactory;
     _shaperCommandContextFactory  = shaperCommandContextFactory;
     _relationalAnnotationProvider = relationalAnnotationProvider;
     _querySqlGeneratorFactory     = querySqlGeneratorFactory;
     _querySource                 = querySource;
     _navigationPath              = navigationPath;
     _queryCompilationContext     = queryCompilationContext;
     _queryIndexes                = queryIndexes;
     _querySourceRequiresTracking = querySourceRequiresTracking;
     _collection = collection;
 }
 /// <summary>
 ///     Clones this dependency parameter object with one service replaced.
 /// </summary>
 /// <param name="querySqlGeneratorFactory"> A replacement for the current dependency of this type. </param>
 /// <returns> A new parameter object with the given service replaced. </returns>
 public RelationalShapedQueryCompilingExpressionVisitorDependencies With(
     [NotNull] IQuerySqlGeneratorFactory querySqlGeneratorFactory)
 => new RelationalShapedQueryCompilingExpressionVisitorDependencies(
     querySqlGeneratorFactory,
     SqlExpressionFactory,
     ParameterNameGeneratorFactory,
     RelationalParameterBasedQueryTranslationPostprocessorFactory);
Ejemplo n.º 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>
 public CosmosShapedQueryCompilingExpressionVisitorFactory(IEntityMaterializerSource entityMaterializerSource,
                                                           ISqlExpressionFactory sqlExpressionFactory,
                                                           IQuerySqlGeneratorFactory querySqlGeneratorFactory)
 {
     _entityMaterializerSource = entityMaterializerSource;
     _sqlExpressionFactory     = sqlExpressionFactory;
     _querySqlGeneratorFactory = querySqlGeneratorFactory;
 }
Ejemplo n.º 6
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>
 public CosmosShapedQueryCompilingExpressionVisitorFactory(
     [NotNull] ShapedQueryCompilingExpressionVisitorDependencies dependencies,
     [NotNull] ISqlExpressionFactory sqlExpressionFactory,
     [NotNull] IQuerySqlGeneratorFactory querySqlGeneratorFactory)
 {
     _dependencies             = dependencies;
     _sqlExpressionFactory     = sqlExpressionFactory;
     _querySqlGeneratorFactory = querySqlGeneratorFactory;
 }
        /// <summary>
        ///     <para>
        ///         Creates the service dependencies parameter object for a <see cref="SelectExpression" />.
        ///     </para>
        ///     <para>
        ///         Do not call this constructor directly from either provider or application code as it may change
        ///         as new dependencies are added. Instead, use this type in your constructor so that an instance
        ///         will be created and injected automatically by the dependency injection container. To create
        ///         an instance with some dependent services replaced, first resolve the object from the dependency
        ///         injection container, then replace selected services using the 'With...' methods. Do not call
        ///         the constructor at any point in this process.
        ///     </para>
        /// </summary>
        /// <param name="querySqlGeneratorFactory"> The query SQL generator factory. </param>
        /// <param name="relationalAnnotationProvider"></param>
        public SelectExpressionDependencies([NotNull] IQuerySqlGeneratorFactory querySqlGeneratorFactory,
                                            [NotNull] IRelationalAnnotationProvider relationalAnnotationProvider)
        {
            Check.NotNull(querySqlGeneratorFactory, nameof(querySqlGeneratorFactory));
            Check.NotNull(relationalAnnotationProvider, nameof(relationalAnnotationProvider));

            QuerySqlGeneratorFactory     = querySqlGeneratorFactory;
            RelationalAnnotationProvider = relationalAnnotationProvider;
        }
Ejemplo n.º 8
0
        public SelectExpression(
            [NotNull] IQuerySqlGeneratorFactory querySqlGeneratorFactory,
            [NotNull] string alias)
            : base(null, Check.NotNull(alias, nameof(alias)))
        {
            Check.NotNull(querySqlGeneratorFactory, nameof(querySqlGeneratorFactory));

            _querySqlGeneratorFactory = querySqlGeneratorFactory;
        }
Ejemplo n.º 9
0
 public MongoShapedQueryCompilingExpressionVisitorFactory(
     ShapedQueryCompilingExpressionVisitorDependencies dependencies,
     ISqlExpressionFactory sqlExpressionFactory,
     IQuerySqlGeneratorFactory querySqlGeneratorFactory)
 {
     _dependencies             = dependencies;
     _sqlExpressionFactory     = sqlExpressionFactory;
     _querySqlGeneratorFactory = querySqlGeneratorFactory;
 }
Ejemplo n.º 10
0
        /// <summary>
        /// 将linq转换成sql 返回sql和参数(EFCore 3.1)
        /// 第一个字符串为替换过 参数的sql字符串
        /// 第二个字符串为原始的sql字符串
        /// 第三个参数为参数
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="query"></param>
        /// <returns></returns>
        public static (string, string, IReadOnlyDictionary <string, object>) ToSqlWithParams <TEntity>(this IQueryable <TEntity> query)
        {
            var enumerator = query.Provider
                             .Execute <IEnumerable <TEntity> >(query.Expression)
                             .GetEnumerator();

            Type enumeratorType = enumerator.GetType();

            FieldInfo relationalCommandCacheFieldInfo = enumeratorType.GetField("_relationalCommandCache", bindingFlags)
                                                        ?? throw new InvalidOperationException(
                                                                  $"cannot find field _relationalCommandCache on type {enumeratorType.Name}");
            Type relationalCommandCacheType = relationalCommandCacheFieldInfo.FieldType;

            //获取查询表达式
            var selectFieldInfo = relationalCommandCacheType.GetField("_selectExpression", bindingFlags)
                                  ?? throw new InvalidOperationException(
                                            $"cannot find field _selectExpression on type {relationalCommandCacheType.Name}");
            var sqlGeneratorFieldInfo = relationalCommandCacheType.GetField("_querySqlGeneratorFactory", bindingFlags)
                                        ?? throw new InvalidOperationException(
                                                  $"cannot find field _querySqlGeneratorFactory on type {relationalCommandCacheType.Name}");
            var queryContextFieldInfo = enumeratorType.GetField("_relationalQueryContext", bindingFlags)
                                        ?? throw new InvalidOperationException(
                                                  $"cannot find field _relationalQueryContext on type {enumeratorType.Name}");

            object relationalCommandCache = relationalCommandCacheFieldInfo.GetValue(enumerator);

            var selectExpression = selectFieldInfo.GetValue(relationalCommandCache) as SelectExpression
                                   ?? throw new InvalidOperationException($"could not get SelectExpression");

            var queryContext = queryContextFieldInfo.GetValue(enumerator) as RelationalQueryContext
                               ?? throw new InvalidOperationException($"could not get RelationalQueryContext");

            IQuerySqlGeneratorFactory factory = sqlGeneratorFieldInfo.GetValue(relationalCommandCache)
                                                as IQuerySqlGeneratorFactory
                                                ?? throw new InvalidOperationException($"could not get IQuerySqlGeneratorFactory");

            //创建一个查询的对象
            var sqlGenerator = factory.Create();
            //获取执行的命令
            var command = sqlGenerator.GetCommand(selectExpression);
            //执行sql传递的参数
            var parametersDict = queryContext.ParameterValues;
            //原始的sql执行文本
            var sql = command.CommandText;
            //将参数赋值转换
            var converSql = sql;

            if (parametersDict != null && parametersDict.Count() > 0)
            {
                foreach (var item in parametersDict)
                {
                    converSql = converSql.Replace($"@{item.Key}", $"'{item.Value.ToString()}'");
                }
            }
            return(converSql, sql, parametersDict);
        }
        /// <summary>
        ///     <para>
        ///         Creates the service dependencies parameter object for a <see cref="SelectExpression" />.
        ///     </para>
        ///     <para>
        ///         Do not call this constructor directly from either provider or application code as it may change
        ///         as new dependencies are added. Instead, use this type in your constructor so that an instance
        ///         will be created and injected automatically by the dependency injection container. To create
        ///         an instance with some dependent services replaced, first resolve the object from the dependency
        ///         injection container, then replace selected services using the 'With...' methods. Do not call
        ///         the constructor at any point in this process.
        ///     </para>
        /// </summary>
        /// <param name="querySqlGeneratorFactory"> The query SQL generator factory. </param>
        /// <param name="typeMapper"> The type mapper. </param>
        public SelectExpressionDependencies(
            [NotNull] IQuerySqlGeneratorFactory querySqlGeneratorFactory,
            [NotNull] IRelationalTypeMapper typeMapper)
        {
            Check.NotNull(querySqlGeneratorFactory, nameof(querySqlGeneratorFactory));
            Check.NotNull(typeMapper, nameof(typeMapper));

            QuerySqlGeneratorFactory = querySqlGeneratorFactory;
            TypeMapper = typeMapper;
        }
Ejemplo n.º 12
0
        public static IRelationalCommand Generate(
            this DbContext dbContext,
            SelectExpression databaseExpression,
            IReadOnlyDictionary <string, object> parameters = null)
        {
            IQuerySqlGeneratorFactory sqlGeneratorFactory = dbContext.GetService <IQuerySqlGeneratorFactory>();
            IQuerySqlGenerator        sqlGenerator        = sqlGeneratorFactory.CreateDefault(databaseExpression);

            return(sqlGenerator.GenerateSql(parameters ?? new Dictionary <string, object>()));
        }
Ejemplo n.º 13
0
        /// <summary>
        ///     <para>
        ///         Creates the service dependencies parameter object for a <see cref="SelectExpression" />.
        ///     </para>
        ///     <para>
        ///         Do not call this constructor directly from either provider or application code as it may change
        ///         as new dependencies are added. Instead, use this type in your constructor so that an instance
        ///         will be created and injected automatically by the dependency injection container. To create
        ///         an instance with some dependent services replaced, first resolve the object from the dependency
        ///         injection container, then replace selected services using the 'With...' methods. Do not call
        ///         the constructor at any point in this process.
        ///     </para>
        /// </summary>
        /// <param name="querySqlGeneratorFactory"> The query SQL generator factory. </param>
        /// <param name="typeMappingSource"> The type mapper. </param>
        public SelectExpressionDependencies(
            [NotNull] IQuerySqlGeneratorFactory querySqlGeneratorFactory,
            [NotNull] IRelationalTypeMappingSource typeMappingSource)
        {
            Check.NotNull(querySqlGeneratorFactory, nameof(querySqlGeneratorFactory));
            Check.NotNull(typeMappingSource, nameof(typeMappingSource));

            QuerySqlGeneratorFactory = querySqlGeneratorFactory;
            TypeMappingSource        = typeMappingSource;
        }
Ejemplo n.º 14
0
        public SelectExpression([NotNull] IQuerySqlGeneratorFactory querySqlGeneratorFactory,
            [NotNull] RelationalQueryCompilationContext queryCompilationContext)
            : base(null, null)
        {
            Check.NotNull(querySqlGeneratorFactory, nameof(querySqlGeneratorFactory));
            Check.NotNull(queryCompilationContext, nameof(queryCompilationContext));

            _querySqlGeneratorFactory = querySqlGeneratorFactory;
            _queryCompilationContext = queryCompilationContext;
        }
Ejemplo n.º 15
0
 public Enumerator(QueryingEnumerable <T> queryingEnumerable)
 {
     _relationalQueryContext = queryingEnumerable._relationalQueryContext;
     _shaper                        = queryingEnumerable._shaper;
     _selectExpression              = queryingEnumerable._selectExpression;
     _querySqlGeneratorFactory      = queryingEnumerable._querySqlGeneratorFactory;
     _contextType                   = queryingEnumerable._contextType;
     _logger                        = queryingEnumerable._logger;
     _sqlExpressionFactory          = queryingEnumerable._sqlExpressionFactory;
     _parameterNameGeneratorFactory = queryingEnumerable._parameterNameGeneratorFactory;
 }
 /// <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 CosmosShapedQueryCompilingExpressionVisitor(
     ShapedQueryCompilingExpressionVisitorDependencies dependencies,
     QueryCompilationContext queryCompilationContext,
     ISqlExpressionFactory sqlExpressionFactory,
     IQuerySqlGeneratorFactory querySqlGeneratorFactory)
     : base(dependencies, queryCompilationContext)
 {
     _sqlExpressionFactory     = sqlExpressionFactory;
     _querySqlGeneratorFactory = querySqlGeneratorFactory;
     _contextType = queryCompilationContext.ContextType;
     _logger      = queryCompilationContext.Logger;
 }
 /// <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 RelationalCommandCache(
     [NotNull] IMemoryCache memoryCache,
     [NotNull] IQuerySqlGeneratorFactory querySqlGeneratorFactory,
     [NotNull] IRelationalParameterBasedSqlProcessorFactory relationalParameterBasedSqlProcessorFactory,
     bool useRelationalNulls,
     [NotNull] SelectExpression selectExpression)
 {
     _memoryCache = memoryCache;
     _querySqlGeneratorFactory             = querySqlGeneratorFactory;
     _selectExpression                     = selectExpression;
     _relationalParameterBasedSqlProcessor = relationalParameterBasedSqlProcessorFactory.Create(useRelationalNulls);
 }
        /// <summary>
        /// parse select statement of queryable
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="queryable"></param>
        /// <param name="ctx"></param>
        /// <returns></returns>
        public static SelectParsingResult Parse <TEntity>(this IQueryable <TEntity> queryable, DbContext ctx, bool ignoreQueryFilters) where TEntity : class
        {
            if (ignoreQueryFilters)
            {
                queryable = queryable.IgnoreQueryFilters();
            }
            SelectParsingResult parsingResult = new SelectParsingResult();
            Expression          query         = queryable.Expression;
            var databaseDependencies          = ctx.GetService <DatabaseDependencies>();
            IQueryTranslationPreprocessorFactory _queryTranslationPreprocessorFactory = ctx.GetService <IQueryTranslationPreprocessorFactory>();
            IQueryableMethodTranslatingExpressionVisitorFactory _queryableMethodTranslatingExpressionVisitorFactory = ctx.GetService <IQueryableMethodTranslatingExpressionVisitorFactory>();
            IQueryTranslationPostprocessorFactory _queryTranslationPostprocessorFactory = ctx.GetService <IQueryTranslationPostprocessorFactory>();
            QueryCompilationContext queryCompilationContext = databaseDependencies.QueryCompilationContextFactory.Create(true);

            IDiagnosticsLogger <DbLoggerCategory.Query> logger = ctx.GetService <IDiagnosticsLogger <DbLoggerCategory.Query> >();
            QueryContext  queryContext  = ctx.GetService <IQueryContextFactory>().Create();
            QueryCompiler queryComipler = ctx.GetService <IQueryCompiler>() as QueryCompiler;
            //parameterize determines if it will use "Declare" or not
            MethodCallExpression         methodCallExpr1 = queryComipler.ExtractParameters(query, queryContext, logger, parameterize: true) as MethodCallExpression;
            QueryTranslationPreprocessor queryTranslationPreprocessor = _queryTranslationPreprocessorFactory.Create(queryCompilationContext);
            MethodCallExpression         methodCallExpr2 = queryTranslationPreprocessor.Process(methodCallExpr1) as MethodCallExpression;
            QueryableMethodTranslatingExpressionVisitor queryableMethodTranslatingExpressionVisitor =
                _queryableMethodTranslatingExpressionVisitorFactory.Create(queryCompilationContext);
            ShapedQueryExpression         shapedQueryExpression1        = queryableMethodTranslatingExpressionVisitor.Visit(methodCallExpr2) as ShapedQueryExpression;
            QueryTranslationPostprocessor queryTranslationPostprocessor = _queryTranslationPostprocessorFactory.Create(queryCompilationContext);
            ShapedQueryExpression         shapedQueryExpression2        = queryTranslationPostprocessor.Process(shapedQueryExpression1) as ShapedQueryExpression;

            IRelationalParameterBasedSqlProcessorFactory _relationalParameterBasedSqlProcessorFactory =
                ctx.GetService <IRelationalParameterBasedSqlProcessorFactory>();
            RelationalParameterBasedSqlProcessor _relationalParameterBasedSqlProcessor = _relationalParameterBasedSqlProcessorFactory.Create(true);

            SelectExpression selectExpression = (SelectExpression)shapedQueryExpression2.QueryExpression;

            selectExpression = _relationalParameterBasedSqlProcessor.Optimize(selectExpression, queryContext.ParameterValues, out bool canCache);
            IQuerySqlGeneratorFactory querySqlGeneratorFactory = ctx.GetService <IQuerySqlGeneratorFactory>();
            IZackQuerySqlGenerator    querySqlGenerator        = querySqlGeneratorFactory.Create() as IZackQuerySqlGenerator;

            if (querySqlGenerator == null)
            {
                throw new InvalidOperationException("please add dbContext.UseBatchEF() to OnConfiguring first!");
            }
            querySqlGenerator.IsForBatchEF = true;
            querySqlGenerator.GetCommand(selectExpression);
            parsingResult.Parameters    = queryContext.ParameterValues;
            parsingResult.PredicateSQL  = querySqlGenerator.PredicateSQL;
            parsingResult.ProjectionSQL = querySqlGenerator.ProjectionSQL;
            TableExpression tableExpression = selectExpression.Tables[0] as TableExpression;

            parsingResult.TableName = tableExpression.Table.Name;

            return(parsingResult);
        }
 public CosmosShapedQueryCompilingExpressionVisitor(
     ShapedQueryCompilingExpressionVisitorDependencies dependencies,
     CosmosQueryCompilationContext cosmosQueryCompilationContext,
     ISqlExpressionFactory sqlExpressionFactory,
     IQuerySqlGeneratorFactory querySqlGeneratorFactory)
     : base(dependencies, cosmosQueryCompilationContext)
 {
     _sqlExpressionFactory     = sqlExpressionFactory;
     _querySqlGeneratorFactory = querySqlGeneratorFactory;
     _contextType = cosmosQueryCompilationContext.ContextType;
     _threadSafetyChecksEnabled = dependencies.CoreSingletonOptions.AreThreadSafetyChecksEnabled;
     _partitionKeyFromExtension = cosmosQueryCompilationContext.PartitionKeyFromExtension;
 }
        /// <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 IncludeExpressionVisitorFactory(
            [NotNull] ISelectExpressionFactory selectExpressionFactory,
            [NotNull] ICompositePredicateExpressionVisitorFactory compositePredicateExpressionVisitorFactory,
            [NotNull] IMaterializerFactory materializerFactory,
            [NotNull] IShaperCommandContextFactory shaperCommandContextFactory,
            [NotNull] IRelationalAnnotationProvider relationalAnnotationProvider,
            [NotNull] IQuerySqlGeneratorFactory querySqlGeneratorFactory)
        {
            Check.NotNull(selectExpressionFactory, nameof(selectExpressionFactory));
            Check.NotNull(compositePredicateExpressionVisitorFactory, nameof(compositePredicateExpressionVisitorFactory));
            Check.NotNull(materializerFactory, nameof(materializerFactory));
            Check.NotNull(shaperCommandContextFactory, nameof(shaperCommandContextFactory));
            Check.NotNull(relationalAnnotationProvider, nameof(relationalAnnotationProvider));
            Check.NotNull(querySqlGeneratorFactory, nameof(querySqlGeneratorFactory));

            _selectExpressionFactory = selectExpressionFactory;
            _compositePredicateExpressionVisitorFactory = compositePredicateExpressionVisitorFactory;
            _materializerFactory = materializerFactory;
            _shaperCommandContextFactory = shaperCommandContextFactory;
            _relationalAnnotationProvider = relationalAnnotationProvider;
            _querySqlGeneratorFactory = querySqlGeneratorFactory;
        }
        /// <summary>
        ///     Initializes a new instance of the Microsoft.EntityFrameworkCore.Query.Expressions.SelectExpressionFactory class.
        /// </summary>
        /// <param name="querySqlGeneratorFactory"> The query SQL generator factory. </param>
        public SelectExpressionFactory([NotNull] IQuerySqlGeneratorFactory querySqlGeneratorFactory)
        {
            Check.NotNull(querySqlGeneratorFactory, nameof(querySqlGeneratorFactory));

            _querySqlGeneratorFactory = querySqlGeneratorFactory;
        }