public void CopyTab()
 {
     try
     {
         var model = new TabModel
         {
             Name        = Name,
             FilterQuery = Model.FilterQuery != null
                 ? QueryCompiler.Compile(Model.FilterQuery.ToQuery())
                 : null,
             RawQueryString    = Model.RawQueryString,
             BindingHashtags   = Model.BindingHashtags.ToArray(),
             NotifyNewArrivals = Model.NotifyNewArrivals,
             ShowUnreadCounts  = Model.ShowUnreadCounts,
             NotifySoundSource = Model.NotifySoundSource
         };
         Model.BindingAccounts.ForEach(id => model.BindingAccounts.Add(id));
         Parent.Model.CreateTab(model);
     }
     catch (FilterQueryException fqex)
     {
         BackstageModel.RegisterEvent(
             new OperationFailedEvent(QueryCompilerResources.QueryCompileFailed, fqex));
     }
 }
Exemple #2
0
 private IEnumerable <IFilter> GenerateFilters(IEnumerable <string> queries)
 {
     foreach (var s in queries)
     {
         FilterCluster cluster = null;
         try
         {
             cluster = QueryCompiler.ToFilter(s);
         }
         catch (Exception e)
         {
             ExceptionStorage.Register(e, ExceptionCategory.ConfigurationError, "フィルタ クエリを読み取れません: " + s);
         }
         if (cluster != null)
         {
             if (cluster.Filters.Count() == 1)
             {
                 var filter = cluster.Filters.First();
                 if (cluster.Negate)
                 {
                     filter.Negate = !filter.Negate;
                 }
                 yield return(filter);
             }
             else
             {
                 yield return(cluster);
             }
         }
     }
 }
Exemple #3
0
        public static IDisposable Dump(IList <string> etlfiles,
                                       Action <Type> onStart,
                                       Action <object> onNext,
                                       Action <Exception> onError,
                                       string query)
        {
            StringWriter          writer  = new StringWriter();
            StringWriter          error   = new StringWriter();
            QueryExecutionContext context = QueryExecutionContext.CreateFromFiles(etlfiles, onStart, onNext);

            QueryCompiler.CompileAndRun(context,
                                        query,
                                        error,
                                        writer);

            string output = error.ToString();

            if (!String.IsNullOrEmpty(output))
            {
                if (onError != null)
                {
                    onError(new Exception(output));
                }
            }

            return(context);
        }
        IReadOnlyList <ICodeFile> ICodeFileCollection.BuildFiles()
        {
            using var lightweight =
                      (QuerySession)OpenSession(
                          new SessionOptions { Tracking = DocumentTracking.None, AllowAnyTenant = true });

            using var identityMap = (QuerySession)OpenSession(
                      new SessionOptions { Tracking = DocumentTracking.IdentityOnly, AllowAnyTenant = true });
            using var dirty = (QuerySession)OpenSession(
                      new SessionOptions { Tracking = DocumentTracking.DirtyTracking, AllowAnyTenant = true });


            var options = new SessionOptions
            {
                AllowAnyTenant = true
            };

            var connection = options.Initialize(this, CommandRunnerMode.ReadOnly);

            using var readOnly = new QuerySession(this, options, connection);

            return(Options.CompiledQueryTypes.SelectMany(x => new ICodeFile[]
            {
                new CompiledQueryCodeFile(x, this, QueryCompiler.BuildPlan(lightweight, x, Options), DocumentTracking.None),
                new CompiledQueryCodeFile(x, this, QueryCompiler.BuildPlan(identityMap, x, Options), DocumentTracking.IdentityOnly),
                new CompiledQueryCodeFile(x, this, QueryCompiler.BuildPlan(dirty, x, Options), DocumentTracking.DirtyTracking),
                new CompiledQueryCodeFile(x, this, QueryCompiler.BuildPlan(readOnly, x, Options), DocumentTracking.QueryOnly)
            }).ToList());
        }
        internal ICompiledQuerySource GetCompiledQuerySourceFor <TDoc, TOut>(ICompiledQuery <TDoc, TOut> query,
                                                                             QuerySession session)
        {
            if (_querySources.TryFind(query.GetType(), out var source))
            {
                return(source);
            }

            if (typeof(TOut).CanBeCastTo <Task>())
            {
                throw InvalidCompiledQueryException.ForCannotBeAsync(query.GetType());
            }

            var plan = QueryCompiler.BuildPlan(session, query, _store.Options);
            var file = new CompiledQueryCodeFile(query.GetType(), _store, plan, _tracking);

            var rules = _store.Options.CreateGenerationRules();

            rules.ReferenceTypes(typeof(TDoc), typeof(TOut), query.GetType());

            file.InitializeSynchronously(rules, _store, null);

            source        = file.Build(rules);
            _querySources = _querySources.AddOrUpdate(query.GetType(), source);

            return(source);
        }
