Exemplo n.º 1
0
        internal static FragmentEventType GetFragmentType(
            Schema schema,
            string propertyName,
            IDictionary <string, PropertySetDescriptorItem> propertyItems,
            EventAdapterService eventAdapterService)
        {
            string unescapePropName        = ASTUtil.UnescapeDot(propertyName);
            PropertySetDescriptorItem item = propertyItems.Get(unescapePropName);

            if (item != null)
            {
                return(item.FragmentEventType);
            }

            Property            property = PropertyParser.ParseAndWalkLaxToSimple(propertyName);
            AvroFieldDescriptor desc     = AvroFieldUtil.FieldForProperty(schema, property);

            if (desc == null)
            {
                return(null);
            }
            if (desc.IsDynamic)
            {
                return(null);
            }
            Schema fieldSchemaByAccess = desc.Field.Schema;

            if (desc.IsAccessedByIndex)
            {
                fieldSchemaByAccess = fieldSchemaByAccess.GetElementType();
            }
            return(GetFragmentEventTypeForField(fieldSchemaByAccess, eventAdapterService));
        }
Exemplo n.º 2
0
        public static StatementSpecRaw CompileEPL(
            string eplStatement,
            string eplStatementForErrorMsg,
            bool addPleaseCheck,
            string statementName,
            SelectClauseStreamSelectorEnum defaultStreamSelector,
            EngineImportService engineImportService,
            VariableService variableService,
            SchedulingService schedulingService,
            string engineURI,
            ConfigurationInformation configSnapshot,
            PatternNodeFactory patternNodeFactory,
            ContextManagementService contextManagementService,
            ExprDeclaredService exprDeclaredService,
            TableService tableService)
        {
            if (Log.IsDebugEnabled)
            {
                Log.Debug(".createEPLStmt statementName=" + statementName + " eplStatement=" + eplStatement);
            }

            ParseResult parseResult = ParseHelper.Parse(
                eplStatement, eplStatementForErrorMsg, addPleaseCheck, EPLParseRule, true);
            ITree ast = parseResult.Tree;

            var walker = new EPLTreeWalkerListener(
                parseResult.TokenStream, engineImportService, variableService, schedulingService, defaultStreamSelector,
                engineURI, configSnapshot, patternNodeFactory, contextManagementService, parseResult.Scripts,
                exprDeclaredService, tableService);

            try
            {
                ParseHelper.Walk(ast, walker, eplStatement, eplStatementForErrorMsg);
            }
            catch (ASTWalkException ex)
            {
                Log.Error(".createEPL Error validating expression", ex);
                throw new EPStatementException(ex.Message, ex, eplStatementForErrorMsg);
            }
            catch (EPStatementSyntaxException ex)
            {
                throw;
            }
            catch (Exception ex)
            {
                string message = "Error in expression";
                Log.Debug(message, ex);
                throw new EPStatementException(GetNullableErrortext(message, ex.Message), ex, eplStatementForErrorMsg);
            }

            if (Log.IsDebugEnabled)
            {
                ASTUtil.DumpAST(ast);
            }

            StatementSpecRaw raw = walker.StatementSpec;

            raw.ExpressionNoAnnotations = parseResult.ExpressionWithoutAnnotations;
            return(raw);
        }
Exemplo n.º 3
0
        private static String MakeProperty(EsperEPL2GrammarParser.EventPropertyAtomicContext ctx, String defaultNamespacePrefix)
        {
            String prefix = "";

            if (defaultNamespacePrefix != null)
            {
                prefix = defaultNamespacePrefix + ":";
            }

            String unescapedIdent = ASTUtil.UnescapeDot(ctx.eventPropertyIdent().GetText());

            if (ctx.lb != null)
            {
                int index         = IntValue.ParseString(ctx.number().GetText());
                int xPathPosition = index + 1;
                return('/' + prefix + unescapedIdent + "[position() = " + xPathPosition + ']');
            }

            if (ctx.lp != null)
            {
                String key = StringValue.ParseString(ctx.s.Text);
                return('/' + prefix + unescapedIdent + "[@id='" + key + "']");
            }

            return('/' + prefix + unescapedIdent);
        }
