Example #1
0
        /// <summary>
        /// Include an entity
        /// </summary>
        /// <typeparam name="TBaseEntity">The base entity type</typeparam>
        /// <param name="query">The query</param>
        /// <param name="joinExpression">The expression to specify the include property
        ///     and join properties, should be something like
        ///         baseEntity => baseEntity.NavigationProperty.JoinProperty = baseEntity.Poperty</param>
        /// <param name="selectPrefix">The select prefix</param>
        /// <param name="useLeftJoin">Indicate whether to use left join</param>
        /// <returns></returns>
        public BaseDal Include <TBaseEntity>(Query query,
                                             Expression <Func <TBaseEntity, bool> > joinExpression,
                                             string selectPrefix = "",
                                             bool useLeftJoin    = false)
        {
            var equalExpressions = new MultipleIncludeVisitor()
                                   .GetEqualExpressions(joinExpression.Body as BinaryExpression);

            foreach (var equalExpression in equalExpressions)
            {
                var(leftSideProps, rightSideProps, navigationProperty) = new IncludeVisitor()
                                                                         .VisitEqualExpression(joinExpression.Body as BinaryExpression);
                if (leftSideProps.Contains(navigationProperty))
                {
                    // Navigate property is on the left side, swap to make sure the subsequent code works
                    (leftSideProps, rightSideProps) = (rightSideProps, leftSideProps);
                }
                var lastRightSideProp   = rightSideProps.Last();
                var baseTableColumnName = GetColumnName(leftSideProps.Last());
                var joinTableColumnName = GetColumnName(lastRightSideProp);
                var prefixPropName      = navigationProperty.Name;
                selectPrefix = selectPrefix.IsNullOrEmpty() ?
                               prefixPropName :
                               $"{selectPrefix}_{prefixPropName}";
                Include(query,
                        baseEntityType: typeof(TBaseEntity),
                        joinEntityType: lastRightSideProp.DeclaringType,
                        selectPrefix: selectPrefix,
                        joinTableColumnName: joinTableColumnName,
                        baseTableColumnName: baseTableColumnName,
                        useLeftJoin: useLeftJoin);
            }

            return(this);
        }
        public async Task CanSkipIncludes()
        {
            var parser = new LuceneQueryParser();
            var result = await parser.ParseAsync("outter @include:other @skipped:(other stuff @include:other)");

            var includes = new Dictionary <string, string> {
                { "other", "field:value" },
                { "nested", "field:value @include:other" }
            };
            var resolved = await IncludeVisitor.RunAsync(result, includes, shouldSkipInclude : (n, ctx) => true);

            Assert.Equal("outter @include:other @skipped:(other stuff @include:other)", resolved.ToString());

            resolved = await IncludeVisitor.RunAsync(result, includes, shouldSkipInclude : ShouldSkipInclude);

            Assert.Equal("outter (field:value) @skipped:(other stuff @include:other)", resolved.ToString());

            resolved = await IncludeVisitor.RunAsync(result, includes, shouldSkipInclude : (n, ctx) => !ShouldSkipInclude(n, ctx));

            Assert.Equal("outter (field:value) @skipped:(other stuff (field:value))", resolved.ToString());

            var nestedResult = await parser.ParseAsync("outter @skipped:(other stuff @include:nested)");

            resolved = await IncludeVisitor.RunAsync(nestedResult, includes, shouldSkipInclude : ShouldSkipInclude);

            Assert.Equal("outter @skipped:(other stuff @include:nested)", resolved.ToString());
        }
Example #3
0
 static void Main(string[] args)
 {
     using (var ctx = new TestDB())
     {
         var query = ctx.Persons.Include(p => p.Parents).Include(p => p.Children);
         // includes[0] = "Parents"
         // includes[1] = "Children"
         var includes = IncludeVisitor.GetIncludes(query.Expression);
     }
 }
Example #4
0
        public void Visit_ExpressionWithObject_ShouldSetCorrectPath()
        {
            var visitor = new IncludeVisitor();
            Expression <Func <Book, Book> > expression = (book) => book.Author !.FavouriteBook !;

            visitor.Visit(expression);

            var expectedPath = $"{nameof(Book.Author)}.{nameof(Person.FavouriteBook)}";

            Assert.Equal(expectedPath, visitor.Path);
        }