Exemple #6
0
        protected CompiledQueryPlan planFor <TDoc, TOut>(ICompiledQuery <TDoc, TOut> query)
        {
            using var store   = DocumentStore.For(ConnectionSource.ConnectionString);
            using var session = store.QuerySession();

            return(QueryCompiler.BuildPlan((IMartenSession)session, query, new StoreOptions()));
        }
Exemple #7
0
        public TabModel ToTabModel()
        {
            FilterQuery filter;

            try
            {
                filter = QueryCompiler.Compile(Query);
            }
            catch (FilterQueryException ex)
            {
                BackstageModel.RegisterEvent(new QueryCorruptionEvent(Name, ex));
                filter = null;
            }
            var model = new TabModel
            {
                Name              = Name,
                FilterQuery       = filter,
                BindingHashtags   = this.BindingHashtags,
                NotifyNewArrivals = this.NotifyNewArrivals,
                NotifySoundSource = this.NotifySoundSource,
                ShowUnreadCounts  = this.ShowUnreadCounts
            };

            this.BindingAccountIds.ForEach(model.BindingAccounts.Add);
            return(model);
        }
        public Task AttachPreBuiltTypes(GenerationRules rules, Assembly assembly, IServiceProvider services)
        {
            foreach (var mapping in Storage.AllDocumentMappings)
            {
                var builder = typeof(ProviderBuilder <>).CloseAndBuildAs <IProviderBuilder>(mapping.DocumentType);
                builder.BuildAndStore(assembly, mapping, this);
            }

            if (_compiledQueryTypes.Any())
            {
                using var session = new LightweightSession(this);
                foreach (var compiledQueryType in _compiledQueryTypes)
                {
                    var plan    = QueryCompiler.BuildPlan(session, compiledQueryType, this);
                    var builder = new CompiledQuerySourceBuilder(plan, this);
                    var source  = builder.CreateFromPreBuiltType(assembly);

                    if (source == null)
                    {
                        Console.WriteLine("Could not find a pre-built compiled query source type for compiled query type " + compiledQueryType.FullNameInCode());
                    }
                    else
                    {
                        _querySources = _querySources.AddOrUpdate(compiledQueryType, source);
                    }
                }
            }

            return(Task.CompletedTask);
        }
        private void SearchVFMappings()
        {
            //        Console.Out.WriteLine("searchVFMappings ");
            IQuery  query  = null;
            IMapper mapper = null;

            vfLibSolutions = new Dictionary <INode, IAtom>();
            if (queryMol != null)
            {
                query  = new QueryCompiler(queryMol).Compile();
                mapper = new VFMapper(query);
                if (mapper.HasMap(GetProductMol()))
                {
                    var map = mapper.GetFirstMap(GetProductMol());
                    if (map != null)
                    {
                        foreach (var e in map)
                        {
                            vfLibSolutions[e.Key] = e.Value;
                        }
                    }
                }
                SetVFMappings(true, query);
            }
            else if (GetReactantMol().Atoms.Count <= GetProductMol().Atoms.Count)
            {
                query  = new QueryCompiler(mol1, IsBondMatchFlag).Compile();
                mapper = new VFMapper(query);
                if (mapper.HasMap(GetProductMol()))
                {
                    var map = mapper.GetFirstMap(GetProductMol());
                    if (map != null)
                    {
                        foreach (var e in map)
                        {
                            vfLibSolutions[e.Key] = e.Value;
                        }
                    }
                }
                SetVFMappings(true, query);
            }
            else
            {
                query  = new QueryCompiler(GetProductMol(), IsBondMatchFlag).Compile();
                mapper = new VFMapper(query);
                if (mapper.HasMap(GetReactantMol()))
                {
                    var map = mapper.GetFirstMap(GetReactantMol());
                    if (map != null)
                    {
                        foreach (var e in map)
                        {
                            vfLibSolutions[e.Key] = e.Value;
                        }
                    }
                }
                SetVFMappings(false, query);
            }
        }
        public ConnectionProvider(Action<string> onExecute)
            : base(null, null)
        {
            CheckCallbackCall = true;
            QueryCompiler = new QueryCompiler();

            _onExecute = onExecute;
        }
