示例#1
0
        public override Expression GetMemberExpression(Expression root, MappingEntity entity, MemberInfo member)
        {
            if (this.mapping.IsAssociationRelationship(entity, member))
            {
                MappingEntity        relatedEntity   = this.mapping.GetRelatedEntity(entity, member);
                ProjectionExpression queryExpression = this.GetQueryExpression(relatedEntity);
                List <MemberInfo>    list            = this.mapping.GetAssociationKeyMembers(entity, member).ToList <MemberInfo>();
                List <MemberInfo>    list2           = this.mapping.GetAssociationRelatedKeyMembers(entity, member).ToList <MemberInfo>();
                Expression           expression2     = null;
                int num   = 0;
                int count = list2.Count;
                while (num < count)
                {
                    Expression expression3 = this.GetMemberExpression(queryExpression.Projector, relatedEntity, list2[num]).Equal(this.GetMemberExpression(root, entity, list[num]));
                    expression2 = (expression2 != null) ? expression2.And(expression3) : expression3;
                    num++;
                }
                TableAlias           newAlias   = new TableAlias();
                ProjectedColumns     columns    = ColumnProjector.ProjectColumns(this.translator.Linguist.Language, queryExpression.Projector, null, newAlias, new TableAlias[] { queryExpression.Select.Alias });
                LambdaExpression     aggregator = Aggregator.GetAggregator(King.Framework.Linq.TypeHelper.GetMemberType(member), typeof(IEnumerable <>).MakeGenericType(new Type[] { columns.Projector.Type }));
                ProjectionExpression expression = new ProjectionExpression(new SelectExpression(newAlias, columns.Columns, queryExpression.Select, expression2), columns.Projector, aggregator);
                return(this.translator.Police.ApplyPolicy(expression, member));
            }
            AliasedExpression expression6 = root as AliasedExpression;

            if ((expression6 != null) && this.mapping.IsColumn(entity, member))
            {
                return(new ColumnExpression(King.Framework.Linq.TypeHelper.GetMemberType(member), this.GetColumnType(entity, member), expression6.Alias, this.mapping.GetColumnName(entity, member)));
            }
            return(QueryBinder.BindMember(root, member));
        }
示例#2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        protected override Expression VisitMemberAccess(MemberExpression m)
        {
            Expression source = this.Visit(m.Expression);

            if (this.mapping.IsRelationship(m.Member))
            {
                ProjectionExpression projection = (ProjectionExpression)this.Visit(this.mapping.GetMemberExpression(source, m.Member));
                if (this.currentFrom != null && this.mapping.IsSingletonRelationship(m.Member))
                {
                    // convert singleton associations directly to OUTER APPLY
                    projection = projection.AddOuterJoinTest();
                    Expression newFrom = new JoinExpression(JoinType.OuterApply, this.currentFrom, projection.Source, null);
                    this.currentFrom = newFrom;
                    return(projection.Projector);
                }
                return(projection);
            }
            else
            {
                Expression       result = QueryBinder.BindMember(source, m.Member);
                MemberExpression mex    = result as MemberExpression;
                if (mex != null && mex.Member == m.Member && mex.Expression == m.Expression)
                {
                    return(m);
                }
                return(result);
            }
        }
示例#3
0
        protected override Expression VisitMemberAccess(MemberExpression m)
        {
            Expression       source = this.Visit(m.Expression);
            EntityExpression ex     = source as EntityExpression;
            IMemberMapping   mm     = null;

            if (ex != null && (mm = ex.Entity.Get(m.Member)) != null && mm.IsRelationship)
            {
                ProjectionExpression projection = (ProjectionExpression)this.Visit(this.expressionBuilder.GetMemberExpression(source, ex.Entity, m.Member));
                if (this.currentFrom != null && mm.IsManyToOne)
                {
                    // convert singleton associations directly to OUTER APPLY
                    projection = this.expressionBuilder.AddOuterJoinTest(projection);
                    Expression newFrom = new JoinExpression(JoinType.OuterApply, this.currentFrom, projection.Select, null);
                    this.currentFrom = newFrom;
                    return(projection.Projector);
                }
                return(projection);
            }
            else
            {
                Expression       result = QueryBinder.BindMember(source, m.Member);
                MemberExpression mex    = result as MemberExpression;
                if (mex != null && mex.Member == m.Member && mex.Expression == m.Expression)
                {
                    return(m);
                }
                return(result);
            }
        }
示例#4
0
        /// <summary>
        /// Apply mapping translations to this expression
        /// </summary>
        public virtual Expression Translate(Expression expression)
        {
            // convert references to LINQ operators into query specific nodes
            var bound = QueryBinder.Bind(this, expression);

            // move aggregate computations so they occur in same select as group-by
            var aggmoved = AggregateRewriter.Rewrite(this.Translator.Linguist.Language, bound);

            // do reduction so duplicate association's are likely to be clumped together
            var reduced = UnusedColumnRemover.Remove(aggmoved);

            reduced = RedundantColumnRemover.Remove(reduced);
            reduced = RedundantSubqueryRemover.Remove(reduced);
            reduced = RedundantJoinRemover.Remove(reduced);

            // convert references to association properties into correlated queries
            var rbound = RelationshipBinder.Bind(this, reduced);

            if (rbound != reduced)
            {
                // clean up after ourselves! (multiple references to same association property)
                rbound = RedundantColumnRemover.Remove(rbound);
                rbound = RedundantJoinRemover.Remove(rbound);
            }

            // rewrite comparision checks between entities and multi-valued constructs
            var result = ComparisonRewriter.Rewrite(this.Mapping, rbound);

            return(result);
        }
        protected override Expression VisitMember(MemberExpression m)
        {
            var       source = Visit(m.Expression);
            IProperty property;

            // **fix** 解决无法返回两级以上关联对象的问题
            // var ex = source as EntityExpression
            // if (ex != null &&
            if ((property = PropertyUnity.GetProperty(m.Expression.Type, m.Member.Name)) != null &&
                property is RelationProperty)
            {
                var projection = (ProjectionExpression)Visit(QueryUtility.GetMemberExpression(_transContext, source, property));
                if (_currentFrom != null && m.Member.GetMemberType().GetEnumerableType() == null)
                {
                    // convert singleton associations directly to OUTER APPLY
                    projection = projection.AddOuterJoinTest();
                    var newFrom = new JoinExpression(JoinType.OuterApply, _currentFrom, projection.Select, null);
                    _currentFrom = newFrom;
                    return(projection.Projector);
                }

                return(projection);
            }

            var result = QueryBinder.BindMember(source, m.Member);

            if (result is MemberExpression mex &&
                mex.Member == m.Member &&
                mex.Expression == m.Expression)
            {
                return(m);
            }

            return(result);
        }
示例#6
0
        static Expression EntityIn(Expression newItem, Dictionary <Type, PrimaryKey[]> entityIDs)
        {
            EntityExpression ee = newItem as EntityExpression;

            if (ee != null)
            {
                return(InPrimaryKey(ee.ExternalId, entityIDs.TryGetC(ee.Type) ?? new PrimaryKey[0]));
            }

            ImplementedByExpression ib = newItem as ImplementedByExpression;

            if (ib != null)
            {
                return(ib.Implementations.JoinDictionary(entityIDs,
                                                         (t, f, values) => Expression.And(DbExpressionNominator.FullNominate(NotEqualToNull(f.ExternalId)), InPrimaryKey(f.ExternalId, values)))
                       .Values.AggregateOr());
            }

            ImplementedByAllExpression iba = newItem as ImplementedByAllExpression;

            if (iba != null)
            {
                return(entityIDs.Select(kvp => Expression.And(
                                            EqualNullable(new PrimaryKeyExpression(QueryBinder.TypeConstant(kvp.Key).Nullify()), iba.TypeId.TypeColumn),
                                            InPrimaryKey(iba.Id, kvp.Value))).AggregateOr());
            }

            throw new InvalidOperationException("EntityIn not defined for newItem of type {0}".FormatWith(newItem.Type.Name));
        }
