Exemplo n.º 1
0
 private void BuildCTE_SelectItems(ISqlSelectQuery query, BuildQueryContext ctx, bool forTeeNodePath = false)
 {
     //ctx.IsBuildCTESelectItem = true;
     foreach (var si in query.Selects.Values)
     {
         FieldExpression fsi = si.Expression as FieldExpression;
         if (!Expression.IsNull(fsi))
         {
             if (Equals(fsi.Owner.Owner, null))
             {
                 if (forTeeNodePath)
                 {
                     ctx.AppendFormat("t.\"{0}\" \"{1}\",", fsi.Name, si.AliasName);
                 }
                 else
                 {
                     ctx.AppendFormat("t.\"{0}\",", fsi.Name);
                 }
             }
         }
         //else if (forTeeNodePath)
         //{
         //    var aggRefField = si.Expression as AggregationRefFieldExpression;
         //    if (!object.Equals(null, aggRefField))
         //    {
         //        BuildAggregationRefFieldExpression(aggRefField, ctx);
         //        ctx.AppendFormat(" \"{0}\",", si.AliasName);
         //    }
         //}
     }
     //ctx.IsBuildCTESelectItem = false;
 }
 protected internal override Expression VisitField(FieldExpression node)
 {
     return new FieldExpression(
         node.PrependFieldName(_prefix),
         node.Serializer,
         node.Original);
 }
Exemplo n.º 3
0
        protected override Expression VisitField(FieldExpression field)
        {
            _stringBuilder.Append(field.Name);

            if (!field.Properties.Any())
            {
                return(field);
            }

            _stringBuilder.Append("(");

            foreach (var(property, index) in field.Properties.WithIndex())
            {
                if (index > 0)
                {
                    _stringBuilder.Append(",");
                }

                _stringBuilder.Append(property.Name);
                Visit(property.Expression);
            }

            _stringBuilder.Append(")");

            return(field);
        }
Exemplo n.º 4
0
        public SerializationExpression BindProjector(ref Expression selector)
        {
            var projector = selector as SerializationExpression;

            if (selector.NodeType == ExpressionType.MemberInit || selector.NodeType == ExpressionType.New)
            {
                var serializer = SerializerBuilder.Build(selector, _serializerRegistry);

                projector = new DocumentExpression(serializer);
            }
            else if (projector == null || projector is PipelineExpression || projector is IFieldExpression || projector is ArrayIndexExpression)
            {
                var newFieldName = "__fld0";
                if (projector is IFieldExpression)
                {
                    // We don't have to do this, but it makes the output a little nicer.
                    newFieldName = ((IFieldExpression)projector).FieldName;
                }

                // the output of a $project stage must be a document, so
                // if this isn't already a serialization expression and it's not
                // a new expression or member init, then we need to create an
                // artificial field to project the computation into.
                var serializer = GetSerializer(selector.Type, selector);
                selector  = new FieldAsDocumentExpression(selector, newFieldName, serializer);
                projector = new FieldExpression(newFieldName, serializer);
            }

            return(projector);
        }
Exemplo n.º 5
0
        protected IFieldExpression CallMethodOnGroup
        (
            TypeCreator typeCreator,
            Expression parameter,
            LambdaExpression lambda,
            MethodInfo methodInfo
        )
        {
            var        queryType      = typeof(IQueryable <>).MakeGenericType(parameter.Type);
            var        queryParameter = Expression.Parameter(queryType);
            Expression expression     = queryParameter;

            var method = methodInfo
                         .MakeGenericMethod(parameter.Type);

            expression = Expression.Call
                         (
                method,
                expression,
                Expression.Quote(lambda)
                         );

            var fieldValue = new FieldExpression(expression, parameter);

            return(fieldValue);
        }
        private void ProcessFieldOwner(FieldExpression fieldExpression)
        {
            if (TreatEntityAsKey || fieldExpression.Owner == null)
            {
                return;
            }
            var entity    = fieldExpression.Owner as EntityExpression;
            var structure = fieldExpression.Owner as StructureFieldExpression;

            while (entity == null && structure != null)
            {
                entity    = structure.Owner as EntityExpression;
                structure = structure.Owner as StructureFieldExpression;
            }
            if (entity == null)
            {
                throw new InvalidOperationException(String.Format(Strings.ExUnableToResolveOwnerOfFieldExpressionX, fieldExpression));
            }

            AddColumns(fieldExpression,
                       entity
                       .Key
                       .Mapping
                       .GetItems()
                       .AddOne(entity
                               .Fields
                               .Single(field => field.Name == WellKnown.TypeIdFieldName)
                               .Mapping
                               .Offset));
        }