Example #5
0
        public void Should_SetPath_IfPassedExpressionWithFunction()
        {
            var visitor = new IncludeVisitor();
            Expression <Func <Book, string> > expression = (book) => book.Author.GetQuote();

            visitor.Visit(expression);

            var expectedPath = nameof(Book.Author);

            Assert.Equal(expectedPath, visitor.Path);
        }
Example #6
0
        public void Should_SetPath_IfPassedExpressionWithCollection()
        {
            var visitor = new IncludeVisitor();
            Expression <Func <Book, List <Person> > > expression = (book) => book.Author.Friends;

            visitor.Visit(expression);

            var expectedPath = $"{nameof(Book.Author)}.{nameof(Person.Friends)}";

            Assert.Equal(expectedPath, visitor.Path);
        }
Example #7
0
        public void Should_SetPath_IfPassedExpressionWithSimpleType()
        {
            var visitor = new IncludeVisitor();
            Expression <Func <Book, string> > expression = (book) => book.Author.FirstName;

            visitor.Visit(expression);

            var expectedPath = $"{nameof(Book.Author)}.{nameof(Person.FirstName)}";

            Assert.Equal(expectedPath, visitor.Path);
        }
Example #8
0
        public void Should_SetPath_IfPassedExpressionWithObject()
        {
            var visitor = new IncludeVisitor();
            Expression <Func <Book, Book> > expression = (book) => book.Author.FavouriteBook;

            visitor.Visit(expression);

            var expectedPath = $"{nameof(Book.Author)}.{nameof(Person.FavouriteBook)}";

            Assert.Equal(expectedPath, visitor.Path);
        }
        public async Task CanExpandIncludesWithOtherCriteriaAndGroupingAsync()
        {
            var parser = new LuceneQueryParser();
            var result = await parser.ParseAsync("field1:value1 OR (@include:other field2:value2)");

            var includes = new Dictionary <string, string> {
                { "other", "field:value" }
            };
            var resolved = await IncludeVisitor.RunAsync(result, includes);

            Assert.Equal("field1:value1 OR ((field:value) field2:value2)", resolved.ToString());
        }
        public async Task CanExpandIncludesAsync()
        {
            var parser = new LuceneQueryParser();
            var result = await parser.ParseAsync("@include:other");

            var includes = new Dictionary <string, string> {
                { "other", "field:value" }
            };
            var resolved = await IncludeVisitor.RunAsync(result, includes);

            Assert.Equal("(field:value)", resolved.ToString());
        }
Example #11
0
        public override IList <Node> IncludeFile(VisitorContext context, string path, string parse)
        {
            var existingPath = context.ViewPath;

            var directoryPath = Path.GetDirectoryName(context.ViewPath);

            var relativePath = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);

            while (relativePath.StartsWith(string.Format("..{0}", Path.DirectorySeparatorChar)))
            {
                directoryPath = Path.GetDirectoryName(directoryPath);
                relativePath  = relativePath.Substring(3);
            }
            context.ViewPath = Path.Combine(directoryPath, relativePath);

            var sourceContext = CreateSourceContext(context.ViewPath, context.ViewFolder);

            switch (parse)
            {
            case "text":
                var encoded = sourceContext.Content
                              .Replace("&", "&amp;")
                              .Replace("<", "&lt;")
                              .Replace(">", "&gt;");
                return(new[] { new TextNode(encoded) });

            case "html":
                return(new[] { new TextNode(sourceContext.Content) });
            }


            var position = new Position(sourceContext);
            var result   = _grammar.Nodes(position);

            if (result.Rest.PotentialLength() != 0)
            {
                ThrowParseException(context.ViewPath, position, result.Rest);
            }
            context.Paint = context.Paint.Union(result.Rest.GetPaint());

            var namespaceVisitor = new NamespaceVisitor(context);

            namespaceVisitor.Accept(result.Value);

            var includeVisitor = new IncludeVisitor(context);

            includeVisitor.Accept(namespaceVisitor.Nodes);

            context.ViewPath = existingPath;
            return(includeVisitor.Nodes);
        }
        void GenerateCode(AstBuilder astBuilder, ITextOutput output)
        {
            var syntaxTree = astBuilder.SyntaxTree;

            syntaxTree.AcceptVisitor(new InsertParenthesesVisitor {
                InsertParenthesesForReadability = true
            });

            // generate AST
            var transform = new CSharpToHpp();

            transform.Run(syntaxTree);

            var include = new IncludeVisitor();

            syntaxTree.AcceptVisitor(include);

            // generate include
            string include_name = "__" + include.namespacename.ToUpper() + "_" + include.typename.ToUpper() + "_H__";

            output.WriteLine("#ifndef " + include_name);
            output.WriteLine("#define " + include_name);
            output.WriteLine();

            if (include.foundClass)
            {
                output.WriteLine("#include <QuantKit/quantkit_global.h>");
                output.WriteLine("#include <QString>");
                output.WriteLine("#include <QDateTime>");
                output.WriteLine("#include <QSharedDataPointer>");
                output.WriteLine();
                output.WriteLine("#include \"qt_extension.h\"");
                output.WriteLine();
                output.WriteLine();
            }

            //Generate hpp Code
            var outputFormatter = new TextOutputFormatter(output)
            {
                FoldBraces = true
            };
            var formattingPolicy = FormattingOptionsFactory.CreateAllman();

            syntaxTree.AcceptVisitor(new HppOutputVisitor(outputFormatter, formattingPolicy));

            // generate endif
            output.WriteLine();
            output.WriteLine("#endif // " + include_name);
        }