示例#7
0
        public static string Substitute(string input, PropertyDescriptor[] properties, Func <int, string> indexedToValue = null)
        {
            input = input ?? "";

            return(Substitute(input, value =>
            {
                var s = value.ToUpper();

                if (properties?.Length > 0)
                {
                    var property = properties[0];

                    switch (s)
                    {
                    case "TYPENAME":
                        return property.DeclaringTypeDescriptor.TypeName;

                    case "PROPERTYNAME":
                        return property.PropertyName;

                    case "PROPERTYTYPENAME":
                        return property.PropertyType.Name;

                    case "PERSISTED_TYPENAME":
                        return property.DeclaringTypeDescriptor.PersistedName;

                    case "PERSISTED_PROPERTYNAME":
                        return property.PersistedName;

                    case "PERSISTED_PROPERTYTYPENAME":
                        return property.PropertyTypeTypeDescriptor.PersistedName;

                    case "PROPERTYNAMES":
                        return properties.Select(c => c.PropertyName);

                    case "PERSISTED_PROPERTYNAMES":
                        return properties.Select(c => c.PersistedName);

                    case "PERSISTED_PROPERTYPREFIXNAMES":
                        return properties.Select(c => c.PrefixName);

                    case "PERSISTED_PROPERTYSUFFIXNAMES":
                        return properties.Select(c => c.SuffixName);

                    case "COLUMNNAME":
                        return QueryBinder.GetColumnInfos(property.DeclaringTypeDescriptor.TypeDescriptorProvider, property);

                    case "COLUMNNAMES":
                        return QueryBinder.GetColumnInfos(property.DeclaringTypeDescriptor.TypeDescriptorProvider, properties);
                    }
                }

                if (indexedToValue != null && int.TryParse(s, out var number))
                {
                    return indexedToValue(number);
                }

                throw new NotSupportedException(value);
            }));
        }
        internal static Expression Optimize(Expression binded, QueryBinder binder, AliasGenerator aliasGenerator, HeavyProfiler.Tracer log)
        {
            log.Switch("Aggregate");
            Expression rewrited = AggregateRewriter.Rewrite(binded);

            log.Switch("EntityCompleter");
            Expression completed = EntityCompleter.Complete(rewrited, binder);

            log.Switch("AliasReplacer");
            Expression replaced = AliasProjectionReplacer.Replace(completed, aliasGenerator);

            log.Switch("OrderBy");
            Expression orderRewrited = OrderByRewriter.Rewrite(replaced);

            log.Switch("Rebinder");
            Expression rebinded = QueryRebinder.Rebind(orderRewrited);

            log.Switch("UnusedColumn");
            Expression columnCleaned = UnusedColumnRemover.Remove(rebinded);

            log.Switch("Redundant");
            Expression subqueryCleaned = RedundantSubqueryRemover.Remove(columnCleaned);

            log.Switch("Condition");
            Expression rewriteConditions = ConditionsRewriter.Rewrite(subqueryCleaned);

            log.Switch("Scalar");
            Expression scalar = ScalarSubqueryRewriter.Rewrite(rewriteConditions);

            return(scalar);
        }
示例#9
0
        protected override Expression VisitMemberAccess(MemberExpression m)
        {
            Expression source = Visit(m.Expression);
            var        ex     = source as EntryExpression;

            if (ex != null && mapping.IsRelationship(ex.Entry, m.Member))
            {
                var projection = (ProjectionExpression)Visit(mapper.GetMemberExpression(source, ex.Entry, m.Member));
                if (currentFrom != null && mapping.IsSingletonRelationship(ex.Entry, m.Member))
                {
                    // convert singleton associations directly to OUTER APPLY
                    projection = language.AddOuterJoinTest(projection);
                    Expression newFrom = new JoinExpression(JoinType.OuterApply, currentFrom, projection.Select, null);
                    currentFrom = newFrom;
                    return(projection.Projector);
                }
                return(projection);
            }
            else
            {
                Expression result = QueryBinder.BindMember(source, m.Member);
                var        mex    = result as MemberExpression;
                if (mex != null && mex.Member == m.Member && mex.Expression == m.Expression)
                {
                    return(m);
                }
                return(result);
            }
        }
示例#10
0
        // GET: O
        public ActionResult BNNextIndex()
        {
            string        _defaultDate = string.Empty;
            List <string> dates        = GetAvaliableDates(out _defaultDate);

            GenerateBackDateURLs(dates);


            string path = ConfigurationManager.AppSettings["BNNextOptions"];

            List <OIOData.OIDetails> objforXml = new List <OIDetails>();
            OBJtoXML xmltoObj = new OBJtoXML();

            string[] txtFiles = Directory.GetFiles(path, "*.txt*", SearchOption.AllDirectories).OrderByDescending(d => new FileInfo(d).LastWriteTime).ToArray();

            //var txtFiles = Directory.EnumerateFiles("D:\\MasterData\\Basic\\", " *.txt").OrderByDescending(x => x);
            List <string>            filesList   = FilterDates(txtFiles.ToList(), _defaultDate);
            List <OIOData.OIDetails> optionsData = new List <OIDetails>();

            foreach (string currentFile in filesList)
            {
                optionsData = (List <OIOData.OIDetails>)xmltoObj.CreateOptionsObject(objforXml, currentFile);
            }
            QueryBinder dataList = new QueryBinder();

            dataList.CallOptionsNextBNData = GenerateCallData(optionsData).CallOptionsNData;
            dataList.PutOptionsNextBNData  = GeneratePutData(optionsData).PutOptionsNData;

            return(View(dataList));
        }