Exemple #11
0
        public void DatabaseConnection_Open_ExternalObjects_ExecutorNull()
        {
            var compiler = new QueryCompiler();

            var connection = new DatabaseConnection(compiler, null);
            var context    = connection.Open();

            Assert.AreSame(context.Compiler, compiler);
            Assert.IsNotNull(context.ExecutionContext);
        }
Exemple #12
0
        public void DatabaseConnection_Open_ExternalObjects()
        {
            var compiler = new QueryCompiler();
            var executor = new ExecutionContext(null);

            var connection = new DatabaseConnection(compiler, executor);
            var context    = connection.Open();

            Assert.AreSame(context.Compiler, compiler);
            Assert.AreSame(context.ExecutionContext, executor);
        }
Exemple #13
0
        public QueryKeyGenerator(IQueryContextFactory queryContextFactory, IQueryCompiler queryCompiler, IDiagnosticsLogger <DbLoggerCategory.Query> logger)
        {
            if (queryCompiler is not QueryCompiler compiler)
            {
                throw new InvalidCastException($"Implementation type of '{nameof(IQueryCompiler)}' must be '{typeof(QueryCompiler)}'");
            }

            _queryCompiler       = compiler;
            _queryContextFactory = queryContextFactory;
            _logger = logger;
        }
        public void QueryCompilerCompileDeleteTest()
        {
            var part = new DelegateQueryPart(OperationType.Delete, () => "Table");
            var parts = new QueryPartsContainer();
            parts.Add(part);

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, "DELETE FROM Table");
        }
Exemple #15
0
        protected ICompiledQuerySource buildQuerySourceFor <TDoc, TOut>(ICompiledQuery <TDoc, TOut> query)
        {
            using var store = DocumentStore.For(ConnectionSource.ConnectionString);
            store.Advanced.Clean.CompletelyRemoveAll();

            using var session = store.QuerySession();

            var plan = QueryCompiler.BuildPlan((IMartenSession)session, query, new StoreOptions());

            return(new CompiledQuerySourceBuilder(plan, new StoreOptions()).Build());
        }
        public void QueryCompilerCompileAndTest()
        {
            var part = new DelegateQueryPart(OperationType.And, () => "Field = 1");
            var parts = new QueryPartsContainer();
            parts.Add(part);

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, "\r\n AND Field = 1");
        }
        public void QueryCompilerCompileFieldTest()
        {
            var part = new QueryPart(OperationType.None);
            part.Add(new FieldQueryPart("Name", null));
            var parts = new QueryPartsContainer();
            parts.Add(part);

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, " Name");
        }
        public void QueryCompilerCompileCountTest()
        {
            var part = new QueryPart(OperationType.None);
            part.Add(new FieldQueryPart("Name", "Alias", operation: OperationType.Count));
            var parts = new QueryPartsContainer();
            parts.Add(part);

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, " COUNT(Name) AS Alias");
        }
        /// <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 void CompileQueryTest()
        {
            // setup
            var parts = new Mock<IQueryPartsContainer>();
            //parts.Setup(p => p.Compile()).Returns(new CompiledQuery());

            // Act
            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts.Object, new InterceptorCollection());

            Assert.IsNotNull(query);
            //parts.Verify(p => p.Compile(), Times.Once);
        }
Exemple #21
0
        public void QueryCompiler_Compile_UnOrdered()
        {
            var container = new ComponentContainer()
                            .Add(new QueryComponent(SyntaxComponent.Keyword, "FROM"))
                            .Add(new QueryComponent(SyntaxComponent.Keytable, "Item"))
                            .Add(new QueryComponent(SyntaxComponent.FieldList, "ID, Name"))
                            .Add(new QueryComponent(SyntaxComponent.Command, "SELECT"));

            var compiler = new QueryCompiler();
            var query    = compiler.Compile(container);

            Assert.AreEqual("SELECT ID, Name FROM Item", query.Query);
        }
        private async void OnTextChanged(string value)
        {
            if (value != null && value.StartsWith("?"))
            {
                IsQueryMode             = true;
                IsSearchOptionAvailable = false;
                IsSearchResultAvailable = false;
                ErrorText = SearchFlipResources.SearchFlipQueryCompiling;
                try
                {
                    if (value == "?")
                    {
                        ErrorText = SearchFlipResources.SearchFlipQueryEmpty;
                        IsSearchResultAvailable = false;
                        return;
                    }
                    await Task.Run(() =>
                    {
                        var result = QueryCompiler.Compile(value.Substring(1));
                        result.GetEvaluator(); // check evaluator
                    });

                    ErrorText = null;
                }
                catch (FilterQueryException fex)
                {
                    ErrorText = fex.Message;
                }
            }
            else
            {
                IsQueryMode             = false;
                IsSearchOptionAvailable = true;
                ErrorText = null;
                if (String.IsNullOrEmpty(value))
                {
                    IsSearchResultAvailable = false;
                    IsSearchOptionAvailable = false;
                }
                else
                {
                    IsSearchResultAvailable = SearchMode == SearchMode.CurrentTab;
                    if (IsSearchResultAvailable)
                    {
                        CommitSearch();
                    }
                    CanBeUserScreenName = _userScreenNameRegex.IsMatch(value);
                }
            }
        }
        public static EnumerateFactory <T> GetEnumerateFactory <T>(ISchema schema, IDataRecord header)
        {
            ColumnCacheKey cacheKey = GetCacheKey(schema, QueryType.List, header);

            return((EnumerateFactory <T>)enumerateMap.GetOrAdd(cacheKey, k =>
            {
                EnumerateParser parser = new EnumerateParser(schema);
                EnumerateResult result = parser.Parse(k.Header);

                QueryCompiler compiler = new QueryCompiler();

                return compiler.Compile <T>(result);
            }));
        }