Exemplo n.º 7
0
 protected internal override Expression VisitField(FieldExpression node)
 {
     return(new FieldExpression(
                node.PrependFieldName(_prefix),
                node.Serializer,
                node.Original));
 }
Exemplo n.º 8
0
 protected override Expression VisitField(FieldExpression f)
 {
     _inField = true;
     var e = base.VisitField(f);
     _inField = false;
     return e;
 }
        protected override Expression VisitField(FieldExpression field)
        {
            if(!_isMapReduce)
                return Visit(field.Expression);
            
            var parts = field.Name.Split('.');

            bool isGroupingField = _determiner.IsGroupingKey(field);
            Expression current;
            if(parts.Contains("Key") && isGroupingField)
                current = _document;
            else
                current = Expression.Call(
                    _document,
                    "Get",
                    new[] {typeof(Document)},
                    Expression.Constant("value"));

            for(int i = 0, n = parts.Length; i < n; i++)
            {
                var type = i == n - 1 ? field.Type : typeof(Document);

                if(parts[i] == "Key" && isGroupingField)
                    parts[i] = "_id";

                current = Expression.Call(
                    current,
                    "Get",
                    new[] {type},
                    Expression.Constant(parts[i]));
            }

            return current;
        }
Exemplo n.º 10
0
        // private methods
        private Expression BindElementAt(MethodCallExpression node)
        {
            if (!ExpressionHelper.IsLinqMethod(node))
            {
                return(base.VisitMethodCall(node));
            }

            var newNode = base.VisitMethodCall(node);
            var methodCallExpression = newNode as MethodCallExpression;

            if (node != newNode && methodCallExpression != null &&
                (methodCallExpression.Method.DeclaringType == typeof(Enumerable) || methodCallExpression.Method.DeclaringType == typeof(Queryable)))
            {
                var serializationExpression = methodCallExpression.Arguments[0] as ISerializationExpression;
                if (serializationExpression != null)
                {
                    var arraySerializer = serializationExpression.Serializer as IBsonArraySerializer;
                    BsonSerializationInfo itemSerializationInfo;
                    if (arraySerializer != null && arraySerializer.TryGetItemSerializationInfo(out itemSerializationInfo))
                    {
                        var index   = (int)((ConstantExpression)methodCallExpression.Arguments[1]).Value;
                        var name    = index >= 0 ? index.ToString() : "$";
                        var newName = serializationExpression.AppendFieldName(name);

                        newNode = new FieldExpression(newName, itemSerializationInfo.Serializer, methodCallExpression);
                    }
                }
            }

            return(newNode);
        }
Exemplo n.º 11
0
        public static void FieldExpression_Parse_Url()
        {
            var sut = FieldExpression.Parse("$url");

            Assert.Equal(FieldExpressionType.Url, sut.ExpressionType);
            Assert.Equal("$url", sut.ToString());
        }
Exemplo n.º 12
0
        public static void FieldExpression_Parse_Method()
        {
            var sut = FieldExpression.Parse("$method");

            Assert.Equal(FieldExpressionType.Method, sut.ExpressionType);
            Assert.Equal("$method", sut.ToString());
        }
        private FieldExpression GetDottedFieldExpression(FieldExpression node)
        {
            var fieldNames = new List <string> {
                node.FieldName
            };
            var document = node.Document as FieldExpression;

            while (document != null)
            {
                fieldNames.Add(document.FieldName);
                document = document.Document as FieldExpression;
            }

            string dottedFieldName;

            if (fieldNames.Count > 1)
            {
                fieldNames.Reverse();
                dottedFieldName = string.Join(".", fieldNames);
            }
            else
            {
                dottedFieldName = fieldNames[0];
            }

            return(new FieldExpression(null, dottedFieldName, node.Serializer, node.Original));
        }