示例#11
0
 internal NewExpression?GenerateSystemPeriod(Alias tableAlias, QueryBinder binder, bool force = false)
 {
     return(this.SystemVersioned != null && (force || binder.systemTime is SystemTime.Interval) ? Expression.New(intervalConstructor,
                                                                                                                 new ColumnExpression(typeof(DateTime), tableAlias, this.SystemVersioned.StartColumnName),
                                                                                                                 new ColumnExpression(typeof(DateTime), tableAlias, this.SystemVersioned.EndColumnName)
                                                                                                                 ) : null);
 }
        private Expression BuildIndexExpression(TypeDescriptor typeDescriptor, SqlTableExpression table, IndexInfo indexInfo)
        {
            Expression where = null;

            var indexedColumns = new List <SqlIndexedColumnExpression>();

            foreach (var property in indexInfo.Properties.Where(c => !c.IncludeOnly))
            {
                foreach (var columnInfo in QueryBinder.GetColumnInfos(this.model.TypeDescriptorProvider, typeDescriptor.GetPropertyDescriptorByPropertyName(property.PropertyName)))
                {
                    indexedColumns.Add(new SqlIndexedColumnExpression(new SqlColumnExpression(columnInfo.DefinitionProperty.PropertyType, null, columnInfo.ColumnName), property.SortOrder, property.Lowercase));
                }
            }

            var includedColumns = new List <SqlIndexedColumnExpression>();

            foreach (var property in indexInfo.Properties.Where(c => c.IncludeOnly))
            {
                foreach (var columnInfo in QueryBinder.GetColumnInfos(this.model.TypeDescriptorProvider, typeDescriptor.GetPropertyDescriptorByPropertyName(property.PropertyName)))
                {
                    includedColumns.Add(new SqlIndexedColumnExpression(new SqlColumnExpression(columnInfo.DefinitionProperty.PropertyType, null, columnInfo.ColumnName)));
                }
            }

            var parameterExpression = Expression.Parameter(typeDescriptor.Type);

            if (indexInfo.Condition == null)
            {
                foreach (var property in indexInfo.Properties.Where(c => !c.Condition.IsNullOrEmpty()))
                {
                    var expression = ComputedExpressionParser.Parse(property.Condition, typeDescriptor.GetPropertyDescriptorByPropertyName(property.PropertyName), parameterExpression, null, typeof(bool));

                    if (expression == null)
                    {
                        continue;
                    }

                    where = where == null ? expression.Body : Expression.And(where, expression.Body);
                }
            }
            else
            {
                where = ComputedExpressionParser.Parse(indexInfo.Condition, parameterExpression, null, typeof(bool)).Body;
            }

            if (where != null)
            {
                where = Expression.Lambda(where, parameterExpression);

                var call = Expression.Call(null, MethodInfoFastRef.QueryableWhereMethod.MakeGenericMethod(parameterExpression.Type), Expression.Constant(null, typeof(DataAccessObjects <>).MakeGenericType(parameterExpression.Type)), where);

                var projection = (SqlProjectionExpression)SqlQueryProvider.Optimize(this.dataAccessModel, SqlQueryProvider.Bind(this.dataAccessModel, this.sqlDataTypeProvider, call));

                where = projection.Select.Where;

                where = SqlAliasReferenceReplacer.Replace(where, ((SqlAliasedExpression)projection.Select.From).Alias, null);
            }

            return(new SqlCreateIndexExpression(indexInfo.IndexName, table, indexInfo.Unique, indexInfo.IndexType, false, indexedColumns, includedColumns, where));
        }
        internal ReadOnlyCollection<MixinEntityExpression> GenerateMixins(Alias tableAlias, QueryBinder binder, Expression id)
        {
            if (this.Mixins == null)
                return null;

            return this.Mixins.Values.Select(m => (MixinEntityExpression)m.GetExpression(tableAlias, binder, id)).ToReadOnly();
        }
示例#14
0
        public QueryBinder TodayPicker(string _defaultDate)
        {
            //Cache5
            QueryBinder           binder          = new QueryBinder();
            RBOData               objData         = new RBOData();
            List <RBOEntity>      data            = objData.RBO(_defaultDate);
            List <CompanyDetails> todayPickerData = new List <CompanyDetails>();
            BulkData              objList         = new BulkData();
            List <CompanyDetails> data1           = objList.GetBasicData(new List <Weightage>(), "All", _masterDatapathBasic, _defaultDate).Where(x => x.BasicSavedTimeStamp.Date == DateTime.Now.Date).ToList();
            int qId = data1.Max(x => x.Id);
            List <CompanyDetails> newDataList = data1.Where(x => x.Id == qId).OrderByDescending(x => Convert.ToDecimal(x.CurrentPrevdayVolumePercentage)).Take(30).ToList();

            foreach (var newItem in newDataList)
            {
                foreach (var item in data.Where(x => Convert.ToDecimal(x.BOPercentage) > 95).OrderByDescending(x => Convert.ToDecimal(x.BOPercentage)))
                {
                    if (item.Code == newItem.Code)
                    {
                        todayPickerData.Add(newItem); break;
                    }
                }
            }
            binder.PosativeData = todayPickerData.ToList();
            return(binder);
        }
示例#15
0
        static ImplementedByAllExpression ToIBA(Expression node, Type type)
        {
            if (node.IsNull())
            {
                return(new ImplementedByAllExpression(type,
                                                      Expression.Constant(null, typeof(string)),
                                                      new TypeImplementedByAllExpression(new PrimaryKeyExpression(Expression.Constant(null, PrimaryKey.Type(typeof(TypeEntity))))), null));
            }

            if (node is EntityExpression e)
            {
                return(new ImplementedByAllExpression(type,
                                                      new SqlCastExpression(typeof(string), e.ExternalId.Value),
                                                      new TypeImplementedByAllExpression(new PrimaryKeyExpression(QueryBinder.TypeConstant(e.Type))), null));
            }

            if (node is ImplementedByExpression ib)
            {
                return(new ImplementedByAllExpression(type,
                                                      new PrimaryKeyExpression(QueryBinder.Coalesce(ib.Implementations.Values.Select(a => a.ExternalId.ValueType.Nullify()).Distinct().SingleEx(), ib.Implementations.Select(e => e.Value.ExternalId))),
                                                      new TypeImplementedByAllExpression(new PrimaryKeyExpression(
                                                                                             ib.Implementations.Select(imp => new When(imp.Value.ExternalId.NotEqualsNulll(), QueryBinder.TypeConstant(imp.Key))).ToList()
                                                                                             .ToCondition(PrimaryKey.Type(typeof(TypeEntity)).Nullify()))), null));
            }

            if (node is ImplementedByAllExpression iba)
            {
                return(iba);
            }

            throw new UnexpectedValueException(node);
        }
示例#16
0
        Expression IQueryPolicy.ApplyPolicy(Expression expression, MemberInfo member)
        {
            List <LambdaExpression> ops;

            if (operations.TryGetValue(member, out ops))
            {
                var syntax = Database.Provider.GetService <ISyntaxProvider>();
                var result = expression;
                foreach (var fnOp in ops)
                {
                    var pop = PartialEvaluator.Eval(fnOp);
                    result = QueryBinder.Bind(Expression.Invoke(pop, result), syntax);
                }

                var projection = (ProjectionExpression)result;
                if (projection.Type != expression.Type)
                {
                    var fnAgg = QueryUtility.GetAggregator(expression.Type, projection.Type);
                    projection = new ProjectionExpression(projection.Select, projection.Projector, fnAgg);
                }

                return(projection);
            }

            return(expression);
        }
示例#17
0
        protected override Expression VisitMemberAccess(MemberExpression m)
        {
            Expression       root        = this.Visit(m.Expression);
            EntityExpression expression2 = root as EntityExpression;

            if ((expression2 != null) && this.mapping.IsRelationship(expression2.Entity, m.Member))
            {
                ProjectionExpression proj = (ProjectionExpression)this.Visit(this.mapper.GetMemberExpression(root, expression2.Entity, m.Member));
                if ((this.currentFrom != null) && this.mapping.IsSingletonRelationship(expression2.Entity, m.Member))
                {
                    proj = this.language.AddOuterJoinTest(proj);
                    Expression expression4 = new JoinExpression(JoinType.OuterApply, this.currentFrom, proj.Select, null);
                    this.currentFrom = expression4;
                    return(proj.Projector);
                }
                return(proj);
            }
            Expression       expression5 = QueryBinder.BindMember(root, m.Member);
            MemberExpression expression6 = expression5 as MemberExpression;

            if (((expression6 != null) && (expression6.Member == m.Member)) && (expression6.Expression == m.Expression))
            {
                return(m);
            }
            return(expression5);
        }
示例#18
0
 static Expression EntityIbaEquals(EntityExpression ee, ImplementedByAllExpression iba)
 {
     return(Expression.And(
                ee.ExternalId.Value == NewId ? False : EqualNullable(new SqlCastExpression(typeof(string), ee.ExternalId.Value), iba.Id),
                EqualNullable(QueryBinder.TypeConstant(ee.Type), iba.TypeId.TypeColumn.Value))
            .And(ee.ExternalPeriod.Overlaps(iba.ExternalPeriod)));
 }