Example #13
0
        /// <summary>
        /// Include an entity
        /// </summary>
        /// <typeparam name="TBaseEntity">The base entity type</typeparam>
        /// <typeparam name="TJoinEntity">The join entity type</typeparam>
        /// <param name="query">The query</param>
        /// <param name="selectPrefix">The select prefix</param>
        /// <param name="joinExpression">The expression to specify join properties,
        ///     should be something like
        ///         () => baseEntity.BaseJoinColumn = joinEntity.JoinColumn</param>
        /// <param name="useLeftJoin">Indicate whether to use left join</param>
        /// <returns></returns>
        public BaseDal Include <TBaseEntity, TJoinEntity>(Query query,
                                                          Expression <Func <TBaseEntity, TJoinEntity, bool> > joinExpression,
                                                          string selectPrefix,
                                                          bool useLeftJoin = false)
        {
            var(leftSideProps, rightSideProps, _) = new IncludeVisitor()
                                                    .VisitEqualExpression(joinExpression.Body as BinaryExpression);
            var baseTableColumnName = GetColumnName(leftSideProps.Last());
            var joinTableColumnName = GetColumnName(rightSideProps.Last());

            return(Include(query,
                           baseEntityType: typeof(TBaseEntity),
                           joinEntityType: typeof(TJoinEntity),
                           selectPrefix: selectPrefix,
                           joinTableColumnName: joinTableColumnName,
                           baseTableColumnName: baseTableColumnName,
                           useLeftJoin: useLeftJoin));
        }
        public override IList <Node> IncludeFile(VisitorContext context, string path, string parse)
        {
            string viewPath      = context.ViewPath;
            string directoryName = Path.GetDirectoryName(context.ViewPath);
            string str3          = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);

            while (str3.StartsWith(string.Format("..{0}", Path.DirectorySeparatorChar)))
            {
                directoryName = Path.GetDirectoryName(directoryName);
                str3          = str3.Substring(3);
            }
            context.ViewPath = Path.Combine(directoryName, str3);
            SourceContext sourceContext = AbstractSyntaxProvider.CreateSourceContext(context.ViewPath, context.ViewFolder);

            switch (parse)
            {
            case "text":
            {
                string text = sourceContext.Content.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;");
                return(new TextNode[] { new TextNode(text) });
            }

            case "html":
                return(new TextNode[] { new TextNode(sourceContext.Content) });
            }
            Position position = new Position(sourceContext);
            ParseResult <IList <Node> > result = this._grammar.Nodes(position);

            if (result.Rest.PotentialLength() != 0)
            {
                base.ThrowParseException(context.ViewPath, position, result.Rest);
            }
            context.Paint = context.Paint.Union <Paint>(result.Rest.GetPaint());
            NamespaceVisitor visitor = new NamespaceVisitor(context);

            visitor.Accept(result.Value);
            IncludeVisitor visitor2 = new IncludeVisitor(context);

            visitor2.Accept(visitor.Nodes);
            context.ViewPath = viewPath;
            return(visitor2.Nodes);
        }