Exemplo n.º 4
0
 public static void DisplayAST(ITree ast)
 {
     Log.Debug(".displayAST...");
     if (Log.IsDebugEnabled)
     {
         ASTUtil.DumpAST(ast);
     }
 }
Exemplo n.º 5
0
 /// <summary>
 /// Locate the select clause that is part of this select statement.
 /// Note, that this might return null as derived select clauses (i.e., no
 /// select clause at the HQL-level) get generated much later than when we
 /// get created; thus it depends upon lifecycle.
 /// </summary>
 /// <returns>Our select clause, or null.</returns>
 public SelectClause GetSelectClause()
 {
     // Due to the complexity in initializing the SelectClause, do not generate one here.
     // If it is not found; simply return null...
     //
     // Also, do not cache since it gets generated well after we are created.
     return(( SelectClause )ASTUtil.FindTypeInChildren(this, HqlSqlWalker.SELECT_CLAUSE));
 }
Exemplo n.º 6
0
 public static void ToPrecedenceFreeEPL(TextWriter writer, string streamOrPropertyName, string unresolvedPropertyName)
 {
     if (streamOrPropertyName != null)
     {
         writer.Write(ASTUtil.UnescapeDot(streamOrPropertyName));
         writer.Write('.');
     }
     writer.Write(ASTUtil.UnescapeDot(PropertyParser.UnescapeBacktick(unresolvedPropertyName)));
 }
Exemplo n.º 7
0
        public Type GetPropertyType(string propertyName)
        {
            PropertySetDescriptorItem item = _propertyItems.Get(ASTUtil.UnescapeDot(propertyName));
            if (item != null)
            {
                return item.SimplePropertyType;
            }

            Property property = PropertyParser.ParseAndWalkLaxToSimple(propertyName);
            return AvroPropertyUtil.PropertyType(_avroSchema, property);
        }