示例#19
0
        internal Expression GetProjectorExpression(Alias tableAlias, QueryBinder binder)
        {
            Expression?id = GetIdExpression(tableAlias);

            if (IsView)
            {
                var bindings = this.Fields.Values.Select(ef => new FieldBinding(ef.FieldInfo, ef.Field.GetExpression(tableAlias, binder, id !, null))).ToReadOnly();

                var hasValue = id == null?Expression.Constant(true) : SmartEqualizer.NotEqualNullable(id, Expression.Constant(null, id.Type.Nullify()));

                return(new EmbeddedEntityExpression(this.Type, hasValue, bindings, null, this));
            }
            else
            {
                Schema.Current.AssertAllowed(Type, inUserInterface: false);

                var period   = GenerateSystemPeriod(tableAlias, binder);
                var bindings = GenerateBindings(tableAlias, binder, id !, period);
                var mixins   = GenerateMixins(tableAlias, binder, id !, period);

                var result = new EntityExpression(this.Type, (PrimaryKeyExpression)id !, period, tableAlias, bindings, mixins, period, avoidExpandOnRetrieving: false);

                return(result);
            }
        }
示例#20
0
        /// <summary>
        /// Get an expression for a mapped property relative to a root expression.
        /// The root is either a TableExpression or an expression defining an entity instance.
        /// </summary>
        /// <param name="root"></param>
        /// <param name="member"></param>
        /// <returns></returns>
        public virtual Expression GetMemberExpression(Expression root, MemberInfo member)
        {
            if (this.IsRelationship(member))
            {
                Type rowType = this.GetRelatedType(member);
                ProjectionExpression projection = this.GetTableQuery(rowType);

                // make where clause for joining back to 'root'
                List <MemberInfo> declaredTypeMembers;
                List <MemberInfo> associatedMembers;
                this.GetAssociationKeys(member, out declaredTypeMembers, out associatedMembers);

                Expression where = null;
                for (int i = 0, n = associatedMembers.Count; i < n; i++)
                {
                    Expression equal = Expression.Equal(
                        this.GetMemberExpression(projection.Projector, associatedMembers[i]),
                        this.GetMemberExpression(root, declaredTypeMembers[i])
                        );
                    where = (where != null) ? Expression.And(where, equal) : equal;
                }

                TableAlias newAlias = new TableAlias();
                var        pc       = ColumnProjector.ProjectColumns(this.Language.CanBeColumn, projection.Projector, null, newAlias, projection.Source.Alias);

                LambdaExpression aggregator = this.GetAggregator(TypeHelper.GetMemberType(member), typeof(IEnumerable <>).MakeGenericType(pc.Projector.Type));
                return(new ProjectionExpression(
                           new SelectExpression(newAlias, pc.Columns, projection.Source, where),
                           pc.Projector, aggregator
                           ));
            }
            else
            {
                TableExpression table = root as TableExpression;
                if (table != null)
                {
                    if (this.IsColumn(member))
                    {
                        string columnName = this.GetColumnName(member);
                        if (!string.IsNullOrEmpty(columnName))
                        {
                            return(new ColumnExpression(TypeHelper.GetMemberType(member), table.Alias, this.GetColumnName(member)));
                        }
                        else
                        {
                            return(root);
                        }
                    }
                    else
                    {
                        return(this.GetTypeProjection(root, TypeHelper.GetMemberType(member)));
                    }
                }
                else
                {
                    return(QueryBinder.BindMember(root, member));
                }
            }
        }
        private Expression BuildIndexExpression(SqlTableExpression table, string indexName, Tuple <IndexAttribute, PropertyDescriptor>[] properties)
        {
            Expression where = null;
            var unique         = properties.Select(c => c.Item1).Any(c => c.Unique);
            var lowercaseIndex = properties.Any(c => c.Item1.LowercaseIndex);
            var indexType      = properties.Select(c => c.Item1.IndexType).FirstOrDefault(c => c != IndexType.Default);
            var sorted         = properties.OrderBy(c => c.Item1.CompositeOrder, Comparer <int> .Default);

            var indexedColumns = new List <SqlIndexedColumnExpression>();

            foreach (var attributeAndProperty in sorted.Where(c => !c.Item1.IncludeOnly))
            {
                foreach (var columnInfo in QueryBinder.GetColumnInfos(this.model.TypeDescriptorProvider, attributeAndProperty.Item2))
                {
                    indexedColumns.Add(new SqlIndexedColumnExpression(new SqlColumnExpression(columnInfo.DefinitionProperty.PropertyType, null, columnInfo.ColumnName), attributeAndProperty.Item1.SortOrder, attributeAndProperty.Item1.LowercaseIndex));
                }
            }

            var includedColumns = new List <SqlIndexedColumnExpression>();

            foreach (var attributeAndProperty in sorted.Where(c => c.Item1.IncludeOnly))
            {
                foreach (var columnInfo in QueryBinder.GetColumnInfos(this.model.TypeDescriptorProvider, attributeAndProperty.Item2))
                {
                    includedColumns.Add(new SqlIndexedColumnExpression(new SqlColumnExpression(columnInfo.DefinitionProperty.PropertyType, null, columnInfo.ColumnName)));
                }
            }

            Debug.Assert(properties.Select(c => c.Item2.PropertyInfo.DeclaringType).Distinct().Count() == 1);

            var parameterExpression = Expression.Parameter(properties.First().Item2.PropertyInfo.DeclaringType);

            foreach (var attributeAndProperty in sorted.Where(c => !c.Item1.Condition.IsNullOrEmpty()))
            {
                var expression = ComputedExpressionParser.Parse(attributeAndProperty.Item1.Condition, attributeAndProperty.Item2, parameterExpression, null, typeof(bool));

                if (expression == null)
                {
                    continue;
                }

                where = where == null ? expression.Body : Expression.And(where, expression.Body);
            }

            if (where != null)
            {
                where = Expression.Lambda(where, parameterExpression);

                var call = Expression.Call(null, MethodInfoFastRef.QueryableWhereMethod.MakeGenericMethod(parameterExpression.Type), Expression.Constant(null, typeof(DataAccessObjects <>).MakeGenericType(parameterExpression.Type)), where);

                var projection = (SqlProjectionExpression)SqlQueryProvider.Optimize(this.dataAccessModel, SqlQueryProvider.Bind(this.dataAccessModel, this.sqlDataTypeProvider, call));

                where = projection.Select.Where;

                where = AliasReferenceReplacer.Replace(where, ((SqlTableExpression)projection.Select.From).Alias, null);
            }

            return(new SqlCreateIndexExpression(indexName, table, unique, lowercaseIndex, indexType, false, indexedColumns, includedColumns, where));
        }
示例#22
0
        internal static Expression GetMemberExpression(Expression root, IProperty property)
        {
            var relationProprety = property as RelationProperty;

            if (relationProprety != null)
            {
                //所关联的实体类型
                var relMetadata = EntityMetadataUnity.GetEntityMetadata(relationProprety.RelationType);
                var projection  = GetTableQuery(relMetadata);

                Expression parentExp = null, childExp = null;
                var        ship = RelationshipUnity.GetRelationship(relationProprety);
                if (ship.ThisType != relationProprety.EntityType)
                {
                    parentExp = projection.Projector;
                    childExp  = root;
                }
                else
                {
                    parentExp = root;
                    childExp  = projection.Projector;
                }

                Expression where = null;
                for (int i = 0, n = ship.Keys.Count; i < n; i++)
                {
                    var equal = GetMemberExpression(parentExp, ship.Keys[i].ThisProperty)
                                .Equal(GetMemberExpression(childExp, ship.Keys[i].OtherProperty));
                    where = (where != null) ? Expression.And(where, equal) : equal;
                }

                var newAlias = new TableAlias();
                var pc       = ColumnProjector.ProjectColumns(CanBeColumnExpression, projection.Projector, null, newAlias, projection.Select.Alias);

                var aggregator = GetAggregator(property.Type, typeof(IEnumerable <>).MakeGenericType(pc.Projector.Type));
                var result     = new ProjectionExpression(
                    new SelectExpression(newAlias, pc.Columns, projection.Select, where),
                    pc.Projector, aggregator
                    );

                return(ApplyPolicy(result, property.Info.ReflectionInfo));
            }

            var table = root as TableExpression;

            if (table != null)
            {
                var sqProperty = property as SubqueryProperty;
                if (sqProperty != null)
                {
                    return(new SubqueryColumnExpression(property.Type, table.Alias, property.Info.FieldName, sqProperty.Subquery));
                }
                else if (property is ISavedProperty)
                {
                    return(new ColumnExpression(property.Type, table.Alias, property.Name, property.Info));
                }
            }
            return(QueryBinder.BindMember(root, property.Info.ReflectionInfo));
        }