Exemple #24
0
        internal ICompiledQuerySource GetCompiledQuerySourceFor <TDoc, TOut>(ICompiledQuery <TDoc, TOut> query, IMartenSession session)
        {
            if (_querySources.TryFind(query.GetType(), out var source))
            {
                return(source);
            }

            var plan = QueryCompiler.BuildPlan(session, query, this);

            source        = new CompiledQuerySourceBuilder(plan, this).Build();
            _querySources = _querySources.AddOrUpdate(query.GetType(), source);

            return(source);
        }
        public static AggregateFactory GetAggregateFactory(ISchema schema, IEnumerable <AggregateAttribute> header)
        {
            AggregateCacheKey cacheKey = new AggregateCacheKey(schema, QueryType.Aggregate, header.ToList());

            return((AggregateFactory)aggregateMap.GetOrAdd(cacheKey, k =>
            {
                AggregateParser parser = new AggregateParser(k.Schema);
                AggregateResult result = parser.Parse(k.Header);

                QueryCompiler compiler = new QueryCompiler();

                return compiler.Compile(result);
            }));
        }
        public void SqlServer_QueryCompiler_Compile_AddColumnMissingNUllableTest()
        {
            var part = new ValueCollectionQueryPart(OperationType.AddColumn);
            part.AddValue(KeyValuePart.MemberName, "ColumnName");
            part.AddValue(KeyValuePart.MemberType, "int");

            var parts = new QueryPartsContainer();
            parts.Add(part);

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, "ADD ColumnName int");
        }
        private void SearchVFMappings()
        {
            IQuery  query  = null;
            IMapper mapper = null;

            vfLibSolutions = new List <IReadOnlyDictionary <INode, IAtom> >();
            if (queryMol != null)
            {
                query  = new QueryCompiler(queryMol).Compile();
                mapper = new VFMapper(query);
                if (mapper.HasMap(GetProductMol()))
                {
                    var maps = mapper.GetMaps(GetProductMol());
                    if (maps != null)
                    {
                        vfLibSolutions.AddRange(maps);
                    }
                }
                SetVFMappings(true, query);
            }
            else if (GetReactantMol().Atoms.Count <= GetProductMol().Atoms.Count)
            {
                query  = new QueryCompiler(mol1, IsBondMatchFlag).Compile();
                mapper = new VFMapper(query);
                if (mapper.HasMap(GetProductMol()))
                {
                    var maps = mapper.GetMaps(GetProductMol());
                    if (maps != null)
                    {
                        vfLibSolutions.AddRange(maps);
                    }
                }
                SetVFMappings(true, query);
            }
            else
            {
                query  = new QueryCompiler(GetProductMol(), IsBondMatchFlag).Compile();
                mapper = new VFMapper(query);
                if (mapper.HasMap(GetReactantMol()))
                {
                    var maps = mapper.GetMaps(GetReactantMol());
                    if (maps != null)
                    {
                        vfLibSolutions.AddRange(maps);
                    }
                }
                SetVFMappings(false, query);
            }
        }
 public FilterElementEditorViewModel(FilterBase filter = null)
 {
     if (filter != null)
     {
         this._currentSelectedItem = filter.Identifier + ": " + filter.Description;
         this._prevDescString      = this._currentSelectedItem;
         ConfiguredFilterBase      = QueryCompiler.ToFilter(filter.ToQuery()).Filters.First() as FilterBase;
         this.IsNegate             = filter.Negate;
     }
     else
     {
         this.CurrentSelectedItem = GetFilterDescriptions().First();
     }
     this._filterDescriptions = GetFilterDescriptions().ToArray();
 }
        public void SqliteQueryCompilerCompileAddColumnNullableTest()
        {
            var part = new ValueCollectionQueryPart(OperationType.AddColumn);
            part.AddValue(KeyValuePart.MemberName, "ColumnName");
            part.AddValue(KeyValuePart.MemberType, "int");
            part.AddValue(KeyValuePart.Nullable, true.ToString());

            var parts = new QueryPartsContainer();
            parts.Add(part);

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, "ADD COLUMN ColumnName int");
        }