Exemplo n.º 8
0
        public Type GetPropertyType(String propertyName)
        {
            RevisionPropertyTypeDesc desc = _propertyDesc.Get(propertyName);

            if (desc != null)
            {
                if (desc.PropertyType is Type)
                {
                    return((Type)desc.PropertyType);
                }
                return(null);
            }

            // dynamic property names note allowed
            if (propertyName.IndexOf('?') != -1)
            {
                return(null);
            }

            // see if this is a nested property
            int index = ASTUtil.UnescapedIndexOfDot(propertyName);

            if (index == -1)
            {
                return(null);
            }

            // Map event types allow 2 types of properties inside:
            //   - a property that is a Java object is interrogated via bean property getters and BeanEventType
            //   - a property that is a Map itself is interrogated via map property getters

            // Take apart the nested property into a map key and a nested value class property name
            String propertyMap    = ASTUtil.UnescapeDot(propertyName.Substring(0, index));
            String propertyNested = propertyName.Substring(index + 1);

            desc = _propertyDesc.Get(propertyMap);
            if (desc == null)
            {
                return(null);  // prefix not a known property
            }

            else if (desc.PropertyType is Type)
            {
                Type      simpleClass     = (Type)desc.PropertyType;
                EventType nestedEventType = _eventAdapterService.AddBeanType(simpleClass.FullName, simpleClass, false, false, false);
                return(nestedEventType.GetPropertyType(propertyNested));
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 9
0
            private void HandleDotStructure(IASTNode dotStructureRoot)
            {
                var expression = ASTUtil.GetPathText(dotStructureRoot);

                var constant = ReflectHelper.GetConstantValue(expression, _sfi);

                if (constant != null)
                {
                    dotStructureRoot.ClearChildren();
                    dotStructureRoot.Type = HqlSqlWalker.JAVA_CONSTANT;
                    dotStructureRoot.Text = expression;
                }
            }
Exemplo n.º 10
0
        public PropertyResolutionDescriptor ResolveByStreamAndPropName(String streamAndPropertyName, bool obtainFragment)
        {
            if (streamAndPropertyName == null)
            {
                throw new ArgumentException("Null stream and property name");
            }

            PropertyResolutionDescriptor desc;

            try
            {
                // first try to resolve as a property name
                desc = FindByPropertyName(streamAndPropertyName, obtainFragment);
            }
            catch (PropertyNotFoundException ex)
            {
                // Attempt to resolve by extracting a stream name
                var index = ASTUtil.UnescapedIndexOfDot(streamAndPropertyName);
                if (index == -1)
                {
                    throw;
                }
                var streamName   = streamAndPropertyName.Substring(0, index);
                var propertyName = streamAndPropertyName.Substring(index + 1);
                try
                {
                    // try to resolve a stream and property name
                    desc = FindByStreamAndEngineName(propertyName, streamName, false, obtainFragment);
                }
                catch (StreamNotFoundException)
                {
                    // Consider the engine URI as a further prefix
                    var propertyNoEnginePair = GetIsEngineQualified(propertyName, streamName);
                    if (propertyNoEnginePair == null)
                    {
                        throw ex;
                    }
                    try
                    {
                        return(FindByStreamNameOnly(propertyNoEnginePair.First, propertyNoEnginePair.Second, false, obtainFragment));
                    }
                    catch (StreamNotFoundException)
                    {
                        throw ex;
                    }
                }
                return(desc);
            }

            return(desc);
        }
Exemplo n.º 11
0
 private IQueryable ResolveEntityJoinReferencedPersister(IASTNode path)
 {
     if (path.Type == IDENT)
     {
         var pathIdentNode = (IdentNode)path;
         return(SessionFactoryHelper.FindQueryableUsingImports(pathIdentNode.Path));
     }
     else if (path.Type == DOT)
     {
         var pathText = ASTUtil.GetPathText(path);
         return(SessionFactoryHelper.FindQueryableUsingImports(pathText));
     }
     return(null);
 }
Exemplo n.º 12
0
        public bool IsProperty(String propertyName)
        {
            var propertyType = GetPropertyType(propertyName);

            if (propertyType == null)
            {
                // Could be a native null type, such as "insert into A select null as field..."
                if (_propertyItems.ContainsKey(ASTUtil.UnescapeDot(propertyName)))
                {
                    return(true);
                }
            }
            return(propertyType != null);
        }
Exemplo n.º 13
0
 private IQueryable ResolveEntityJoinReferencedPersister(IASTNode path)
 {
     if (path.Type == IDENT)
     {
         var pathIdentNode = (IdentNode)path;
         // Since IDENT node is not expected for implicit join path, we can throw on not found persister
         return((IQueryable)SessionFactoryHelper.RequireClassPersister(pathIdentNode.Path));
     }
     else if (path.Type == DOT)
     {
         var pathText = ASTUtil.GetPathText(path);
         return(SessionFactoryHelper.FindQueryableUsingImports(pathText));
     }
     return(null);
 }
Exemplo n.º 14
0
        private static Property MakeProperty(EsperEPL2GrammarParser.EventPropertyAtomicContext atomic, bool isRootedInDynamic)
        {
            var prop = ASTUtil.UnescapeDot(atomic.eventPropertyIdent().GetText());

            if (prop.Length == 0)
            {
                throw new PropertyAccessException("Invalid zero-length string provided as an event property name");
            }
            if (atomic.lb != null)
            {
                var index = IntValue.ParseString(atomic.ni.GetText());
                if (!isRootedInDynamic && atomic.q == null)
                {
                    return(new IndexedProperty(prop, index));
                }
                else
                {
                    return(new DynamicIndexedProperty(prop, index));
                }
            }
            else if (atomic.lp != null)
            {
                var key = StringValue.ParseString(atomic.s.Text);
                if (!isRootedInDynamic && atomic.q == null)
                {
                    return(new MappedProperty(prop, key));
                }
                else
                {
                    return(new DynamicMappedProperty(prop, key));
                }
            }
            else
            {
                if (!isRootedInDynamic && atomic.q1 == null)
                {
                    return(new SimpleProperty(prop));
                }
                else
                {
                    return(new DynamicSimpleProperty(prop));
                }
            }
        }
Exemplo n.º 15
0
        private Pair <String, String> GetIsEngineQualified(String propertyName, String streamName)
        {
            // If still not found, test for the stream name to contain the engine URI
            if (!streamName.Equals(_engineURIQualifier))
            {
                return(null);
            }

            var index = ASTUtil.UnescapedIndexOfDot(propertyName);

            if (index == -1)
            {
                return(null);
            }

            var streamNameNoEngine   = propertyName.Substring(0, index);
            var propertyNameNoEngine = propertyName.Substring(index + 1);

            return(new Pair <String, String>(propertyNameNoEngine, streamNameNoEngine));
        }
Exemplo n.º 16
0
        private Type DoResolvePropertyType(String propertyExpression, bool allowSimpleProperties)
        {
            // see if this is an indexed property
            int index = ASTUtil.UnescapedIndexOfDot(propertyExpression);

            if ((!allowSimpleProperties) && (index == -1))
            {
                // parse, can be an indexed property
                Property property = PropertyParser.ParseAndWalkLaxToSimple(propertyExpression);
                if (!property.IsDynamic)
                {
                    if (!(property is IndexedProperty))
                    {
                        return(null);
                    }
                    var indexedProp = (IndexedProperty)property;
                    EventPropertyDescriptor descriptor = PropertyDescriptorMap.Get(indexedProp.PropertyNameAtomic);
                    if (descriptor == null)
                    {
                        return(null);
                    }
                    return(descriptor.PropertyType);
                }
            }

            Property prop = PropertyParser.ParseAndWalkLaxToSimple(propertyExpression);

            if (prop.IsDynamic)
            {
                return(typeof(XmlNode));
            }

            SchemaItem item = prop.GetPropertyTypeSchema(_schemaModelRoot, EventAdapterService);

            if (item == null)
            {
                return(null);
            }

            return(SchemaUtil.ToReturnType(item));
        }
Exemplo n.º 17
0
            public void Visit(IASTNode node)
            {
                if (_dotRoot != null)
                {
                    // we are already processing a dot-structure
                    if (ASTUtil.IsSubtreeChild(_dotRoot, node))
                    {
                        // ignore it...
                        return;
                    }

                    // we are now at a new tree level
                    _dotRoot = null;
                }

                if (_dotRoot == null && node.Type == HqlSqlWalker.DOT)
                {
                    _dotRoot = node;
                    HandleDotStructure(_dotRoot);
                }
            }
Exemplo n.º 18
0
        public void ResolveSelectExpression()
        {
            if (Walker.IsShallowQuery || Walker.CurrentFromClause.IsSubQuery)
            {
                Resolve(false, true);
            }
            else
            {
                Resolve(true, false);
                IType type = GetDataType();

                if (type.IsEntityType)
                {
                    FromElement fromElement = FromElement;
                    fromElement.IncludeSubclasses = true;                     // Tell the destination fromElement to 'includeSubclasses'.

                    if (UseThetaStyleImplicitJoins)
                    {
                        fromElement.JoinSequence.SetUseThetaStyle(true);                                // Use theta style (for regression)

                        // Move the node up, after the origin node.
                        FromElement origin = fromElement.Origin;

                        if (origin != null)
                        {
                            ASTUtil.MakeSiblingOfParent(origin, fromElement);
                        }
                    }
                }
            }

            FromReferenceNode lhs = GetLhs();

            while (lhs != null)
            {
                CheckSubclassOrSuperclassPropertyReference(lhs, lhs.NextSibling.Text);
                lhs = (FromReferenceNode)lhs.GetChild(0);
            }
        }
Exemplo n.º 19
0
        public OrderByClause GetOrderByClause()
        {
            if (_orderByClause == null)
            {
                _orderByClause = LocateOrderByClause();

                // if there is no order by, make one
                if (_orderByClause == null)
                {
                    Log.Debug("getOrderByClause() : Creating a new ORDER BY clause");
                    _orderByClause = (OrderByClause)Walker.ASTFactory.CreateNode(HqlSqlWalker.ORDER, "ORDER");

                    // Find the WHERE; if there is no WHERE, find the FROM...
                    IASTNode prevSibling = ASTUtil.FindTypeInChildren(this, HqlSqlWalker.WHERE) ??
                                           ASTUtil.FindTypeInChildren(this, HqlSqlWalker.FROM);

                    // Now, inject the newly built ORDER BY into the tree
                    prevSibling.AddSibling(_orderByClause);
                }
            }
            return(_orderByClause);
        }
        private void ExtractOrders(IASTNode node)
        {
            if (this.rootClassMetadata == null)
            {
                throw new NotSupportedException("Ordering of sharded scalar HQL queries is not supported");
            }

            var child = node.GetFirstChild();

            while (child != null)
            {
                var propertyPath = ASTUtil.GetPathText(child);
                var aliasLength  = propertyPath.IndexOf('.');
                if (aliasLength >= 0)
                {
                    propertyPath = propertyPath.Substring(aliasLength + 1);
                }

                var isDescending = false;

                child = child.NextSibling;
                if (child != null)
                {
                    isDescending = child.Type == HqlSqlWalker.DESCENDING;
                    if (isDescending || child.Type == HqlSqlWalker.ASCENDING)
                    {
                        child = child.NextSibling;
                    }
                }

                this.exitOperationBuilder.Orders.Add(
                    new SortOrder(
                        o => propertyPath == this.rootClassMetadata.IdentifierPropertyName
                                                    ? this.rootClassMetadata.GetIdentifier(o)
                                                    : this.rootClassMetadata.GetPropertyValue(o, propertyPath),
                        isDescending));
            }
        }
Exemplo n.º 21
0
        private static StatementSpecRaw Walk(
            ParseResult parseResult,
            string epl,
            StatementSpecMapEnv mapEnv)
        {
            var ast = parseResult.Tree;

            var defaultStreamSelector =
                StatementSpecMapper.MapFromSODA(mapEnv.Configuration.Compiler.StreamSelection.DefaultStreamSelector);
            var walker = new EPLTreeWalkerListener(
                parseResult.TokenStream,
                defaultStreamSelector,
                parseResult.Scripts,
                parseResult.Classes,
                mapEnv);

            try {
                ParseHelper.Walk(ast, walker, epl, epl);
            }
            catch (ASTWalkException ex) {
                throw new StatementSpecCompileException(ex.Message, ex, epl);
            }
            catch (ValidationException ex) {
                throw new StatementSpecCompileException(ex.Message, ex, epl);
            }
            catch (Exception ex) {
                var message = "Invalid expression encountered";
                throw new StatementSpecCompileException(GetNullableErrortext(message, ex.Message), ex, epl);
            }

            if (Log.IsDebugEnabled)
            {
                ASTUtil.DumpAST(ast);
            }

            return(walker.StatementSpec);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Override the analysis of invocation expressions to verify that when a variable is dereferenced
        /// it has the appropriate annotated type.  This allows us to present an error when a possibly
        /// null value is unsafely dereferenced.  We still want to exercise the functionality present in the
        /// base class, so we conclude by calling the method which we are overridding here.
        /// </summary>
        /// <param name="context">The analysis context</param>
        /// <param name="invocationExpr">The invocation expression</param>
        internal override void AnalyzeInvocationExpr(SyntaxNodeAnalysisContext context, InvocationExpressionSyntax invocationExpr)
        {
            //We want to present a warning when we are dereferencing variable which may be null
            if (invocationExpr.Expression is MemberAccessExpressionSyntax memAccessExpr)
            {
                var identifierNameExpr = memAccessExpr.Expression;
                var symbol             = context.SemanticModel.GetSymbolInfo(memAccessExpr.Expression).Symbol;
                if (symbol != null)
                {
                    var dereferencedAttrs = symbol.GetAttributes();
                    var filteredAttrs     = ASTUtil.GetSharpCheckerAttributeStrings(dereferencedAttrs);
                    if (!ASTUtil.AnnotationDictionary.ContainsKey(identifierNameExpr) && filteredAttrs.Count() > 0)
                    {
                        ASTUtil.AnnotationDictionary.TryAdd(identifierNameExpr, new List <List <String> >()
                        {
                            filteredAttrs
                        });
                    }
                }
            }

            //Now perform the normal collection of attributes
            base.AnalyzeInvocationExpr(context, invocationExpr);
        }
        public AssignmentSpecification(IASTNode eq, IQueryable persister)
        {
            if (eq.Type != HqlSqlWalker.EQ)
            {
                throw new QueryException("assignment in set-clause not associated with equals");
            }

            _eq      = eq;
            _factory = persister.Factory;

            // Needed to bump this up to DotNode, because that is the only thing which currently
            // knows about the property-ref path in the correct format; it is either this, or
            // recurse over the DotNodes constructing the property path just like DotNode does
            // internally
            DotNode lhs;

            try
            {
                lhs = (DotNode)eq.GetFirstChild();
            }
            catch (InvalidCastException e)
            {
                throw new QueryException(
                          string.Format("Left side of assigment should be a case sensitive property or a field (depending on mapping); found '{0}'", eq.GetFirstChild()), e);
            }
            var rhs = (SqlNode)lhs.NextSibling;

            ValidateLhs(lhs);

            string propertyPath = lhs.PropertyPath;
            var    temp         = new HashedSet <string>();
            // yuck!
            var usep = persister as UnionSubclassEntityPersister;

            if (usep != null)
            {
                temp.AddAll(persister.ConstraintOrderedTableNameClosure);
            }
            else
            {
                temp.Add(persister.GetSubclassTableName(persister.GetSubclassPropertyTableNumber(propertyPath)));
            }
            _tableNames = new ImmutableSet <string>(temp);

            if (rhs == null)
            {
                _hqlParameters = new IParameterSpecification[0];
            }
            else if (IsParam(rhs))
            {
                _hqlParameters = new[] { ((ParameterNode)rhs).HqlParameterSpecification };
            }
            else
            {
                var parameterList = ASTUtil.CollectChildren(rhs, IsParam);
                _hqlParameters = new IParameterSpecification[parameterList.Count];
                int i = 0;
                foreach (ParameterNode parameterNode in parameterList)
                {
                    _hqlParameters[i++] = parameterNode.HqlParameterSpecification;
                }
            }
        }
Exemplo n.º 24
0
 public IList <IASTNode> GetCollectionFetches()
 {
     return(ASTUtil.CollectChildren(this, CollectionFetchPredicate));
 }
Exemplo n.º 25
0
        public EventPropertyGetterSPI GetGetterSPI(string propertyName)
        {
            var desc = _propertyDesc.Get(propertyName);

            if (desc != null)
            {
                return(desc.RevisionGetter);
            }

            // dynamic property names note allowed
            if (propertyName.IndexOf('?') != -1)
            {
                return(null);
            }

            // see if this is a nested property
            var index = ASTUtil.UnescapedIndexOfDot(propertyName);

            if (index == -1)
            {
                var prop = PropertyParser.ParseAndWalkLaxToSimple(propertyName);
                if (prop is SimpleProperty)
                {
                    // there is no such property since it wasn't found earlier
                    return(null);
                }
                string atomic = null;
                if (prop is IndexedProperty)
                {
                    var indexedprop = (IndexedProperty)prop;
                    atomic = indexedprop.PropertyNameAtomic;
                }
                if (prop is MappedProperty)
                {
                    var indexedprop = (MappedProperty)prop;
                    atomic = indexedprop.PropertyNameAtomic;
                }
                desc = _propertyDesc.Get(atomic);
                if (desc == null)
                {
                    return(null);
                }
                if (!(desc.PropertyType is Type))
                {
                    return(null);
                }
                var nestedClass     = (Type)desc.PropertyType;
                var complexProperty = (BeanEventType)_eventAdapterService.AddBeanType(nestedClass.GetDefaultTypeName(), nestedClass, false, false, false);
                return(prop.GetGetter(complexProperty, _eventAdapterService));
            }

            // Map event types allow 2 types of properties inside:
            //   - a property that is a Java object is interrogated via bean property getters and BeanEventType
            //   - a property that is a Map itself is interrogated via map property getters

            // Take apart the nested property into a map key and a nested value class property name
            var propertyMap    = ASTUtil.UnescapeDot(propertyName.Substring(0, index));
            var propertyNested = propertyName.Substring(index + 1);

            desc = _propertyDesc.Get(propertyMap);
            if (desc == null)
            {
                return(null); // prefix not a known property
            }

            // only nested classes supported for revision event types since deep property information not currently exposed by EventType
            if (desc.PropertyType is Type)
            {
                // ask the nested class to resolve the property
                var simpleClass     = (Type)desc.PropertyType;
                var nestedEventType = (EventTypeSPI)_eventAdapterService.AddBeanType(
                    simpleClass.Name, simpleClass, false, false, false);
                var nestedGetter = nestedEventType.GetGetterSPI(propertyNested);
                if (nestedGetter == null)
                {
                    return(null);
                }

                // construct getter for nested property
                return(new RevisionNestedPropertyGetter(desc.RevisionGetter, nestedGetter, _eventAdapterService));
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 26
0
 public IList <IASTNode> GetExplicitFromElements()
 {
     return(ASTUtil.CollectChildren(this, ExplicitFromPredicate));
 }
Exemplo n.º 27
0
 /// <summary>
 /// Returns the list of from elements that will be part of the result set.
 /// </summary>
 /// <returns>the list of from elements that will be part of the result set.</returns>
 public IList <IASTNode> GetProjectionList()
 {
     return(ASTUtil.CollectChildren(this, ProjectionListPredicate));
 }
Exemplo n.º 28
0
        public static StatementSpecRaw CompilePattern(String expression, String expressionForErrorMessage, bool addPleaseCheck, EPServicesContext services, SelectClauseStreamSelectorEnum defaultStreamSelector)
        {
            // Parse
            ParseResult parseResult = ParseHelper.Parse(expression, expressionForErrorMessage, addPleaseCheck, PatternParseRule, true);
            var         ast         = parseResult.Tree;

            if (Log.IsDebugEnabled)
            {
                ASTUtil.DumpAST(ast);
            }

            // Walk
            EPLTreeWalkerListener walker = new EPLTreeWalkerListener(
                parseResult.TokenStream,
                services.EngineImportService,
                services.VariableService,
                services.SchedulingService,
                defaultStreamSelector,
                services.EngineURI,
                services.ConfigSnapshot,
                services.PatternNodeFactory,
                services.ContextManagementService,
                parseResult.Scripts,
                services.ExprDeclaredService,
                services.TableService);

            try
            {
                ParseHelper.Walk(ast, walker, expression, expressionForErrorMessage);
            }
            catch (ASTWalkException ex)
            {
                Log.Debug(".createPattern Error validating expression", ex);
                throw new EPStatementException(ex.Message, expression);
            }
            catch (EPStatementSyntaxException ex)
            {
                throw;
            }
            catch (Exception ex)
            {
                String message = "Error in expression";
                Log.Debug(message, ex);
                throw new EPStatementException(GetNullableErrortext(message, ex.Message), expression);
            }

            var walkerStatementSpec = walker.GetStatementSpec();

            if (walkerStatementSpec.StreamSpecs.Count > 1)
            {
                throw new IllegalStateException("Unexpected multiple stream specifications encountered");
            }

            // Get pattern specification
            var patternStreamSpec = (PatternStreamSpecRaw)walkerStatementSpec.StreamSpecs[0];

            // Create statement spec, set pattern stream, set wildcard select
            var statementSpec = new StatementSpecRaw(SelectClauseStreamSelectorEnum.ISTREAM_ONLY);

            statementSpec.StreamSpecs.Add(patternStreamSpec);
            statementSpec.SelectClauseSpec.SelectExprList.Clear();
            statementSpec.SelectClauseSpec.SelectExprList.Add(new SelectClauseElementWildcard());
            statementSpec.Annotations             = walkerStatementSpec.Annotations;
            statementSpec.ExpressionNoAnnotations = parseResult.ExpressionWithoutAnnotations;

            return(statementSpec);
        }
Exemplo n.º 29
0
        private void DereferenceEntityJoin(string classAlias, EntityType propertyType, bool impliedJoin, IASTNode parent)
        {
            _dereferenceType = DerefEntity;
            if (Log.IsDebugEnabled)
            {
                Log.Debug("dereferenceEntityJoin() : generating join for " + _propertyName + " in "
                          + FromElement.ClassName + " "
                          + ((classAlias == null) ? "{no alias}" : "(" + classAlias + ")")
                          + " parent = " + ASTUtil.GetDebugstring(parent)
                          );
            }

            // Create a new FROM node for the referenced class.
            string associatedEntityName = propertyType.GetAssociatedEntityName();
            string tableAlias           = AliasGenerator.CreateName(associatedEntityName);

            string[] joinColumns = GetColumns();
            string   joinPath    = Path;

            if (impliedJoin && Walker.IsInFrom)
            {
                _joinType = Walker.ImpliedJoinType;
            }

            FromClause  currentFromClause = Walker.CurrentFromClause;
            FromElement elem = currentFromClause.FindJoinByPath(joinPath);

            ///////////////////////////////////////////////////////////////////////////////
            //
            // This is the piece which recognizes the condition where an implicit join path
            // resolved earlier in a correlated subquery is now being referenced in the
            // outer query.  For 3.0final, we just let this generate a second join (which
            // is exactly how the old parser handles this).  Eventually we need to add this
            // logic back in and complete the logic in FromClause.promoteJoin; however,
            // FromClause.promoteJoin has its own difficulties (see the comments in
            // FromClause.promoteJoin).
            //
            //		if ( elem == null ) {
            //			// see if this joinPath has been used in a "child" FromClause, and if so
            //			// promote that element to the outer query
            //			FromClause currentNodeOwner = getFromElement().getFromClause();
            //			FromClause currentJoinOwner = currentNodeOwner.locateChildFromClauseWithJoinByPath( joinPath );
            //			if ( currentJoinOwner != null && currentNodeOwner != currentJoinOwner ) {
            //				elem = currentJoinOwner.findJoinByPathLocal( joinPath );
            //				if ( elem != null ) {
            //					currentFromClause.promoteJoin( elem );
            //					// EARLY EXIT!!!
            //					return;
            //				}
            //			}
            //		}
            //
            ///////////////////////////////////////////////////////////////////////////////

            bool found = elem != null;
            // even though we might find a pre-existing element by join path, for FromElements originating in a from-clause
            // we should only ever use the found element if the aliases match (null != null here).  Implied joins are
            // always (?) ok to reuse.
            bool useFoundFromElement = found && (elem.IsImplied || (AreSame(classAlias, elem.ClassAlias)));

            if (!useFoundFromElement)
            {
                // If this is an implied join in a from element, then use the impled join type which is part of the
                // tree parser's state (set by the gramamar actions).
                JoinSequence joinSequence = SessionFactoryHelper
                                            .CreateJoinSequence(impliedJoin, propertyType, tableAlias, _joinType, joinColumns);

                FromElementFactory factory = new FromElementFactory(
                    currentFromClause,
                    GetLhs().FromElement,
                    joinPath,
                    classAlias,
                    joinColumns,
                    impliedJoin
                    );
                elem = factory.CreateEntityJoin(
                    associatedEntityName,
                    tableAlias,
                    joinSequence,
                    _fetch,
                    Walker.IsInFrom,
                    propertyType
                    );
            }
            else
            {
                currentFromClause.AddDuplicateAlias(classAlias, elem);
            }


            SetImpliedJoin(elem);
            Walker.AddQuerySpaces(elem.EntityPersister.QuerySpaces);
            FromElement = elem;                 // This 'dot' expression now refers to the resulting from element.
        }
Exemplo n.º 30
0
        private static QueryException BuildIllegalCollectionDereferenceException(string propertyName, IASTNode lhs)
        {
            string lhsPath = ASTUtil.GetPathText(lhs);

            return(new QueryException("illegal attempt to dereference collection [" + lhsPath + "] with element property reference [" + propertyName + "]"));
        }