示例#23
0
        internal override Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id)
        {
            var bindings = (from kvp in Fields
                            let fi = kvp.Value.FieldInfo
                                     select new FieldBinding(fi, kvp.Value.Field.GetExpression(tableAlias, binder, id))).ToReadOnly();

            return(new MixinEntityExpression(this.FieldType, bindings, tableAlias, this));
        }
示例#24
0
        private QueryBinder GenerateDynamicList(QueryBinder binder, QueryBinder binderList)
        {
            QueryBinder obj = new QueryBinder();



            return(obj);
        }
示例#25
0
        protected override Expression VisitUpdate(SqlUpdateExpression expression)
        {
            if (!expression.RequiresIdentityInsert)
            {
                return(base.VisitUpdate(expression));
            }

            var tableName = ((SqlTableExpression)expression.Source).Name;

            var typeDescriptor = this
                                 .typeDescriptorProvider
                                 .GetTypeDescriptors()
                                 .Single(c => c.PersistedName == tableName);

            var insertedColumns = expression
                                  .Assignments
                                  .OfType <SqlAssignExpression>()
                                  .Select(c => new { name = ((SqlColumnExpression)c.Target).Name, value = c.Value, propertyDescriptor = typeDescriptor.GetPropertyDescriptorByColumnName(((SqlColumnExpression)c.Target).Name) })
                                  .ToList();

            var columnInfos = QueryBinder
                              .GetColumnInfos(this.typeDescriptorProvider, typeDescriptor.PersistedProperties.Where(c => insertedColumns.All(d => d.propertyDescriptor != c)))
                              .ToList();

            var visitedUpdated       = (SqlUpdateExpression)base.VisitUpdate(expression);
            var selectIntoExpression = new SqlSelectExpression
                                       (
                typeof(void),
                null,
                columnInfos.Select
                (
                    c => new SqlColumnDeclaration
                    (
                        null, new SqlColumnExpression(c.DefinitionProperty.PropertyType, null, c.GetColumnName())
                    )
                )
                .Concat(insertedColumns.Select(d => d.value.Type.GetUnwrappedNullableType() == typeof(bool) ? new SqlColumnDeclaration(d.name, new BitBooleanExpression(d.value)) : new SqlColumnDeclaration(d.name, d.value)))
                .ToReadOnlyCollection(),
                visitedUpdated.Source,
                visitedUpdated.Where,
                null, null, false, null, null, false, false, new SqlTableExpression("#TEMP")
                                       );

            var selectExpression = new SqlSelectExpression(typeof(void), null, null, selectIntoExpression.Into, null, null);
            var insertExpression = new SqlInsertIntoExpression(visitedUpdated.Source, columnInfos.Select(c => c.GetColumnName()).Concat(insertedColumns.Select(c => c.name)).ToReadOnlyCollection(), null, selectExpression, null, true);
            var deleteExpression = new SqlDeleteExpression(visitedUpdated.Source, visitedUpdated.Where);

            var list = new List <Expression>
            {
                selectIntoExpression,
                deleteExpression,
                new SqlSetCommandExpression("IDENTITY_INSERT", visitedUpdated.Source, new SqlKeywordExpression("ON")),
                insertExpression,
                new SqlSetCommandExpression("IDENTITY_INSERT", visitedUpdated.Source, new SqlKeywordExpression("OFF")),
            };

            return(new SqlStatementListExpression(list));
        }
示例#26
0
        private Expression TranslateInternal(Expression expression, TranslateOptions options)
        {
            var syntax      = TranslateScope.Current.Context.Database.Provider.GetService <ISyntaxProvider>();
            var translation = QueryBinder.Bind(expression, syntax);

            translation = LogicalDeleteFlagRewriter.Rewrite(translation);
            translation = GlobalQueryPolicyRewriter.Rewrite(translation);
            translation = AggregateRewriter.Rewrite(translation);
            translation = UnusedColumnRemover.Remove(translation);
            translation = RedundantColumnRemover.Remove(translation);
            translation = RedundantSubqueryRemover.Remove(translation);
            translation = RedundantJoinRemover.Remove(translation);

            var bound = RelationshipBinder.Bind(translation);

            if (bound != translation)
            {
                translation = bound;
                translation = RedundantColumnRemover.Remove(translation);
                translation = RedundantJoinRemover.Remove(translation);
            }
            translation = ComparisonRewriter.Rewrite(translation);

            var rewritten = RelationshipIncluder.Include(TranslateScope.Current.Context, translation);

            if (rewritten != translation)
            {
                translation = rewritten;
                translation = UnusedColumnRemover.Remove(translation);
                translation = RedundantColumnRemover.Remove(translation);
                translation = RedundantSubqueryRemover.Remove(translation);
                translation = RedundantJoinRemover.Remove(translation);
            }

            rewritten = SingletonProjectionRewriter.Rewrite(translation);
            if (rewritten != translation)
            {
                translation = rewritten;
                translation = UnusedColumnRemover.Remove(translation);
                translation = RedundantColumnRemover.Remove(translation);
                translation = RedundantSubqueryRemover.Remove(translation);
                translation = RedundantJoinRemover.Remove(translation);
            }

            rewritten = ClientJoinedProjectionRewriter.Rewrite(translation);
            if (rewritten != translation)
            {
                translation = rewritten;
                translation = UnusedColumnRemover.Remove(translation);
                translation = RedundantColumnRemover.Remove(translation);
                translation = RedundantSubqueryRemover.Remove(translation);
                translation = RedundantJoinRemover.Remove(translation);
            }

            translation = BuildExpression(translation);

            return(translation);
        }
示例#27
0
        private Expression VisitType(Expression exp)
        {
            if (exp.NodeType == ExpressionType.Constant)
            {
                return(exp);
            }

            return(new TypeImplementedByAllExpression(QueryBinder.ExtractTypeId(exp)));
        }
示例#28
0
 internal IntervalExpression?GenerateSystemPeriod(Alias tableAlias, QueryBinder binder, bool force = false)
 {
     return(this.SystemVersioned != null && (force || binder.systemTime is SystemTime.Interval) ? new IntervalExpression(typeof(Interval <DateTime>),
                                                                                                                         this.SystemVersioned.StartColumnName?.Let(c => new ColumnExpression(typeof(DateTime), tableAlias, c)),
                                                                                                                         this.SystemVersioned.EndColumnName?.Let(c => new ColumnExpression(typeof(DateTime), tableAlias, c)),
                                                                                                                         this.SystemVersioned.PostgreeSysPeriodColumnName?.Let(c => new ColumnExpression(typeof(NpgsqlRange <DateTime>), tableAlias, c)),
                                                                                                                         asUtc: true
                                                                                                                         ) : null);
 }
示例#29
0
        public QueryBinder GeneratePutData(List <OIDetails> optionsData)
        {
            QueryBinder obj = new QueryBinder();

            obj.PutOptionsNData = optionsData.Where(x => x.optionType == "PE").OrderByDescending(x => x.strikePrice).ToList();
            //generate tool tip
            obj.PutOptionsNData = GenerateToolTip(obj.PutOptionsNData);
            return(obj);
        }