Exemple #30
0
        IReadOnlyList <ICodeFile> ICodeFileCollection.BuildFiles()
        {
            using var lightweight = (QuerySession)LightweightSession();
            using var identityMap = (QuerySession)OpenSession();
            using var dirty       = (QuerySession)DirtyTrackedSession();
            using var readOnly    = (QuerySession)QuerySession();

            return(Options.CompiledQueryTypes.SelectMany(x => new ICodeFile[]
            {
                new CompiledQueryCodeFile(x, this, QueryCompiler.BuildPlan(lightweight, x, Options), DocumentTracking.None),
                new CompiledQueryCodeFile(x, this, QueryCompiler.BuildPlan(identityMap, x, Options), DocumentTracking.IdentityOnly),
                new CompiledQueryCodeFile(x, this, QueryCompiler.BuildPlan(dirty, x, Options), DocumentTracking.DirtyTracking),
                new CompiledQueryCodeFile(x, this, QueryCompiler.BuildPlan(readOnly, x, Options), DocumentTracking.QueryOnly)
            }).ToList());
        }
Exemple #31
0
        public void CopyTab()
        {
            var model = new TabModel
            {
                Name        = this.Name,
                FilterQuery = this.Model.FilterQuery != null?QueryCompiler.Compile(this.Model.FilterQuery.ToQuery()) : null,
                                  BindingHashtags   = this.Model.BindingHashtags.ToArray(),
                                  NotifyNewArrivals = this.Model.NotifyNewArrivals,
                                  ShowUnreadCounts  = this.Model.ShowUnreadCounts,
                                  NotifySoundSource = this.Model.NotifySoundSource
            };

            this.Model.BindingAccounts.ForEach(id => model.BindingAccounts.Add(id));
            this.Parent.Model.CreateTab(model);
        }
        public static ListFactory GetListFactory(ISchema schema, QueryType queryType, IDataRecord header)
        {
            ColumnCacheKey cacheKey = GetCacheKey(schema, queryType, header);

            return(listMap.GetOrAdd(cacheKey, k =>
            {
                BufferCache buffer = GetBuffer(k.Schema);
                ListParser parser = new ListParser(buffer, queryType);
                ListResult result = parser.Parse(k.Header);

                QueryCompiler compiler = new QueryCompiler();

                return compiler.Compile(result);
            }));
        }
Exemple #33
0
        /// <summary>
        /// Create new tab model
        /// </summary>
        /// <param name="name">tab name</param>
        /// <param name="query">tab query(KQ)</param>
        /// <returns>tab model</returns>
        public static TabModel Create(string name, string query)
        {
            var model = new TabModel
            {
                Name        = name,
                FilterQuery = query != null?QueryCompiler.Compile(query) : null,
                                  RawQueryString    = query,
                                  ShowUnreadCounts  = true,
                                  NotifyNewArrivals = false,
            };
            var cf = TabManager.CurrentFocusTab;

            cf?.BindingAccounts.ForEach(model.BindingAccounts.Add);
            return(model);
        }