Example #15
0
        void GenerateCode(AstBuilder astBuilder, ITextOutput output)
        {
            var syntaxTree = astBuilder.SyntaxTree;

            syntaxTree.AcceptVisitor(new InsertParenthesesVisitor {
                InsertParenthesesForReadability = true
            });

            // generate AST
            var transform = new CSharpToCpp();

            transform.Run(syntaxTree);

            var include = new IncludeVisitor();

            syntaxTree.AcceptVisitor(include);

            // generate include
            string include_name = include.typename + ".h";

            output.WriteLine("#include <QuantKit/Event/" + include_name + ">");
            output.WriteLine("#include <QuantKit/EventType.h>");
            output.WriteLine("#include \"../Event_p.h\"");
            output.WriteLine("#include \"DataObject_p.h\"");
            output.WriteLine("#include \"Tick_p.h\"");
            output.WriteLine();

            //Generate cpp Code
            var outputFormatter = new TextOutputFormatter(output)
            {
                FoldBraces = true
            };
            var formattingPolicy = FormattingOptionsFactory.CreateAllman();

            syntaxTree.AcceptVisitor(new PrivateHppOutputVisitor(outputFormatter, formattingPolicy));
            syntaxTree.AcceptVisitor(new PrivateCppOutputVisitor(outputFormatter, formattingPolicy));
            syntaxTree.AcceptVisitor(new CppOutputVisitor(outputFormatter, formattingPolicy));

            // generate endif
            output.WriteLine();
        }
Example #16
0
        private IList <IIncludePlan> readBodyClauses(QueryModel queryModel, IDocumentStorage storage)
        {
            var includes = new List <IIncludePlan>();

            if (!(Model.SelectClause.Selector is QuerySourceReferenceExpression))
            {
                var visitor = new IncludeVisitor(includes);
                visitor.Visit(Model.SelectClause.Selector);
            }

            for (var i = 0; i < queryModel.BodyClauses.Count; i++)
            {
                var clause = queryModel.BodyClauses[i];
                switch (clause)
                {
                case WhereClause where:
                    CurrentStatement.WhereClauses.Add(@where);
                    break;

                case OrderByClause orderBy:
                    CurrentStatement.Orderings.AddRange(orderBy.Orderings);
                    break;

                case AdditionalFromClause additional:
                    var isComplex       = queryModel.BodyClauses.Count > i + 1 || queryModel.ResultOperators.Any() || includes.Any();
                    var elementType     = additional.ItemType;
                    var collectionField = storage.Fields.FieldFor(additional.FromExpression);

                    CurrentStatement = CurrentStatement.ToSelectMany(collectionField, _session, isComplex, elementType);


                    break;

                default:
                    throw new NotSupportedException();
                }
            }

            return(includes);
        }
Example #17
0
        public override IList<Node> IncludeFile(VisitorContext context, string path, string parse)
        {
            var existingPath = context.ViewPath;

            var directoryPath = Path.GetDirectoryName(context.ViewPath);

            var relativePath = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
            while (relativePath.StartsWith(string.Format("..{0}", Path.DirectorySeparatorChar)))
            {
                directoryPath = Path.GetDirectoryName(directoryPath);
                relativePath = relativePath.Substring(3);
            }
            context.ViewPath = Path.Combine(directoryPath, relativePath);

            var sourceContext = CreateSourceContext(context.ViewPath, context.ViewFolder);

            switch (parse)
            {
                case "text":
                    var encoded = sourceContext.Content
                        .Replace("&", "&amp;")
                        .Replace("<", "&lt;")
                        .Replace(">", "&gt;");
                    return new[] {new TextNode(encoded)};
                case "html":
                    return new[] {new TextNode(sourceContext.Content)};
            }

            var position = new Position(sourceContext);
            var result = _grammar.Nodes(position);
            if (result.Rest.PotentialLength() != 0)
            {
                ThrowParseException(context.ViewPath, position, result.Rest);
            }
            context.Paint = context.Paint.Union(result.Rest.GetPaint());

            var namespaceVisitor = new NamespaceVisitor(context);
            namespaceVisitor.Accept(result.Value);

            var includeVisitor = new IncludeVisitor(context);
            includeVisitor.Accept(namespaceVisitor.Nodes);

            context.ViewPath = existingPath;
            return includeVisitor.Nodes;
        }
Example #18
0
 static IncludeVisitor()
 {
     _visitor = new IncludeVisitor();
 }