示例#30
0
        public QueryBinder MCData(string _defaultDate)
        {
            //Cache2
            QueryBinder binder  = new QueryBinder();
            BulkData    objList = new BulkData();

            binder.MCData = objList.MCData(masterMCpath, _defaultDate);
            return(binder);
        }
示例#31
0
        private static Expression TypeConstantIbaEquals(ConstantExpression ce, TypeImplementedByAllExpression typeIba)
        {
            if (ce.IsNull())
            {
                return(EqualsToNull(typeIba.TypeColumn));
            }

            return(EqualNullable(QueryBinder.TypeConstant((Type)ce.Value), typeIba.TypeColumn.Value));
        }
示例#32
0
        public static Expression Complete(Expression source, QueryBinder binder)
        {
            EntityCompleter pc = new EntityCompleter() { binder = binder };
            
            var result = pc.Visit(source);

            var expandedResul = QueryJoinExpander.ExpandJoins(result, binder);

            return expandedResul;
        }
示例#33
0
 private static Query CreateQuery(Application application, CepStream<BrandQuote> streamDefinition, BrandQuoteInputConfig inputConfig, BrandQuoteOutputConfig outputConfig)
 {
     var template = application.CreateQueryTemplate("QueryTemplate", null, streamDefinition);
     var binder = new QueryBinder(template);
     var inputAdapter = application.CreateInputAdapter<BrandQuoteInputAdapterFactory>("InputAdapter", null);
     binder.BindProducer("Input", inputAdapter, inputConfig, EventShape.Point);
     var outputAdapter = application.CreateOutputAdapter<BrandQuoteOutputAdapterFactory>("OutputAdapter", null);
     binder.AddConsumer("Output", outputAdapter, outputConfig, EventShape.Point, StreamEventOrder.FullyOrdered);
     var query = application.CreateQuery("Query", null, binder);
     return query;
 }
示例#34
0
 /// <summary>
 /// Creates and binds a query with a single input stream.
 /// </summary>
 private static Query CreateQuery(Application application, CepStream<EventType> streamDefinition, Uri inputAddress, Uri outputAddress)
 {
     QueryTemplate template = application.CreateQueryTemplate("QueryTemplate", null, streamDefinition);
     QueryBinder binder = new QueryBinder(template);
     InputAdapter inputAdapter = application.CreateInputAdapter<WcfInputAdapterFactory>("InputAdapter", null);
     binder.BindProducer("Input", inputAdapter, inputAddress, EventShape.Point);
     OutputAdapter outputAdapter = application.CreateOutputAdapter<WcfOutputAdapterFactory>("OutputAdapter", null);
     binder.AddConsumer("Output", outputAdapter, outputAddress, EventShape.Point, StreamEventOrder.FullyOrdered);
     Query query = application.CreateQuery("Query", null, binder);
     return query;
 }
        internal ReadOnlyCollection<FieldBinding> GenerateBindings(Alias tableAlias, QueryBinder binder, Expression id)
        {
            List<FieldBinding> result = new List<FieldBinding>();

           result.Add(new FieldBinding(Table.fiId, id));

            foreach (var ef in this.Fields.Values)
            {
                var fi = ef.FieldInfo;

                if (!ReflectionTools.FieldEquals(fi, fiId))
                    result.Add(new FieldBinding(fi, ef.Field.GetExpression(tableAlias, binder, id)));
            }


            return result.ToReadOnly();
        }
        internal Expression GetProjectorExpression(Alias tableAlias, QueryBinder binder)
        {
            Expression id = GetIdExpression(tableAlias);

            if (IsView)
            {
                var bindings = this.Fields.Values.Select(ef=>new FieldBinding(ef.FieldInfo, ef.Field.GetExpression(tableAlias, binder, id))).ToReadOnly();

                var hasValue = id == null ? Expression.Constant(true): SmartEqualizer.NotEqualNullable(id, Expression.Constant(null, id.Type.Nullify()));

                return new EmbeddedEntityExpression(this.Type, hasValue, bindings, null);
            }
            else
            {
                var bindings = GenerateBindings(tableAlias, binder, id); 
                var mixins = GenerateMixins(tableAlias, binder, id);

                Schema.Current.AssertAllowed(Type, inUserInterface: false);

                var result = new EntityExpression(this.Type, (PrimaryKeyExpression)id, tableAlias, bindings, mixins, avoidExpandOnRetrieving: false);

                return result; 
            }
        }
        internal override Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id)
        {
            var bindings = (from kvp in EmbeddedFields
                            let fi = kvp.Value.FieldInfo
                            select new FieldBinding(fi, kvp.Value.Field.GetExpression(tableAlias, binder, id))).ToReadOnly();

            Expression hasValue = HasValue == null ? SmartEqualizer.NotEqualNullable(id,
                id is PrimaryKeyExpression ? QueryBinder.NullId(((PrimaryKeyExpression)id).ValueType) : (Expression)Expression.Constant(null, id.Type.Nullify())) :
                new ColumnExpression(((IColumn)HasValue).Type, tableAlias, HasValue.Name);

            return new EmbeddedEntityExpression(this.FieldType, hasValue, bindings, this); 
        }
 internal override Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id)
 {
     return new MListExpression(FieldType, id, TableMList); // keep back id empty for some seconds 
 }
        internal override Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id)
        {
            Type cleanType = IsLite ? Lite.Extract(FieldType) : FieldType;

            var result = new EntityExpression(cleanType, new PrimaryKeyExpression(new ColumnExpression(this.Type.Nullify(), tableAlias, Name)), null, null, null, AvoidExpandOnRetrieving);

            if(this.IsLite)
                return binder.MakeLite(result, null);
            else 
                return result; 
        }
 internal override Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id)
 {
     return Expression.Convert(new ColumnExpression(this.Type, tableAlias, Name), FieldType);
 }
        internal override Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id)
        {
            Expression result = new ImplementedByAllExpression(IsLite ? Lite.Extract(FieldType) : FieldType,
                new ColumnExpression(Column.Type, tableAlias, Column.Name),
                new TypeImplementedByAllExpression(new PrimaryKeyExpression(new ColumnExpression(ColumnType.Type.Nullify(), tableAlias, ColumnType.Name))));

            if (this.IsLite)
                return binder.MakeLite(result, null);
            else
                return result;
        }
示例#42
0
        /// <summary>
        /// Example of using a user-defined aggregate
        /// </summary>
        /// <param name="application"></param>
        /// <param name="inputConfig"></param>
        /// <param name="outputConfig"></param>
        /// <param name="inputAdapter"></param>
        /// <param name="outputAdapter"></param>
        /// <returns></returns>
        private static Query createStandardDeviationExampleQuery(Application application, StockQuoteInputConfig inputConfig, StockQuoteOutputConfig outputConfig, InputAdapter inputAdapter, OutputAdapter outputAdapter)
        {
            var input = CepStream<StockQuote>.Create("input");
            var stddevCepStream = from w in input.Where(e => e.FieldID == "Close")
                                                             .HoppingWindow(TimeSpan.FromDays(7), TimeSpan.FromDays(1), HoppingWindowOutputPolicy.ClipToWindowEnd)
                                  select new StockQuote()
                                  {
                                      StockID = "ERIC",
                                      FieldID = "7-day Stddev",
                                      Value = w.StandardDeviation()
                                  };
            var queryTemplate = application.CreateQueryTemplate("standardDeviationExampleTemplate", "Description...", stddevCepStream);

            var queryBinder = new QueryBinder(queryTemplate);
            queryBinder.BindProducer<StockQuote>("input", inputAdapter, inputConfig, EventShape.Point);
            queryBinder.AddConsumer<StockQuote>("output", outputAdapter, outputConfig, EventShape.Point, StreamEventOrder.ChainOrdered);

            var query = application.CreateQuery("standardDeviationExampleQuery", "Description...", queryBinder);
            return query;
        }
 internal abstract Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id);