Exemple #34
0
        public void TestQueryCache()
        {
            int iterations = 1000;
            var cache      = new QueryCache(10);

            var notCached = RunTimedTest(iterations, i =>
            {
                var results = db.OrderDetails.Where(d => d.OrderID > i).Take(n).ToList();
                System.Diagnostics.Debug.Assert(results.Count == n);
            });

            this.provider.Cache = cache;
            var autoCached = RunTimedTest(iterations, i =>
            {
                var results = db.OrderDetails.Where(d => d.OrderID > i).Take(n).ToList();
                System.Diagnostics.Debug.Assert(results.Count == n);
            });

            this.provider.Cache = null;

            var check = RunTimedTest(iterations, i =>
            {
                var query    = db.OrderDetails.Where(d => d.OrderID > i).Take(n);
                var isCached = cache.Contains(query);
            });

            var cached = RunTimedTest(iterations, i =>
            {
                var query   = db.OrderDetails.Where(d => d.OrderID > i).Take(n);
                var results = cache.Execute(query).ToList();
                System.Diagnostics.Debug.Assert(results.Count == n);
            });

            System.Diagnostics.Debug.Assert(cache.Count == 1);

            var cq       = QueryCompiler.Compile((Northwind nw, int i) => nw.OrderDetails.Where(d => d.OrderID > i).Take(n));
            var compiled = RunTimedTest(iterations, i =>
            {
                var results = cq(db, i).ToList();
                System.Diagnostics.Debug.Assert(results.Count == n);
            });

            Console.WriteLine("compiled   : {0} sec", compiled);
            Console.WriteLine("check cache: {0}", check);
            Console.WriteLine("cached     : {0}  {1:#.##}x vs compiled", cached, cached / compiled);
            Console.WriteLine("auto cached: {0}  {1:#.##}x vs compiled", autoCached, autoCached / compiled);
            Console.WriteLine("not cached : {0}  {1:#.##}x vs compiled", notCached, notCached / compiled);
        }
Exemple #35
0
        private void SearchVFMCSMappings()
        {
            IQuery  query  = null;
            IMapper mapper = null;

            if (queryMol == null)
            {
                countR = GetReactantMol().Atoms.Count
                         + AtomContainerManipulator.GetSingleBondEquivalentSum(GetReactantMol());
                countP = GetProductMol().Atoms.Count
                         + AtomContainerManipulator.GetSingleBondEquivalentSum(GetProductMol());
            }
            vfLibSolutions = new List <IReadOnlyDictionary <INode, IAtom> >();
            if (queryMol != null)
            {
                query  = new QueryCompiler(queryMol).Compile();
                mapper = new VFMCSMapper(query);
                var maps = mapper.GetMaps(GetProductMol());
                if (maps != null)
                {
                    vfLibSolutions.AddRange(maps);
                }
                SetVFMappings(true, query);
            }
            else if (countR <= countP)
            {
                query  = new QueryCompiler(mol1, IsBondMatchFlag).Compile();
                mapper = new VFMCSMapper(query);
                var maps = mapper.GetMaps(GetProductMol());
                if (maps != null)
                {
                    vfLibSolutions.AddRange(maps);
                }
                SetVFMappings(true, query);
            }
            else
            {
                query  = new QueryCompiler(GetProductMol(), IsBondMatchFlag).Compile();
                mapper = new VFMCSMapper(query);
                var maps = mapper.GetMaps(GetReactantMol());
                if (maps != null)
                {
                    vfLibSolutions.AddRange(maps);
                }
                SetVFMappings(false, query);
            }
            SetVFMappings(false, query);
        }
        public void TestCompiledQuery()
        {
            int n          = 50;
            int iterations = 100;

            var query  = QueryCompiler.Compile((Northwind nw, int i) => nw.OrderDetails.Where(d => d.OrderID > i).Take(n));
            var result = query(db, 0).ToList();

            var compiledTime = RunTimedTest(iterations, i =>
            {
                var list = query(db, i).ToList();
            });

            var adoTime = RunTimedTest(iterations, i =>
            {
                var cmd = this.GetProvider().Connection.CreateCommand();

                cmd.CommandText = "SELECT TOP (@p0) OrderID, ProductID FROM [Order Details] WHERE OrderID > @p1";
                //cmd.CommandText = "PARAMETERS p1 int; SELECT TOP 50 OrderID, ProductID FROM [Order Details] WHERE OrderID > p1";

                var p0           = cmd.CreateParameter();
                p0.ParameterName = "p0";
                p0.Value         = n;
                cmd.Parameters.Add(p0);

                var p1           = cmd.CreateParameter();
                p1.ParameterName = "p1";
                p1.Value         = i;
                cmd.Parameters.Add(p1);

                var reader = cmd.ExecuteReader();

                var list = new List <object>();
                while (reader.Read())
                {
                    var orderId   = reader.IsDBNull(0) ? default(int) : reader.GetInt32(0);
                    var productId = reader.IsDBNull(1) ? default(int) : reader.GetInt32(1);
                    list.Add(new OrderDetail {
                        OrderID = orderId, ProductID = productId
                    });
                }

                reader.Close();
            });

            Console.WriteLine("Direct ADO : {0}", adoTime);
            Console.WriteLine("Compiled IQ: {0}  {1:#.##}x vs ADO", compiledTime, compiledTime / adoTime);
        }