Exemplo n.º 14
0
        private void CheckFieldExpression(FieldExpression e, TypeCheckingContext context)
        {
            if (!e.IsStatic)
            {
                PerformTypeChecking(e.Operand, context);
            }


            e.Field = (e.IsStatic ? e.OwnerType : e.Operand.Type).GetField(e.FieldName);
            if (e.Field != null)
            {
                e.Type = e.Field.FieldType;
            }
            else
            {
                e.Property = (e.IsStatic ? e.OwnerType : e.Operand.Type).GetProperty(e.FieldName);
                if (e.Property != null)
                {
                    e.Type = e.Property.PropertyType;
                }
                else
                {
                    context.ErrorProvider.ThrowException(string.Format("Field or property {0}.{1} not found.", e.Operand.Type, e.FieldName), e);
                }
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Retrieve concrete expression of an fieldexpression
        /// </summary>
        /// <param name="expression">FieldExpression</param>
        /// <returns>Concrete expression</returns>
        private Expression GetExpression(FieldExpression expression)
        {
            Expression expr = expression.GetExpression();

            //Get real expression, not a variable
            while (expr is VarExpression)
            {
                expr = SymbolTable.GetVariableDefinition(((VarExpression)expr).GetVariableIdentifier());
            }

            //Get specific record from recordExpression
            if (expr is RecordExpression)
            {
                RecordExpression record      = (RecordExpression)expr;
                ISyntaxNode[]    recordArray = record.GetRecords().ToArray();
                foreach (KeyValuePair pair in recordArray)
                {
                    if (pair.GetKey() == expression.GetIdentifier())
                    {
                        return(pair.GetValue());
                    }
                }
            }
            return(null);
        }
Exemplo n.º 16
0
 public virtual Expression Visit(FieldExpression expression)
 {
     return(new FieldExpression(expression.Token, expression.Left.Accept(this))
     {
         EndToken = expression.EndToken
     });
 }
Exemplo n.º 17
0
        public Expression Bind(PipelineExpression pipeline, PipelineBindingContext bindingContext, MethodCallExpression node, IEnumerable <Expression> arguments)
        {
            var        source = pipeline.Source;
            Expression keySelector;
            var        previousSelectExpression = source as SelectExpression;

            if (previousSelectExpression != null)
            {
                keySelector = previousSelectExpression.Selector;
                source      = previousSelectExpression.Source;

                var fieldAsDocumentExpression = keySelector as FieldAsDocumentExpression;
                if (fieldAsDocumentExpression != null)
                {
                    keySelector = fieldAsDocumentExpression.Expression;
                }
            }
            else if (pipeline.Projector is FieldExpression)
            {
                keySelector = pipeline.Projector;
            }
            else
            {
                var currentProjector = (ISerializationExpression)pipeline.Projector;
                keySelector = new FieldExpression("$ROOT", currentProjector.Serializer);
            }

            var serializer = bindingContext.GetSerializer(keySelector.Type, keySelector);

            return(new PipelineExpression(
                       new GroupByExpression(
                           source,
                           keySelector),
                       new FieldExpression("_id", serializer)));
        }
Exemplo n.º 18
0
        public void IfThenClauseNegated()
        {
            // Arrange
            var mockField   = new Mock <IField>().Object;
            var expr        = new FieldExpression(mockField);
            var pred        = new ConstantClause(expr, ComparisonOperator.GTE, DBValue.Create(100));
            var subseq      = new ConstantClause(expr, ComparisonOperator.LTE, DBValue.Create(200));
            var subseqNeg   = new ConstantClause(expr, ComparisonOperator.GT, DBValue.Create(200));
            var clause      = Clause.IfThen(pred, subseq).Negation();
            var mockBuilder = new Mock <IConstraintDeclBuilder>();

            // Sequence
            var sequence = mockBuilder.MakeSequence();

            sequence.Add(builder => builder.StartClause());
            sequence.Add(builder => builder.AddClause(subseqNeg.Matcher()));
            sequence.Add(builder => builder.And());
            sequence.Add(builder => builder.AddClause(pred.Matcher()));
            sequence.Add(builder => builder.EndClause());

            // Act
            var fields = clause.GetDependentFields();

            clause.AddDeclarationTo(mockBuilder.Object);

            // Assert
            fields.Should().BeEquivalentTo(new IField[] { mockField, mockField });
            sequence.VerifyCompleted();
            mockBuilder.VerifyNoOtherCalls();
        }
Exemplo n.º 19
0
        private void EvalItem
        (
            TypeCreator typeCreator,
            Expression parameter,
            JObject jObject
        )
        {
            var props = jObject.Properties()
                        .ToDictionary(o => o.Name, o => o.Value);

            var left  = props["name"];
            var rule  = props["rule"];
            var right = props["value"];

            var leftExpression = typeCreator.BuildProjection(parameter, (JArray)left, false);

            var rightExpression = default(IFieldExpression);

            if (right is JArray)
            {
                rightExpression = typeCreator.BuildProjection(parameter, (JArray)right, false);
            }
            else
            {
                rightExpression = new FieldExpression(Expression.Constant(right.Value <object>()), parameter);
            }
        }
Exemplo n.º 20
0
        public static void FieldExpression_Parse_StatusCode()
        {
            var sut = FieldExpression.Parse("$statusCode");

            Assert.Equal(FieldExpressionType.StatusCode, sut.ExpressionType);
            Assert.Equal("$statusCode", sut.ToString());
        }
Exemplo n.º 21
0
        /// <summary>
        /// FieldExpression を作成する.
        /// </summary>
        /// <returns></returns>
        public static GeneratedExpression CreateField()
        {
            FieldExpression exp = new FieldExpression();

            exp.Type = ExpressionType.Field;
            return(exp);
        }
Exemplo n.º 22
0
        private bool Method(FieldExpression field, out MethodExpression op)
        {
            var args = ReadMethodArguments();

            op = new MethodExpression(field.FieldValue, args);
            return(true);
        }
Exemplo n.º 23
0
 protected override Expression VisitField(FieldExpression field)
 {
     FieldExpression mapped;
     if (_map.TryGetValue(field, out mapped))
         return mapped;
     return field;
 }
Exemplo n.º 24
0
        // protected methods
        protected override Expression VisitBinary(BinaryExpression node)
        {
            var newNode = base.VisitBinary(node);
            var binary  = newNode as BinaryExpression;

            if (binary != null && binary.NodeType == ExpressionType.ArrayIndex)
            {
                var serializationExpression = binary.Left as IBsonSerializationInfoExpression;
                if (serializationExpression != null)
                {
                    var arraySerializer = serializationExpression.SerializationInfo.Serializer as IBsonArraySerializer;
                    var indexExpression = binary.Right as ConstantExpression;
                    if (arraySerializer != null && indexExpression != null && indexExpression.Type == typeof(int))
                    {
                        var index = (int)indexExpression.Value;
                        var itemSerializationInfo = arraySerializer.GetItemSerializationInfo();
                        itemSerializationInfo = new BsonSerializationInfo(
                            index.ToString(),
                            itemSerializationInfo.Serializer,
                            itemSerializationInfo.NominalType);

                        var serializationInfo = serializationExpression.SerializationInfo.Merge(itemSerializationInfo);
                        newNode = new FieldExpression(binary, serializationInfo, serializationExpression.IsProjected);
                    }
                }
            }

            return(newNode);
        }
Exemplo n.º 25
0
        public Expression Bind(PipelineExpression pipeline, PipelineBindingContext bindingContext, MethodCallExpression node, IEnumerable <Expression> arguments)
        {
            var newType = node.Method.GetGenericArguments()[0];

            var serializer = bindingContext.GetSerializer(newType, pipeline.Projector);

            var projector      = pipeline.Projector;
            var fieldProjector = projector as IFieldExpression;

            if (fieldProjector != null)
            {
                projector = new FieldExpression(
                    fieldProjector.FieldName,
                    serializer);
            }
            else
            {
                projector = new DocumentExpression(serializer);
            }

            return(new PipelineExpression(
                       new WhereExpression(
                           pipeline.Source,
                           "__p",
                           Expression.TypeIs(pipeline.Projector, newType)),
                       projector));
        }
Exemplo n.º 26
0
        protected override Expression VisitBinary(BinaryExpression node)
        {
            var newNode          = base.VisitBinary(node);
            var binaryExpression = newNode as BinaryExpression;

            if (binaryExpression != null && binaryExpression.NodeType == ExpressionType.ArrayIndex)
            {
                var serializationExpression = binaryExpression.Left as ISerializationExpression;
                if (serializationExpression != null)
                {
                    var arraySerializer = serializationExpression.Serializer as IBsonArraySerializer;
                    var indexExpression = binaryExpression.Right as ConstantExpression;
                    BsonSerializationInfo itemSerializationInfo;
                    if (arraySerializer != null &&
                        indexExpression != null &&
                        indexExpression.Type == typeof(int) &&
                        arraySerializer.TryGetItemSerializationInfo(out itemSerializationInfo))
                    {
                        var index   = (int)indexExpression.Value;
                        var name    = index >= 0 ? index.ToString() : "$";
                        var newName = serializationExpression.AppendFieldName(name);

                        newNode = new FieldExpression(newName, itemSerializationInfo.Serializer, binaryExpression);
                    }
                }
            }

            return(newNode);
        }
Exemplo n.º 27
0
        protected override Expression VisitFieldExpression(FieldExpression expression)
        {
            var tupleExpression = GetTupleExpression(expression);

            // Materialize non-owned field.
            if (expression.Owner == null || expression.UnderlyingProperty == null)
            {
                if (expression.Field.IsEnum)
                {
                    var underlyingType = Enum.GetUnderlyingType(expression.Type.StripNullable());
                    if (expression.Field.IsNullable)
                    {
                        underlyingType = underlyingType.ToNullable();
                    }
                    var result = Expression.Convert(
                        tupleExpression.MakeTupleAccess(underlyingType, expression.Mapping.Offset),
                        expression.Type);
                    return(result);
                }
                if (typeof(Key).IsAssignableFrom(expression.Field.ValueType))
                {
                    Expression <Func <Domain, string, Key> > keyParseLambda = (d, s) => Key.Parse(d, s);
                    Expression <Func <ItemMaterializationContext, Domain> > domainExtractorLambda = imc => imc.Session.Domain;
                    var result = keyParseLambda.BindParameters(
                        domainExtractorLambda.BindParameters(itemMaterializationContextParameter),
                        tupleExpression.MakeTupleAccess(typeof(string), expression.Mapping.Offset));
                    return(result);
                }

                var tupleAccess = tupleExpression.MakeTupleAccess(expression.Type, expression.Mapping.Offset);
                return(tupleAccess);
            }

            return(MaterializeThroughOwner(expression, tupleExpression));
        }
Exemplo n.º 28
0
 protected override Expression VisitField(FieldExpression field)
 {
     if (_oldAliases.Contains(field.Alias))
     {
         return(new FieldExpression(field.Expression, _newAlias, field.Name, field.MemberMap));
     }
     return(field);
 }
Exemplo n.º 29
0
        protected virtual Expression VisitField(FieldExpression field)
        {
            var e = Visit(field.Expression);
            if (field.Expression != e)
                field = new FieldExpression(e, field.Alias, field.Name);

            return field;
        }
Exemplo n.º 30
0
        protected override Expression VisitField(FieldExpression f)
        {
            _inField = true;
            var e = base.VisitField(f);

            _inField = false;
            return(e);
        }
Exemplo n.º 31
0
        protected virtual Expression VisitField(FieldExpression field)
        {
            var properties = VisitFieldDeclarations(field.Properties);

            return(properties.Equals(field.Properties)
                ? field
                : new FieldExpression(field.Type, field.Name, properties));
        }
Exemplo n.º 32
0
        public UpdateBuilder<T> SetPartial<TV>(Expression<Func<T, TV>> field, Action<UpdateBuilder<TV>> build)
        {
            var expression = new FieldExpression<T, TV>(field);

            _updates.Add(new AqlUpdateSetPartial<T, TV>(expression.Field, (_fieldname ?? expression.Name) + "." + expression.Field, build));

            return this;
        }
Exemplo n.º 33
0
        public UpdateBuilder<T> Inc<TV>(Expression<Func<T, TV>> field, IAqlValue<TV> build)
        {
            var expression = new FieldExpression<T, TV>(field);

            _updates.Add(new AqlUpdateInc(expression.Field, (_fieldname ?? expression.Name), build));

            return this;
        }
Exemplo n.º 34
0
        protected override Expression VisitField(FieldExpression field)
        {
            if (field.Alias == this.documentAlias) {
                return Expression.Convert(Expression.Call(this.documentParameter, miGetValue, Expression.Constant(field.Name), Expression.Constant(field.Type)), field.Type);
            }

            return field;
        }
Exemplo n.º 35
0
        public UpdateBuilder<T> Set<TV>(Expression<Func<T, TV>> field, IAqlValue<TV> value)
        {
            var expression = new FieldExpression<T, TV>(field);

            _updates.Add(new AqlUpdateSetValue(expression.Field, value));

            return this;
        }
        public string Visit(FieldExpression node)
        {
            var codeWriter = new XzaarCodeWriter();

            codeWriter.Write(node.FieldType + " " + node.Name, currentIndent);
            codeWriter.NewLine();
            return(codeWriter.ToString());
        }
Exemplo n.º 37
0
        protected override Expression VisitField(FieldExpression field)
        {
            Alias newAlias;
            if (_map.TryGetValue(field.Alias, out newAlias))
                return new FieldExpression(field.Expression, newAlias, field.Name);

            return field;
        }
Exemplo n.º 38
0
        protected override Expression VisitField(FieldExpression field)
        {
            var fields = new FieldGatherer().Gather(field.Expression);
            if (fields.Count == 0)
                _fields.Add(field);
            else
                _fields.AddRange(fields);

            return base.VisitField(field);
        }
        protected internal override Expression VisitField(FieldExpression node)
        {
            var document = Visit(node.Document) as IFieldExpression;
            if (document != null)
            {
                return new FieldExpression(
                    node.PrependFieldName(document.FieldName),
                    node.Serializer,
                    node.Original);
            }

            return node;
        }
Exemplo n.º 40
0
        protected internal override Expression VisitField(FieldExpression node)
        {
            if (node.Document is IFieldExpression || node.Document is ArrayIndexExpression)
            {
                return node.Update(
                    Visit(node.Document),
                    node.Original);
            }

            return new FieldExpression(
                node.Document,
                node.PrependFieldName(_prefix),
                node.Serializer,
                node.Original);
        }
Exemplo n.º 41
0
        protected override Expression Visit(Expression expression)
        {
            if (this.candidates.Contains(expression))
              {
            if (expression.NodeType == (ExpressionType)LuceneExpressionType.Field)
            {
              FieldExpression field = (FieldExpression)expression;
              FieldExpression mapped;

              if (this.map.TryGetValue(field, out mapped))
              {
            return mapped;
              }

              if (this.existingAlias == field.Alias)
              {
            int ordinal = this.fields.Count;
            string fieldName = this.GetUniqueFieldName(field.Name);
            this.fields.Add(new FieldDeclaration(fieldName, field));
            mapped = new FieldExpression(field.Type, this.newAlias, fieldName, ordinal, field.Analyzer);
            this.map[field] = mapped;
            this.fieldNames.Add(fieldName);
            return mapped;
              }

              // must be referring to outer scope
              return field;
            }

            else
            {
              string fieldName = this.GetNextFieldName();
              int ordinal = this.fields.Count;
              this.fields.Add(new FieldDeclaration(fieldName, expression));
              return new FieldExpression(expression.Type, this.newAlias, fieldName, ordinal, new StandardAnalyzer());
            }
              }
              else
              {
            return base.Visit(expression);
              }
        }
Exemplo n.º 42
0
        protected override Expression VisitField(FieldExpression field)
        {
            if (!_isMapReduce)
                return Visit(field.Expression);

            var parts = field.Name.Split('.');

            bool isGroupingField = _determiner.IsGroupingKey(field);
            Expression current;
            if (parts.Contains("Key") && isGroupingField)
                current = _document;
            else
                current = Expression.Call(
                            _document,
                            "GetValue",
                            Type.EmptyTypes,
                            Expression.Constant("value"));

            for (int i = 0; i < parts.Length; i++)
            {
                if (parts[i] == "Key" && isGroupingField)
                    parts[i] = "_id";

                current = Expression.Call(
                        Expression.Convert(
                            current,
                            typeof(BsonDocument)),
                        "GetValue",
                        Type.EmptyTypes,
                        Expression.Constant(parts[i]));
            }

            return Expression.Convert(
                current = Expression.Call(
                    typeof(Convert),
                    "ChangeType",
                    Type.EmptyTypes,
                    Expression.MakeMemberAccess(current, typeof(BsonValue).GetProperty("RawValue")),
                    Expression.Constant(field.Type)),
                field.Type);
        }
Exemplo n.º 43
0
        protected override Expression VisitSelect(SelectExpression select)
        {
            select = (SelectExpression)base.VisitSelect(select);

            var fields = select.Fields.OrderBy(f => f.Name).ToList();
            var removed = new BitArray(fields.Count);
            var anyRemoved = false;
            for (int i = 0, n = fields.Count; i < n; i++)
            {
                var fi = fields[i];
                var fxi = new FieldExpression(fi.Expression, select.Alias, fi.Name);
                for (int j = i + 1; j < n; j++)
                {
                    if (!removed.Get(i))
                    {
                        FieldDeclaration fj = fields[j];
                        if (AreSameExpression(fi.Expression, fj.Expression))
                        {
                            var fxj = new FieldExpression(fj.Expression, select.Alias, fj.Name);
                            _map.Add(fxj, fxi);
                            removed.Set(j, true);
                            anyRemoved = true;
                        }
                    }
                }
            }

            if (anyRemoved)
            {
                var newFields = new List<FieldDeclaration>();
                for (int i = 0, n = fields.Count; i < n; i++)
                {
                    if (!removed.Get(i))
                        newFields.Add(fields[i]);
                }
                select = select.SetFields(newFields);
            }
            return select;
        }
Exemplo n.º 44
0
 protected override Expression VisitField(FieldExpression f)
 {
     return f;
 }
Exemplo n.º 45
0
        private BsonClassMap BuildClassMap(Type type, ProjectionMapping mapping)
        {
            if (type == null || type == typeof(object))
            {
                return null;
            }

            var baseClassMap = BuildClassMap(type.GetTypeInfo().BaseType, mapping);
            if (baseClassMap != null)
            {
                baseClassMap.Freeze();
            }
            var classMap = new BsonClassMap(type, baseClassMap);

            foreach (var memberMapping in mapping.Members.Where(x => x.Member.DeclaringType == type))
            {
                var serializationExpression = memberMapping.Expression as SerializationExpression;
                if (serializationExpression == null)
                {
                    var serializer = Build(memberMapping.Expression);
                    serializationExpression = new FieldExpression(
                        memberMapping.Member.Name,
                        serializer,
                        memberMapping.Expression);
                }

                var memberMap = classMap.MapMember(memberMapping.Member)
                    .SetSerializer(serializationExpression.Serializer)
                    .SetElementName(memberMapping.Member.Name);

                if (classMap.IdMemberMap == null && serializationExpression is GroupingKeyExpression)
                {
                    classMap.SetIdMember(memberMap);
                }
            }

            return classMap;
        }
 protected internal virtual Expression VisitField(FieldExpression node)
 {
     return node.Update(
         Visit(node.Document),
         node.Original);
 }
Exemplo n.º 47
0
        private Expression VisitCorrelatedGroup(CorrelatedExpression node)
        {
            var groupExpression = (GroupByExpression)node.Expression;
            if (_accumulatorLookup != null && _accumulatorLookup.Contains(node.CorrelationId))
            {
                var source = Visit(groupExpression.Source);
                var accumulators = new List<AccumulatorExpression>();
                var fieldExpressions = new List<FieldExpression>();
                var comparer = new ExpressionComparer();
                foreach (var correlatedAccumulator in _accumulatorLookup[node.CorrelationId])
                {
                    var index = accumulators.FindIndex(x => comparer.Compare((Expression)x, correlatedAccumulator.Expression));

                    FieldExpression fieldExpression;
                    if (index == -1)
                    {
                        var accumulator = (AccumulatorExpression)correlatedAccumulator.Expression;

                        // TODO: might not need to do any renames...
                        accumulator = new AccumulatorExpression(
                            accumulator.Type,
                            "__agg" + accumulators.Count,
                            accumulator.Serializer,
                            accumulator.AccumulatorType,
                            accumulator.Argument);

                        accumulators.Add(accumulator);
                        fieldExpression = new FieldExpression(accumulator.FieldName, accumulator.Serializer);
                        fieldExpressions.Add(fieldExpression);
                    }
                    else
                    {
                        fieldExpression = fieldExpressions[index];
                    }

                    _accumulatorReplacementMap[correlatedAccumulator] = fieldExpression;
                }

                groupExpression = new GroupByExpression(
                    groupExpression.Type,
                    source,
                    groupExpression.KeySelector,
                    accumulators.AsReadOnly());
            }

            return Visit(groupExpression);
        }
        private BsonValue TranslateField(FieldExpression expression)
        {
            if (expression.Document == null)
            {
                return "$" + expression.FieldName;
            }

            // 2 possibilities. 
            // 1. This is translatable into a single string:
            // 2. This has an array index operation in it which we must then use a $let expression for
            var parent = expression.Document;
            var currentName = expression.FieldName;
            while (parent != null)
            {
                var field = parent as IFieldExpression;
                if (field != null)
                {
                    currentName = field.FieldName + "." + currentName;
                    parent = field.Document;
                }
                else
                {
                    var array = parent as ArrayIndexExpression;
                    if (array != null)
                    {
                        return new BsonDocument("$let", new BsonDocument
                        {
                            { "vars", new BsonDocument("item", TranslateValue(parent)) },
                            { "in", "$$item." + currentName }
                        });
                    }

                    break;
                }
            }

            return "$" + currentName;
        }
Exemplo n.º 49
0
			protected internal override void VisitFieldExpression(FieldExpression expression)
			{
				WriteMemberAccess((ComponentMetadata)expression.Field.DeclaringObject);
				_writer.Append("{0}", expression.Field.Name);
			}
Exemplo n.º 50
0
 protected override Expression VisitField(FieldExpression field)
 {
     QueryString.Append(field.Name).Append(":");
     return field;
 }
Exemplo n.º 51
0
        public virtual LinqExpression VisitField(FieldExpression field)
        {
            var target = Visit(field.Target);
            var mi = target.Type.GetFieldOrProperty(field.Name);

            if (mi is FieldInfo)
            {
                return LinqExpression.Field(target, (FieldInfo)mi);
            }

            if (mi is PropertyInfo)
            {
                return LinqExpression.Property(target, (PropertyInfo)mi);
            }

            throw new NotSupportedException(field.ToString());
        }
Exemplo n.º 52
0
 protected override Expression VisitField(FieldExpression field)
 {
     if (_oldAliases.Contains(field.Alias))
         return new FieldExpression(field.Expression, _newAlias, field.Name);
     return field;
 }
Exemplo n.º 53
0
        private BindResult RebindOrderings(IEnumerable<OrderExpression> orderings, Alias alias, ICollection<Alias> existingAliases, IEnumerable<FieldDeclaration> existingFields)
        {
            List<FieldDeclaration> newFields = null;
            var newOrderings = new List<OrderExpression>();
            foreach (var ordering in orderings)
            {
                var expression = ordering.Expression;
                var field = expression as FieldExpression;

                if(field != null && (existingAliases == null || !existingAliases.Contains(field.Alias)))
                    continue;
                
                int ordinal = 0;
                foreach (var fieldDecl in existingFields)
                {
                    var fieldDeclExpression = fieldDecl.Expression as FieldExpression;
                    if (fieldDecl.Expression == ordering.Expression || (field != null && fieldDeclExpression != null && field.Alias == fieldDeclExpression.Alias && field.Name == fieldDeclExpression.Name))
                    {
                        if(field != null)
                            expression = new FieldExpression(field.Expression, alias, fieldDecl.Name, field.MemberMap);
                        break;
                    }
                    ordinal++;
                }

                if (expression == ordering.Expression)
                {
                    if (newFields == null)
                    {
                        newFields = new List<FieldDeclaration>(existingFields);
                        existingFields = newFields;
                    }

                    var fieldName = field != null ? field.Name : "_$f" + ordinal;
                    newFields.Add(new FieldDeclaration(fieldName, ordering.Expression));
                    expression = new FieldExpression(expression, alias, fieldName);
                }

                newOrderings.Add(new OrderExpression(ordering.OrderType, expression));
            }
            return new BindResult(existingFields, newOrderings);
        }
Exemplo n.º 54
0
 public string GetExpression(FieldExpression expression, ref List<OleDbParameter> parameters)
 {
     return " " + _entityQueryWrapper.GetDbFieldName(expression.FieldName) + " ";
 }
Exemplo n.º 55
0
			protected internal override void VisitFieldExpression(FieldExpression expression)
			{
				_expr = Ssm.Expr.NewVarExpr(Ssm.Var.NewField(expression.Field.Name, Transform(expression.Field.Type)));
			}
        public SerializationExpression BindProjector(ref Expression selector)
        {
            var projector = selector as SerializationExpression;
            if (selector.NodeType == ExpressionType.MemberInit || selector.NodeType == ExpressionType.New)
            {
                var serializer = GetSerializer(selector.Type, selector);
                projector = new DocumentExpression(serializer);
            }
            else if (projector == null || projector is IFieldExpression || projector is ArrayIndexExpression)
            {
                var newFieldName = "__fld0";
                if (projector is IFieldExpression)
                {
                    // We don't have to do this, but it makes the output a little nicer.
                    newFieldName = ((IFieldExpression)projector).FieldName;
                }

                // the output of a $project stage must be a document, so 
                // if this isn't already a serialization expression and it's not
                // a new expression or member init, then we need to create an 
                // artificial field to project the computation into.
                var serializer = GetSerializer(selector.Type, selector);
                selector = new FieldAsDocumentExpression(selector, newFieldName, serializer);
                projector = new FieldExpression(newFieldName, serializer);
            }

            return projector;
        }
 protected virtual bool CompareField(FieldExpression a, FieldExpression b)
 {
     return CompareAlias(a.Alias, b.Alias) && a.Name == b.Name && Compare(a.Expression, b.Expression);
 }
 private BsonValue TranslateField(FieldExpression expression)
 {
     return "$" + expression.FieldName;
 }
Exemplo n.º 59
0
		/// <summary>
		///     Visits an element of type <see cref="FieldExpression" />.
		/// </summary>
		/// <param name="expression">The <see cref="FieldExpression" /> instance that should be visited.</param>
		protected internal virtual void VisitFieldExpression(FieldExpression expression)
		{
			DefaultVisit(expression);
		}
 protected internal virtual Expression VisitField(FieldExpression node)
 {
     return node;
 }