示例#44
0
 internal override Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id)
 {
     return new ColumnExpression(this.FieldType, tableAlias, this.Name);
 }
        internal Expression FieldExpression(Alias tableAlias, QueryBinder binder, bool withRowId)
        {
            var rowId = RowIdExpression(tableAlias);

            var exp = Field.GetExpression(tableAlias, binder, rowId);

            if (!withRowId)
                return exp;

            var type = this.Field.FieldType;

            var ci = typeof(MList<>.RowIdElement).MakeGenericType(type).GetConstructor(new[] { type, typeof(PrimaryKey), typeof(int?) });

            var order =  Order == null ? (Expression)Expression.Constant(null, typeof(int?)) : OrderExpression(tableAlias).Nullify();

            return Expression.New(ci, exp, rowId.UnNullify(), order);
        }
        internal Expression GetProjectorExpression(Alias tableAlias, QueryBinder binder)
        {
            Schema.Current.AssertAllowed(this.BackReference.ReferenceTable.Type, inUserInterface: false);

            Type elementType = typeof(MListElement<,>).MakeGenericType(BackReference.FieldType, Field.FieldType);

            var rowId = RowIdExpression(tableAlias);

            return new MListElementExpression(
                rowId,
                (EntityExpression)this.BackReference.GetExpression(tableAlias, binder, null),
                this.Order == null ? null: OrderExpression(tableAlias), 
                this.Field.GetExpression(tableAlias, binder, rowId), this);
        }
示例#47
0
        /// <summary>
        /// Example of detecting when stock price falls more than 10% in 7 days
        /// </summary>
        /// <param name="application"></param>
        /// <param name="inputConfig"></param>
        /// <param name="outputConfig"></param>
        /// <param name="inputAdapter"></param>
        /// <param name="outputAdapter"></param>
        /// <returns></returns>
        private static Query createBigLooserExampleQuery(Application application, StockQuoteInputConfig inputConfig, StockQuoteOutputConfig outputConfig, InputAdapter inputAdapter, OutputAdapter outputAdapter)
        {
            var input = CepStream<StockQuote>.Create("input");
            var bigLooserCepStream = (from e1 in input
                                      from e2 in input.ShiftEventTime(e => e.StartTime.AddDays(7))
                                      where e1.FieldID == "Close" && e2.FieldID == "Close"
                                      select new StockQuote()
                                      {
                                          StockID = "ERIC > 10% drop",
                                          FieldID = "Close",
                                          Value = (e1.Value - e2.Value) / e2.Value * 100
                                      }).Where(e => e.Value < -10);
            var queryTemplate = application.CreateQueryTemplate("bigLooserExampleTemplate", "Description...", bigLooserCepStream);

            var queryBinder = new QueryBinder(queryTemplate);
            queryBinder.BindProducer<StockQuote>("input", inputAdapter, inputConfig, EventShape.Point);
            queryBinder.AddConsumer<StockQuote>("output", outputAdapter, outputConfig, EventShape.Point, StreamEventOrder.ChainOrdered);

            var query = application.CreateQuery("bigLooserExampleQuery", "Description...", queryBinder);
            return query;
        }
示例#48
0
        /// <summary>
        /// Compare USD and SEK stock prices using given exchange rate. Example of a cross join.
        /// </summary>
        /// <param name="application"></param>
        /// <param name="ericUSDConfig"></param>
        /// <param name="ericSEKConfig"></param>
        /// <param name="USDSEKConfig"></param>
        /// <param name="outputConfig"></param>
        /// <param name="inputAdapter"></param>
        /// <param name="outputAdapter"></param>
        /// <returns></returns>
        private static Query createCrossJoinExampleQuery(Application application, StockQuoteInputConfig ericUSDConfig, StockQuoteInputConfig ericSEKConfig, StockQuoteInputConfig USDSEKConfig, StockQuoteOutputConfig outputConfig, InputAdapter inputAdapter, OutputAdapter outputAdapter)
        {
            var ericUSDStream = CepStream<StockQuote>.Create("ericUSDStream");
            var ericSEKStream = CepStream<StockQuote>.Create("ericSEKStream");
            var USDSEKStream = CepStream<StockQuote>.Create("USDSEKStream");
            var ericRecalcCepStream = from eUSD in ericUSDStream
                                      from eXch in USDSEKStream // Cross join
                                      where eUSD.FieldID == "Close"
                                      select new StockQuote()
                                      {
                                          StockID = "ERIC-Recalc",
                                          FieldID = "Close",
                                          Value = eUSD.Value * eXch.Value // Convert ERIC USD quote to SEK
                                      };

            var ericCompareCepStream = from eRecalc in ericRecalcCepStream
                                       from eSEK in ericSEKStream
                                       where eSEK.FieldID == "Close"
                                       select new StockQuote()
                                       {
                                           StockID = "ERIC-Compare",
                                           FieldID = "Diff",
                                           Value = eSEK.Value - eRecalc.Value
                                       };
            var queryTemplate = application.CreateQueryTemplate("ericCompareTemplate", "Description...", ericCompareCepStream);

            var queryBinder = new QueryBinder(queryTemplate);
            queryBinder.BindProducer<StockQuote>("ericUSDStream", inputAdapter, ericUSDConfig, EventShape.Point);
            queryBinder.BindProducer<StockQuote>("ericSEKStream", inputAdapter, ericSEKConfig, EventShape.Point);
            queryBinder.BindProducer<StockQuote>("USDSEKStream", inputAdapter, USDSEKConfig, EventShape.Point);
            queryBinder.AddConsumer<StockQuote>("output", outputAdapter, outputConfig, EventShape.Point, StreamEventOrder.ChainOrdered);

            var query = application.CreateQuery("ericCompareQuery", "Description...", queryBinder);
            return query;
        }
示例#49
0
        /// <summary>
        /// Example of a grouping and calculation of averages for the groups
        /// </summary>
        /// <param name="application"></param>
        /// <param name="inputConfig"></param>
        /// <param name="outputConfig"></param>
        /// <param name="inputAdapter"></param>
        /// <param name="outputAdapter"></param>
        /// <returns></returns>
        private static Query createGroupApplyExampleQuery(Application application, StockQuoteInputConfig inputConfig, StockQuoteOutputConfig outputConfig, InputAdapter inputAdapter, OutputAdapter outputAdapter)
        {
            var input = CepStream<StockQuote>.Create("input");
            var ericUSDGroupCepStream = from e in input
                                        group e by e.FieldID into eGroup
                                        from w in eGroup.HoppingWindow(TimeSpan.FromDays(7), TimeSpan.FromDays(1), HoppingWindowOutputPolicy.ClipToWindowEnd)
                                        select new StockQuote()
                                        {
                                            StockID = "ERIC 7-day avg",
                                            FieldID = eGroup.Key,
                                            Value = w.Avg(e => e.Value)
                                        };
            var queryTemplate = application.CreateQueryTemplate("groupApplyExampleTemplate", "Description...", ericUSDGroupCepStream);

            var queryBinder = new QueryBinder(queryTemplate);
            queryBinder.BindProducer<StockQuote>("input", inputAdapter, inputConfig, EventShape.Point);
            queryBinder.AddConsumer<StockQuote>("output", outputAdapter, outputConfig, EventShape.Point, StreamEventOrder.ChainOrdered);

            var query = application.CreateQuery("groupApplyExampleQuery", "Description...", queryBinder);
            return query;
        }
        internal override Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id)
        {
            var bindings = (from kvp in Fields
                            let fi = kvp.Value.FieldInfo
                            select new FieldBinding(fi, kvp.Value.Field.GetExpression(tableAlias, binder, id))).ToReadOnly();

            return new MixinEntityExpression(this.FieldType, bindings, tableAlias, this);
        }