Exemple #37
0
        private async void CheckCompile(string source)
        {
            try
            {
                var newFilter = await Task.Run(() => QueryCompiler.Compile(source));

                newFilter.GetEvaluator(); // validate types
                _filterQuery = newFilter;
                FoundError   = false;
            }
            catch (Exception ex)
            {
                FoundError       = true;
                ExceptionMessage = ex.Message;
            }
        }
Exemple #38
0
        internal CouchDatabase(IFlurlClient flurlClient, CouchOptions options, QueryContext queryContext)
        {
            _flurlClient  = flurlClient;
            _options      = options;
            _queryContext = queryContext;

            var queryOptimizer  = new QueryOptimizer();
            var queryTranslator = new QueryTranslator(options);
            var querySender     = new QuerySender(flurlClient, queryContext);
            var queryCompiler   = new QueryCompiler(queryOptimizer, queryTranslator, querySender);

            _queryProvider = new CouchQueryProvider(queryCompiler);

            Security       = new CouchSecurity(NewRequest);
            LocalDocuments = new LocalDocuments(flurlClient, queryContext);
        }
        public void QueryCompilerCompileValuesTest()
        {
            var part = new QueryPart(OperationType.Values, null);
            var parts = new QueryPartsContainer();
            parts.Add(part);

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, " VALUES ()");
        }
        public void QueryCompilerCompileUpdateWithUpdateValueTest()
        {
            var part = new DelegateQueryPart(OperationType.Update, () => "Table");
            part.Add(new DelegateQueryPart(OperationType.UpdateValue, () => "Field1=Value1, "));
            part.Add(new DelegateQueryPart(OperationType.UpdateValue, () => "Field2=Value2"));
            var parts = new QueryPartsContainer();
            parts.Add(part);

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, "UPDATE Table SET Field1=Value1, Field2=Value2");
        }
        public void QueryCompilerCompileUpdateValueWithValueCollectionTest()
        {
            var part = new ValueCollectionQueryPart(OperationType.UpdateValue);
            part.AddValue(KeyValuePart.MemberName, "Member");
            part.AddValue(KeyValuePart.Value, "Value");
            var parts = new QueryPartsContainer();
            parts.Add(part);

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, "Member = Value");
        }
        public void SqlServer_QueryCompiler_Compile_ColumnMultipleTest()
        {
            var part = new QueryPart(OperationType.None);

            var part1 = new ValueCollectionQueryPart(OperationType.Column);
            part1.AddValue(KeyValuePart.MemberName, "ColumnName1");
            part1.AddValue(KeyValuePart.MemberType, "int");
            part1.AddValue(KeyValuePart.Nullable, false.ToString());

            part.Add(part1);

            var part2 = new ValueCollectionQueryPart(OperationType.Column);
            part2.AddValue(KeyValuePart.MemberName, "ColumnName2");
            part2.AddValue(KeyValuePart.MemberType, "VARCHAR(20)");
            part2.AddValue(KeyValuePart.Nullable, true.ToString());

            part.Add(part2);

            var parts = new QueryPartsContainer();
            parts.Add(part);

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, "ColumnName1 int NOT NULL, ColumnName2 VARCHAR(20)");
        }
        public void SqlServer_QueryCompiler_Compile_ParameterTest()
        {
            var part = new QueryPart(OperationType.None, null);
            part.Add(new DelegateQueryPart(OperationType.Parameter, () => "Param=value"));
            var parts = new QueryPartsContainer();
            parts.Add(part);

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, "Param=value");
        }
        public void QueryCompilerCompileOrderByTest()
        {
            var part = new DelegateQueryPart(OperationType.OrderBy, () => "Field");
            var parts = new QueryPartsContainer();
            parts.Add(part);

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, " \r\nORDER BY Field ASC");
        }
        public void QueryCompilerCompileSelectTest()
        {
            var parts = new QueryPartsContainer();
            parts.Add(new QueryPart(OperationType.Select, null));

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, "SELECT");
        }
        public void QueryCompilerCompileJoinithAliasTest()
        {
            var part = new EntityPart(OperationType.Join, entity: "Table", entityAlias: "Alias");
            var parts = new QueryPartsContainer();
            parts.Add(part);

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, " \r\nJOIN Table Alias");
        }
        public void SqlServer_QueryCompiler_Compile_AlterTableTest()
        {
            var part = new DelegateQueryPart(OperationType.AlterTable, () => "Table");
            var parts = new QueryPartsContainer();
            parts.Add(part);

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, "ALTER TABLE Table ");
        }
        public void QueryCompilerCompileInsertWithInsertMemberTest()
        {
            var part = new DelegateQueryPart(OperationType.Insert, () => "TableName");
            part.Add(new DelegateQueryPart(OperationType.InsertMember, () => "Field1"));
            part.Add(new DelegateQueryPart(OperationType.InsertMember, () => "Field2"));
            var parts = new QueryPartsContainer();
            parts.Add(part);

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, "INSERT INTO TableName (Field1, Field2)");
        }
        public void QueryCompilerCompileIgnoreTest()
        {
            var select = new QueryPart(OperationType.IgnoreColumn);
            var parts = new QueryPartsContainer();
            parts.Add(select);

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, string.Empty);
        }
        public void QueryCompilerCompileFromTest()
        {
            var part = new EntityPart(OperationType.From, entity: "Table");
            var parts = new QueryPartsContainer();
            parts.Add(part);

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, " \r\nFROM Table");
        }
        public void QueryCompilerCompileValuesWithInsertValuesTest()
        {
            var part = new QueryPart(OperationType.Values);
            part.Add(new DelegateQueryPart(OperationType.InsertValue, () => "Field1"));
            part.Add(new DelegateQueryPart(OperationType.InsertValue, () => "Field2"));
            var parts = new QueryPartsContainer();
            parts.Add(part);

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, " VALUES (Field1, Field2)");
        }
        public void QueryCompilerCompileSelectWithIncludeTest()
        {
            var select = new QueryPart(OperationType.Select);
            select.Add(new FieldQueryPart("Name", "Alias") { OperationType = OperationType.Include });
            var parts = new QueryPartsContainer();
            parts.Add(select);

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, "SELECT Name AS Alias");
        }
        public void SqlServer_QueryCompiler_Compile_PrimaryKeyWithMultipleColumnsTest()
        {
            var part = new QueryPart(OperationType.PrimaryKey);
            part.Add(new DelegateQueryPart(OperationType.Column, () => "Column1"));
            part.Add(new DelegateQueryPart(OperationType.Column, () => "Column2"));

            var parts = new QueryPartsContainer();
            parts.Add(part);

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, "PRIMARY KEY (Column1, Column2)");
        }
        public void QueryCompilerCompileSimpleJoinTest()
        {
            var part = new DelegateQueryPart(OperationType.Join, () => "Table");
            var parts = new QueryPartsContainer();
            parts.Add(part);

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, " \r\nJOIN Table");
        }
        public void QueryCompilerCompileFieldWithAliasAndTableAndTableAliasDefinitionTest()
        {
            var part = new QueryPart(OperationType.None);
            part.Add(new FieldQueryPart("Name", "Alias", entity: "Entity", entityalias: "EntityAlias"));
            var parts = new QueryPartsContainer();
            parts.Add(part);

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, " EntityAlias.Name AS Alias");
        }
        public void SqlServer_QueryCompiler_Compile_SelectWithOutputParameterSelectTest()
        {
            var part = new QueryPart(OperationType.Select);
            part.Add(new DelegateQueryPart(OperationType.OutParameterSelect, () => "Param1"));
            part.Add(new DelegateQueryPart(OperationType.OutParameterSelect, () => "Param2"));
            var parts = new QueryPartsContainer();
            parts.Add(part);

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, "SELECT @Param1 AS Param1, @Param2 AS Param2");
        }
        public void SqlServer_QueryCompiler_Compile_OutputParameterSetTest()
        {
            var part = new DelegateQueryPart(OperationType.OutParameterSet, () => "ParamName=1");
            var parts = new QueryPartsContainer();
            parts.Add(part);

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, "SET @ParamName=1\r\n");
        }
        public void QueryCompilerCompileThenByDescTest()
        {
            var part = new DelegateQueryPart(OperationType.ThenByDesc, () => "Field");
            var parts = new QueryPartsContainer();
            parts.Add(part);

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, ", Field DESC");
        }
        public void SqlServer_QueryCompiler_Compile_ProcedureTest()
        {
            var part = new DelegateQueryPart(OperationType.Procedure, () => "ProcName");
            var parts = new QueryPartsContainer();
            parts.Add(part);

            var compiler = new QueryCompiler();
            var query = compiler.Compile(parts, new InterceptorCollection());

            Assert.AreEqual(query.QueryString, "EXEC ProcName ");
        }
 public ConnectionProvider()
     : base(null, null)
 {
     CheckCallbackCall = true;
     QueryCompiler = new QueryCompiler();
 }