示例#51
0
        internal override Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id)
        {
            var bindings = (from kvp in EmbeddedFields
                            let fi = kvp.Value.FieldInfo
                            select new FieldBinding(fi, kvp.Value.Field.GetExpression(tableAlias, binder, id))).ToReadOnly();

            Expression hasValue = HasValue == null ? SmartEqualizer.NotEqualNullable(id, QueryBinder.NullId) : new ColumnExpression(typeof(bool), tableAlias, HasValue.Name);
            return new EmbeddedEntityExpression(this.FieldType, hasValue, bindings, this); 
        }
        internal override Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id)
        {
            var implementations = ImplementationColumns.SelectDictionary(t => t, (t, ic) =>
                 new EntityExpression(t, new PrimaryKeyExpression(new ColumnExpression(ic.Type.Nullify(), tableAlias, ic.Name)), null, null, null, AvoidExpandOnRetrieving));

            var result = new ImplementedByExpression(IsLite ? Lite.Extract(FieldType) : FieldType, SplitStrategy, implementations);

            if (this.IsLite)
                return binder.MakeLite(result, null);
            else
                return result; 
        }
示例#53
0
        /// <summary>
        /// Event handler for Run button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="eventArgs"></param>
        private void RunBtn_Click(object sender, EventArgs eventArgs)
        {
            // Get selected source and query
            Source source;
            if (SourceDpl.SelectedItem.ToString() == "Browse...")
            {
                source = BrowseAndReadSource();
            }
            else
            {
                source = Sources.Single(s => s.Name == SourceDpl.SelectedItem.ToString());
            }
            var queryTemplate = Queries[QueryDpl.SelectedItem.ToString()];

            // Initialize display properties
            stockGraph1.StartDate = new DateTime(2009, 01, 01);
            stockGraph1.EndDate = new DateTime(2009, 12, 31);
            stockGraph1.GridDateSize = 30;
            stockGraph1.ValueLabelFormat = "f0";
            stockGraph1.DateLabelFormat = "dd MMM";

            stockGraph1.MaxValue = source.MaxValue;
            stockGraph1.MinValue = source.MinValue;
            stockGraph1.GridValueSize = source.GridValueSize;

            // Clear previous stock signals
            stockGraph1.Clear();

            // Instantiate query
            var queryBinder = new QueryBinder(queryTemplate);
            queryBinder.BindProducer<StockQuote>("input", application.InputAdapters["StockQuoteInput"], source.Config, EventShape.Point);
            queryBinder.AddConsumer<StockQuote>("output", application.OutputAdapters["StockSignalOutput"], new StockSignalOutputConfig(), EventShape.Point, StreamEventOrder.ChainOrdered);

            var query = application.CreateQuery(queryTemplate.ShortName + " " + Guid.NewGuid().ToString(), "Description...", queryBinder);

            backgroundWorker1.RunWorkerAsync(query);
        }
 internal override Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id)
 {
     return new PrimaryKeyExpression(new ColumnExpression(this.Type.Nullify(), tableAlias, this.Name).Nullify());
 }
示例#55
0
        /// <summary>
        /// Example of using a user-defined filter
        /// </summary>
        /// <param name="application"></param>
        /// <param name="inputConfig"></param>
        /// <param name="outputConfig"></param>
        /// <param name="inputAdapter"></param>
        /// <param name="outputAdapter"></param>
        /// <returns></returns>
        private static Query createUserFilterExampleQuery(Application application, StockQuoteInputConfig inputConfig, StockQuoteOutputConfig outputConfig, InputAdapter inputAdapter, OutputAdapter outputAdapter)
        {
            var input = CepStream<StockQuote>.Create("input");
            var filteredCepStream = from e in input
                                    where UserDefinedFilter(e.FieldID)
                                    select e;
            var queryTemplate = application.CreateQueryTemplate("userFilterExampleTemplate", "Description...", filteredCepStream);

            var queryBinder = new QueryBinder(queryTemplate);
            queryBinder.BindProducer<StockQuote>("input", inputAdapter, inputConfig, EventShape.Point);
            queryBinder.AddConsumer<StockQuote>("output", outputAdapter, outputConfig, EventShape.Point, StreamEventOrder.ChainOrdered);

            var query = application.CreateQuery("userFilterExampleQuery", "Description...", queryBinder);
            return query;
        }
示例#56
0
        /// <summary>
        /// Binds the query template to the specified adapters.
        /// </summary>
        /// <param name="inputAdapter">Input adapter metadata object to bind to all query template inputs.</param>
        /// <param name="outputAdapter">Input adapter metadata object to bind to the query template output.</param>
        /// <param name="queryTemplate">Query template to bind to adapters.</param>
        /// <returns>The query binder.</returns>
        private static QueryBinder BindQuery(InputAdapter inputAdapter, OutputAdapter outputAdapter, QueryTemplate queryTemplate)
        {
            // Create a query binder, wrapping the query template.
            QueryBinder queryBinder = new QueryBinder(queryTemplate);

            // Define the runtime configuration for both input adapters.
            var sensorInputConf = new TextFileReaderConfig
            {
                InputFileName = @"..\..\..\TrafficSensors.csv",
                Delimiter = ',',
                CtiFrequency = 9,
                CultureName = "en-US",
                InputFieldOrders = new Collection<string>() { "SensorId", "AverageSpeed", "VehicularCount" }
            };
            var locationInputConf = new TextFileReaderConfig
            {
                InputFileName = @"..\..\..\TrafficSensorLocations.csv",
                Delimiter = ',',
                CtiFrequency = 100,
                CultureName = "en-US",
                InputFieldOrders = new Collection<string>() { "SensorId", "LocationId" }
            };

            // Define the runtime configuration for the output adapter.
            // Specify an empty file name, which will just dump the output
            // events on the console. Also pass an event handle name to
            // synchronize the shutdown.
            var outputConf = new TextFileWriterConfig
            {
                OutputFileName = string.Empty,
                Delimiter = '\t'
            };

            // Bind input adapters to query template's input streams,
            // applying runtime configuration.
            // In this example, the given input file for sensor input
            // contains interval events (each sensor reading has a start
            // and end time), while the location input is represented by
            // edge events (for each event, the end time is not known in
            // advance).
            queryBinder.BindProducer("sensorInput", inputAdapter, sensorInputConf, EventShape.Interval);
            queryBinder.BindProducer("locationInput", inputAdapter, locationInputConf, EventShape.Edge);

            // Bind output adapter to query, applying runtime
            // configuration.
            queryBinder.AddConsumer<TextFileWriterConfig>("queryresult", outputAdapter, outputConf, EventShape.Point, StreamEventOrder.FullyOrdered);
            return queryBinder;
        }
        internal override Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id)
        {
            var column = new ColumnExpression(this.Type, tableAlias, this.Name);

            if(this.Type == this.FieldType)
                return column;

            return Expression.Convert(column, this.FieldType);
        }
        internal override Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id)
        {
            if (this.Type == this.FieldType)
               return new ColumnExpression(this.Type, tableAlias, this.Name);

            if (this.Type == typeof(DateTime))
                return Expression.Property(new ColumnExpression(this.Type, tableAlias, this.Name), piDateTimeTicks);

            throw new NotImplementedException("FieldTicks of type {0} not supported".FormatWith(this.Type));
        }
示例#59
0
        internal Expression FieldExpression(Alias tableAlias, QueryBinder binder)
        {
            var rowId = RowIdExpression(tableAlias);

            return Field.GetExpression(tableAlias, binder, rowId);
        }