Esempio n. 1
0
        public override ProjectionExpression GetQueryExpression(MappingEntity entity)
        {
            var tableAlias  = new TableAlias();
            var selectAlias = new TableAlias();
            var table       = new TableExpression(tableAlias, entity, this.mapping.GetTableName(entity));

            Expression projector = this.GetEntityExpression(table, entity);
            var        pc        = ColumnProjector.ProjectColumns(this.translator.Linguist.Language, projector, null, selectAlias, tableAlias);

            var proj = new ProjectionExpression(
                new SelectExpression(selectAlias, pc.Columns, table, null),
                pc.Projector
                );

            return((ProjectionExpression)this.Translator.Police.ApplyPolicy(proj, entity.ElementType));
        }
Esempio n. 2
0
        public override Expression GetInsertExpression(MappingEntity entity, Expression instance, LambdaExpression selector)
        {
            var tableAlias  = new TableAlias();
            var table       = new TableExpression(tableAlias, entity, this.mapping.GetTableName(entity));
            var assignments = this.GetColumnAssignments(table, instance, entity, (e, m) => !(mapping.IsGenerated(e, m) || mapping.IsReadOnly(e, m)));   // #MLCHANGE

            if (selector != null)
            {
                return(new BlockCommand(
                           new InsertCommand(table, assignments),
                           this.GetInsertResult(entity, instance, selector, null)
                           ));
            }

            return(new InsertCommand(table, assignments));
        }
Esempio n. 3
0
        protected virtual Expression GetUpdateResult(MappingEntity entity, Expression instance, LambdaExpression selector)
        {
            var tq = this.GetQueryExpression(entity);

            var where = this.GetIdentityCheck(tq.Select, entity, instance);
            var selection = DbExpressionReplacer.Replace(selector.Body, selector.Parameters[0], tq.Projector);
            var newAlias  = new TableAlias();
            var pc        = DbColumnProjector.ProjectColumns(this.translator.Linguist.Language, selection, null, newAlias, tq.Select.Alias);

            return(new DbProjectionExpression
                   (
                       new DbSelectExpression(newAlias, pc.Columns, tq.Select, where),
                       pc.Projector,
                       DbAggregator.GetAggregator(selector.Body.Type, typeof(IEnumerable <>).MakeGenericType(selector.Body.Type))
                   ));
        }
        private bool GetEquiJoinKeyExpressions(Expression predicate, TableAlias outerAlias, List <Expression> outerExpressions, List <Expression> innerExpressions)
        {
            if (predicate.NodeType == ExpressionType.Equal)
            {
                var b = (BinaryExpression)predicate;
                ColumnExpression leftCol  = this.GetColumnExpression(b.Left);
                ColumnExpression rightCol = this.GetColumnExpression(b.Right);
                if (leftCol != null && rightCol != null)
                {
                    if (leftCol.Alias == outerAlias)
                    {
                        outerExpressions.Add(b.Left);
                        innerExpressions.Add(b.Right);
                        return(true);
                    }
                    else if (rightCol.Alias == outerAlias)
                    {
                        innerExpressions.Add(b.Left);
                        outerExpressions.Add(b.Right);
                        return(true);
                    }
                }
            }

            bool hadKey = false;
            var  parts  = predicate.Split(ExpressionType.And, ExpressionType.AndAlso);

            if (parts.Length > 1)
            {
                foreach (var part in parts)
                {
                    bool hasOuterAliasReference = ReferencedAliasGatherer.Gather(part).Contains(outerAlias);
                    if (hasOuterAliasReference)
                    {
                        if (!GetEquiJoinKeyExpressions(part, outerAlias, outerExpressions, innerExpressions))
                        {
                            return(false);
                        }
                        hadKey = true;
                    }
                }
            }

            return(hadKey);
        }
Esempio n. 5
0
 private ColumnProjector(QueryLanguage language, ProjectionAffinity affinity, Expression expression, IEnumerable <ColumnDeclaration> existingColumns, TableAlias newAlias, IEnumerable <TableAlias> existingAliases)
 {
     this.language        = language;
     this.newAlias        = newAlias;
     this.existingAliases = new HashSet <TableAlias>(existingAliases);
     this.map             = new Dictionary <ColumnExpression, ColumnExpression>();
     if (existingColumns != null)
     {
         this.columns     = new List <ColumnDeclaration>(existingColumns);
         this.columnNames = new HashSet <string>(existingColumns.Select(c => c.Name));
     }
     else
     {
         this.columns     = new List <ColumnDeclaration>();
         this.columnNames = new HashSet <string>();
     }
     this.candidates = Nominator.Nominate(language, affinity, expression);
 }
        protected override Expression VisitProjection(ProjectionExpression proj)
        {
            if (isTopLevel)
            {
                isTopLevel         = false;
                this.currentSelect = proj.Select;
                Expression projector = this.Visit(proj.Projector);
                if (projector != proj.Projector || this.currentSelect != proj.Select)
                {
                    return(new ProjectionExpression(this.currentSelect, projector, proj.Aggregator));
                }
                return(proj);
            }

            if (proj.IsSingleton && this.CanJoinOnServer(this.currentSelect))
            {
                TableAlias newAlias = new TableAlias();
                this.currentSelect = this.currentSelect.AddRedundantSelect(this.language, newAlias);

                // remap any references to the outer select to the new alias;
                SelectExpression source = (SelectExpression)ColumnMapper.Map(proj.Select, newAlias, this.currentSelect.Alias);

                // add outer-join test
                ProjectionExpression pex = this.language.AddOuterJoinTest(new ProjectionExpression(source, proj.Projector));

                var pc = ColumnProjector.ProjectColumns(this.language, pex.Projector, this.currentSelect.Columns, this.currentSelect.Alias, newAlias, proj.Select.Alias);

                JoinExpression join = new JoinExpression(JoinType.OuterApply, this.currentSelect.From, pex.Select, null);

                this.currentSelect = new SelectExpression(this.currentSelect.Alias, pc.Columns, join, null);
                return(this.Visit(pc.Projector));
            }

            var saveTop    = this.isTopLevel;
            var saveSelect = this.currentSelect;

            this.isTopLevel    = true;
            this.currentSelect = null;
            Expression result = base.VisitProjection(proj);

            this.isTopLevel    = saveTop;
            this.currentSelect = saveSelect;
            return(result);
        }
        public override Expression GetUpdateExpression(MappingEntity entity, Expression instance, LambdaExpression updateCheck, LambdaExpression selector, Expression @else)
        {
            var tableAlias = new TableAlias();
            var table      = new TableExpression(tableAlias, entity, this.mapping.GetTableName(entity));

            var where = this.GetIdentityCheck(table, entity, instance);
            if (updateCheck != null)
            {
                Expression typeProjector = this.GetEntityExpression(table, entity);
                Expression pred          = DbExpressionReplacer.Replace(updateCheck.Body, updateCheck.Parameters[0], typeProjector);
                where = where.And(pred);
            }

            var assignments = this.GetColumnAssignments(table, instance, entity, (e, m) => this.mapping.IsUpdatable(e, m));

            Expression update = new UpdateCommand(table, where, assignments);

            if (selector != null)
            {
                return(new BlockCommand(
                           update,
                           new IFCommand(
                               this.translator.Linguist.Language.GetRowsAffectedExpression(update).GreaterThan(Expression.Constant(0)),
                               this.GetUpdateResult(entity, instance, selector),
                               @else
                               )
                           ));
            }
            else if (@else != null)
            {
                return(new BlockCommand(
                           update,
                           new IFCommand(
                               this.translator.Linguist.Language.GetRowsAffectedExpression(update).LessThanOrEqual(Expression.Constant(0)),
                               @else,
                               null
                               )
                           ));
            }
            else
            {
                return(update);
            }
        }
Esempio n. 8
0
        public override Expression GetInsertExpression(MappingEntity entity, Expression instance, LambdaExpression selector)
        {
            var tables = this.mapping.GetTables(entity);

            if (tables.Count < 2)
            {
                return(base.GetInsertExpression(entity, instance, selector));
            }

            var commands = new List <Expression>();

            var map    = this.GetDependentGeneratedColumns(entity);
            var vexMap = new Dictionary <MemberInfo, Expression>();

            foreach (var table in this.GetDependencyOrderedTables(entity))
            {
                var tableAlias  = new TableAlias();
                var tex         = new DbTableExpression(tableAlias, entity, this.mapping.GetTableName(table));
                var assignments = this.GetColumnAssignments
                                  (
                    tex, instance, entity,
                    (e, m) => this.mapping.GetAlias(e, m) == this.mapping.GetAlias(table) && !this.mapping.IsGenerated(e, m),
                    vexMap
                                  );
                var totalAssignments = assignments.Concat(this.GetRelatedColumnAssignments(tex, entity, table, vexMap));

                commands.Add(new DbInsertCommand(tex, totalAssignments));

                if (map.TryGetValue(this.mapping.GetAlias(table), out List <MemberInfo> members))
                {
                    var d = this.GetDependentGeneratedVariableDeclaration(entity, table, members, instance, vexMap);

                    commands.Add(d);
                }
            }

            if (selector != null)
            {
                commands.Add(this.GetInsertResult(entity, instance, selector, vexMap));
            }

            return(new DbBlockCommand(commands));
        }
        public override Expression GetMemberExpression(Expression root, MappingEntity entity, MemberInfo member)
        {
            if (this.mapping.IsAssociationRelationship(entity, member))
            {
                MappingEntity        relatedEntity = this.mapping.GetRelatedEntity(entity, member);
                ProjectionExpression projection    = this.GetQueryExpression(relatedEntity);

                // make where clause for joining back to 'root'
                var declaredTypeMembers = this.mapping.GetAssociationKeyMembers(entity, member).ToList();
                var associatedMembers   = this.mapping.GetAssociationRelatedKeyMembers(entity, member).ToList();

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

                TableAlias newAlias = new TableAlias();
                var        pc       = ColumnProjector.ProjectColumns(this.translator.Linguist.Language, projection.Projector, null, newAlias, projection.Select.Alias);

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

                return(this.translator.Police.ApplyPolicy(result, member));
            }
            else
            {
                AliasedExpression aliasedRoot = root as AliasedExpression;
                if (aliasedRoot != null && this.mapping.IsColumn(entity, member))
                {
                    return(new ColumnExpression(TypeHelper.GetMemberType(member), this.GetColumnType(entity, member), aliasedRoot.Alias, this.mapping.GetColumnName(entity, member)));
                }
                return(QueryBinder.BindMember(root, member));
            }
        }
Esempio n. 10
0
        private Expression MakeSubquery(Expression expression)
        {
            var newAlias = new TableAlias();
            var aliases  = DeclaredAliasGatherer.Gather(expression);

            var decls = new List <ColumnDeclaration>();

            foreach (var ta in aliases)
            {
                foreach (var col in this.columns[ta])
                {
                    string name = decls.GetAvailableColumnName(col.Name);
                    var    decl = new ColumnDeclaration(name, col, col.QueryType);
                    decls.Add(decl);
                    var newCol = new ColumnExpression(col.Type, col.QueryType, newAlias, col.Name);
                    this.map.Add(col, newCol);
                }
            }

            return(new SelectExpression(newAlias, decls, expression, null));
        }
        protected virtual DeclarationCommand GetGeneratedIdCommand(MappingEntity entity, List <MemberInfo> members, Dictionary <MemberInfo, Expression> map)
        {
            var columns = new List <ColumnDeclaration>();
            var decls   = new List <VariableDeclaration>();
            var alias   = new TableAlias();

            foreach (var member in members)
            {
                Expression genId   = this.translator.Linguist.Language.GetGeneratedIdExpression(member);
                var        name    = member.Name;
                var        colType = this.GetColumnType(entity, member);
                columns.Add(new ColumnDeclaration(member.Name, genId, colType));
                decls.Add(new VariableDeclaration(member.Name, colType, new ColumnExpression(genId.Type, colType, alias, member.Name)));
                if (map != null)
                {
                    var vex = new VariableExpression(member.Name, TypeHelper.GetMemberType(member), colType);
                    map.Add(member, vex);
                }
            }
            var select = new SelectExpression(alias, columns, null, null);

            return(new DeclarationCommand(decls, select));
        }
Esempio n. 12
0
 public SelectExpression(
     TableAlias alias,
     IEnumerable <ColumnDeclaration> columns,
     Expression from,
     Expression where,
     IEnumerable <OrderExpression> orderBy,
     IEnumerable <Expression> groupBy,
     bool isDistinct,
     Expression skip,
     Expression take,
     bool isReverse
     )
     : base(DbExpressionType.Select, typeof(void), alias)
 {
     this.Columns    = columns.ToReadOnly();
     this.IsDistinct = isDistinct;
     this.From       = from;
     this.Where      = where;
     this.OrderBy    = orderBy.ToReadOnly();
     this.GroupBy    = groupBy.ToReadOnly();
     this.Take       = take;
     this.Skip       = skip;
     this.IsReverse  = isReverse;
 }
Esempio n. 13
0
        protected virtual BindResult RebindOrderings(IEnumerable <DbOrderExpression> orderings, TableAlias alias, HashSet <TableAlias> existingAliases, IEnumerable <DbColumnDeclaration> existingColumns)
        {
            var newColumns   = null as List <DbColumnDeclaration>;
            var newOrderings = new List <DbOrderExpression>();

            foreach (var ordering in orderings)
            {
                var expr   = ordering.Expression;
                var column = expr as DbColumnExpression;

                if (column == null || (existingAliases != null && existingAliases.Contains(column.Alias)))
                {
                    var iOrdinal = 0;

                    foreach (var decl in existingColumns)
                    {
                        var declColumn = decl.Expression as DbColumnExpression;

                        if (decl.Expression == ordering.Expression || (column != null && declColumn != null && column.Alias == declColumn.Alias && column.Name == declColumn.Name))
                        {
                            expr = new DbColumnExpression(column.Type, column.QueryType, alias, decl.Name);

                            break;
                        }

                        iOrdinal++;
                    }

                    if (expr == ordering.Expression)
                    {
                        if (newColumns == null)
                        {
                            newColumns      = new List <DbColumnDeclaration>(existingColumns);
                            existingColumns = newColumns;
                        }

                        var colName = column != null ? column.Name : "c" + iOrdinal;

                        colName = newColumns.GetAvailableColumnName(colName);

                        var colType = this.language.TypeSystem.GetColumnType(expr.Type);

                        newColumns.Add(new DbColumnDeclaration(colName, ordering.Expression, colType));

                        expr = new DbColumnExpression(expr.Type, colType, alias, colName);
                    }

                    newOrderings.Add(new DbOrderExpression(ordering.OrderType, expr));
                }
            }

            return(new BindResult(existingColumns, newOrderings));
        }
Esempio n. 14
0
        internal override DbProjectionExpression GetQueryExpression(MappingEntity entity)
        {
            var tables = this.mapping.GetTables(entity);

            if (tables.Count <= 1)
            {
                return(base.GetQueryExpression(entity));
            }

            var aliases   = new Dictionary <string, TableAlias>();
            var rootTable = tables.Single(ta => !this.mapping.IsExtensionTable(ta));
            var tex       = new DbTableExpression(new TableAlias(), entity, this.mapping.GetTableName(rootTable));

            aliases.Add(this.mapping.GetAlias(rootTable), tex.Alias);

            var source = tex as Expression;

            foreach (var table in tables.Where(t => this.mapping.IsExtensionTable(t)))
            {
                var joinedTableAlias = new TableAlias();
                var extensionAlias   = this.mapping.GetAlias(table);

                aliases.Add(extensionAlias, joinedTableAlias);

                var keyColumns     = this.mapping.GetExtensionKeyColumnNames(table).ToList();
                var relatedMembers = this.mapping.GetExtensionRelatedMembers(table).ToList();
                var relatedAlias   = this.mapping.GetExtensionRelatedAlias(table);

                aliases.TryGetValue(relatedAlias, out TableAlias relatedTableAlias);

                var joinedTex = new DbTableExpression(joinedTableAlias, entity, this.mapping.GetTableName(table));
                var cond      = null as Expression;

                for (int i = 0, n = keyColumns.Count; i < n; i++)
                {
                    var memberType    = TypeHelper.GetMemberType(relatedMembers[i]);
                    var colType       = this.GetColumnType(entity, relatedMembers[i]);
                    var relatedColumn = new DbColumnExpression(memberType, colType, relatedTableAlias, this.mapping.GetColumnName(entity, relatedMembers[i]));
                    var joinedColumn  = new DbColumnExpression(memberType, colType, joinedTableAlias, keyColumns[i]);
                    var eq            = joinedColumn.Equal(relatedColumn);

                    cond = (cond != null) ? cond.And(eq) : eq;
                }

                source = new DbJoinExpression(JoinType.SingletonLeftOuter, source, joinedTex, cond);
            }

            var columns = new List <DbColumnDeclaration>();

            this.GetColumns(entity, aliases, columns);

            var root            = new DbSelectExpression(new TableAlias(), columns, source, null);
            var existingAliases = aliases.Values.ToArray();

            var projector   = this.GetEntityExpression(root, entity) as Expression;
            var selectAlias = new TableAlias();
            var pc          = DbColumnProjector.ProjectColumns(this.Translator.Linguist.Language, projector, null, selectAlias, root.Alias);
            var proj        = new DbProjectionExpression
                              (
                new DbSelectExpression(selectAlias, pc.Columns, root, null),
                pc.Projector
                              );

            return(this.Translator.Police.ApplyPolicy(proj, entity.ElementType.GetTypeInfo()) as DbProjectionExpression);
        }
Esempio n. 15
0
 public TableExpression(TableAlias alias, MappingEntity entity, string name)
     : base(DbExpressionType.Table, typeof(void), alias)
 {
     this.Entity = entity;
     this.Name   = name;
 }
        protected override Expression VisitProjection(ProjectionExpression proj)
        {
            SelectExpression save = this.currentSelect;

            this.currentSelect = proj.Select;
            try
            {
                if (!this.isTopLevel)
                {
                    if (this.CanJoinOnClient(this.currentSelect))
                    {
                        // make a query that combines all the constraints from the outer queries into a single select
                        SelectExpression newOuterSelect = (SelectExpression)QueryDuplicator.Duplicate(save);

                        // remap any references to the outer select to the new alias;
                        SelectExpression newInnerSelect = (SelectExpression)ColumnMapper.Map(proj.Select, newOuterSelect.Alias, save.Alias);
                        // add outer-join test
                        ProjectionExpression newInnerProjection = this.language.AddOuterJoinTest(new ProjectionExpression(newInnerSelect, proj.Projector));
                        newInnerSelect = newInnerProjection.Select;
                        Expression newProjector = newInnerProjection.Projector;

                        TableAlias newAlias = new TableAlias();
                        var        pc       = ColumnProjector.ProjectColumns(this.language, newProjector, null, newAlias, newOuterSelect.Alias, newInnerSelect.Alias);

                        JoinExpression   join         = new JoinExpression(JoinType.OuterApply, newOuterSelect, newInnerSelect, null);
                        SelectExpression joinedSelect = new SelectExpression(newAlias, pc.Columns, join, null, null, null, proj.IsSingleton, null, null, false);

                        // apply client-join treatment recursively
                        this.currentSelect = joinedSelect;
                        newProjector       = this.Visit(pc.Projector);

                        // compute keys (this only works if join condition was a single column comparison)
                        List <Expression> outerKeys = new List <Expression>();
                        List <Expression> innerKeys = new List <Expression>();
                        if (this.GetEquiJoinKeyExpressions(newInnerSelect.Where, newOuterSelect.Alias, outerKeys, innerKeys))
                        {
                            // outerKey needs to refer to the outer-scope's alias
                            var outerKey = outerKeys.Select(k => ColumnMapper.Map(k, save.Alias, newOuterSelect.Alias));
                            // innerKey needs to refer to the new alias for the select with the new join
                            var innerKey = innerKeys.Select(k => ColumnMapper.Map(k, joinedSelect.Alias, ((ColumnExpression)k).Alias));
                            ProjectionExpression newProjection = new ProjectionExpression(joinedSelect, newProjector, proj.Aggregator);
                            return(new ClientJoinExpression(newProjection, outerKey, innerKey));
                        }
                    }
                    else
                    {
                        bool saveJoin = this.canJoinOnClient;
                        this.canJoinOnClient = false;
                        var result = base.VisitProjection(proj);
                        this.canJoinOnClient = saveJoin;
                        return(result);
                    }
                }
                else
                {
                    this.isTopLevel = false;
                }
                return(base.VisitProjection(proj));
            }
            finally
            {
                this.currentSelect = save;
            }
        }
Esempio n. 17
0
 protected AliasedExpression(DbExpressionType nodeType, Type type, TableAlias alias)
     : base(nodeType, type)
 {
     this.Alias = alias;
 }
Esempio n. 18
0
 public static Expression Map(Expression expression, TableAlias newAlias, IEnumerable <TableAlias> oldAliases)
 {
     return(new ColumnMapper(oldAliases, newAlias).Visit(expression));
 }
Esempio n. 19
0
 public static ProjectedColumns ProjectColumns(QueryLanguage language, ProjectionAffinity affinity, Expression expression, IEnumerable <ColumnDeclaration> existingColumns, TableAlias newAlias, params TableAlias[] existingAliases) => ProjectColumns(language, affinity, expression, existingColumns, newAlias, (IEnumerable <TableAlias>)existingAliases);
        protected override Expression VisitProjection(DbProjectionExpression proj)
        {
            var save = this.currentSelect;

            this.currentSelect = proj.Select;

            try
            {
                if (this.isTopLevel == false)
                {
                    if (this.CanJoinOnClient(this.currentSelect))
                    {
                        var newOuterSelect = DbQueryDuplicator.Duplicate(save) as DbSelectExpression;

                        var newInnerSelect     = DbColumnMapper.Map(proj.Select, newOuterSelect.Alias, save.Alias) as DbSelectExpression;
                        var newInnerProjection = this.language.AddOuterJoinTest(new DbProjectionExpression(newInnerSelect, proj.Projector));

                        if (newInnerProjection != null)
                        {
                            newInnerSelect = newInnerProjection.Select;
                        }

                        var newProjector = newInnerProjection.Projector;

                        var newAlias = new TableAlias();
                        var pc       = DbColumnProjector.ProjectColumns(this.language, newProjector, null, newAlias, newOuterSelect.Alias, newInnerSelect.Alias);

                        var join         = new DbJoinExpression(JoinType.OuterApply, newOuterSelect, newInnerSelect, null);
                        var joinedSelect = new DbSelectExpression(newAlias, pc.Columns, join, null, null, null, proj.IsSingleton, null, null, false);

                        this.currentSelect = joinedSelect;

                        if (pc != null)
                        {
                            newProjector = this.Visit(pc.Projector);
                        }

                        var outerKeys = new List <Expression>();
                        var innerKeys = new List <Expression>();

                        if (this.GetEquiJoinKeyExpressions(newInnerSelect.Where, newOuterSelect.Alias, outerKeys, innerKeys))
                        {
                            var outerKey      = outerKeys.Select(k => DbColumnMapper.Map(k, save.Alias, newOuterSelect.Alias));
                            var innerKey      = innerKeys.Select(k => DbColumnMapper.Map(k, joinedSelect.Alias, ((DbColumnExpression)k).Alias));
                            var newProjection = new DbProjectionExpression(joinedSelect, newProjector, proj.Aggregator);

                            return(new DbClientJoinExpression(newProjection, outerKey, innerKey));
                        }
                    }
                    else
                    {
                        var saveJoin = this.canJoinOnClient;


                        this.canJoinOnClient = false;

                        var result = base.VisitProjection(proj);

                        this.canJoinOnClient = saveJoin;

                        return(result);
                    }
                }
                else
                {
                    this.isTopLevel = false;
                }

                return(base.VisitProjection(proj));
            }
            finally
            {
                this.currentSelect = save;
            }
        }
Esempio n. 21
0
 private ColumnMapper(IEnumerable <TableAlias> oldAliases, TableAlias newAlias)
 {
     this.oldAliases = new HashSet <TableAlias>(oldAliases);
     this.newAlias   = newAlias;
 }
Esempio n. 22
0
        /// <summary>
        /// Rebind order expressions to reference a new alias and add to column declarations if necessary
        /// </summary>
        protected virtual BindResult RebindOrderings(IEnumerable <OrderExpression> orderings, TableAlias alias, HashSet <TableAlias> existingAliases, IEnumerable <ColumnDeclaration> existingColumns)
        {
            List <ColumnDeclaration> newColumns   = null;
            List <OrderExpression>   newOrderings = new List <OrderExpression>();

            foreach (OrderExpression ordering in orderings)
            {
                Expression       expr   = ordering.Expression;
                ColumnExpression column = expr as ColumnExpression;
                if (column == null || (existingAliases != null && existingAliases.Contains(column.Alias)))
                {
                    // check to see if a declared column already contains a similar expression
                    int iOrdinal = 0;
                    foreach (ColumnDeclaration decl in existingColumns)
                    {
                        ColumnExpression declColumn = decl.Expression as ColumnExpression;
                        if (decl.Expression == ordering.Expression ||
                            (column != null && declColumn != null && column.Alias == declColumn.Alias && column.Name == declColumn.Name))
                        {
                            // found it, so make a reference to this column
                            expr = new ColumnExpression(column.Type, column.QueryType, alias, decl.Name);
                            break;
                        }
                        iOrdinal++;
                    }
                    // if not already projected, add a new column declaration for it
                    if (expr == ordering.Expression)
                    {
                        if (newColumns == null)
                        {
                            newColumns      = new List <ColumnDeclaration>(existingColumns);
                            existingColumns = newColumns;
                        }
                        string colName = column != null ? column.Name : "c" + iOrdinal;
                        colName = newColumns.GetAvailableColumnName(colName);
                        var colType = this.language.TypeSystem.GetColumnType(expr.Type);
                        newColumns.Add(new ColumnDeclaration(colName, ordering.Expression, colType));
                        expr = new ColumnExpression(expr.Type, colType, alias, colName);
                    }
                    newOrderings.Add(new OrderExpression(ordering.OrderType, expr));
                }
            }
            return(new BindResult(existingColumns, newOrderings));
        }
 private void ClearColumnsUsed(TableAlias alias)
 {
     this.allColumnsUsed[alias] = new HashSet <string>();
 }
        protected virtual Expression GetInsertResult(MappingEntity entity, Expression instance, LambdaExpression selector, Dictionary <MemberInfo, Expression> map)
        {
            var tableAlias = new TableAlias();
            var tex        = new TableExpression(tableAlias, entity, this.mapping.GetTableName(entity));
            var aggregator = Aggregator.GetAggregator(selector.Body.Type, typeof(IEnumerable <>).MakeGenericType(selector.Body.Type));

            Expression where;
            DeclarationCommand genIdCommand = null;
            var generatedIds = this.mapping.GetMappedMembers(entity).Where(m => this.mapping.IsPrimaryKey(entity, m) && this.mapping.IsGenerated(entity, m)).ToList();

            if (generatedIds.Count > 0)
            {
                if (map == null || !generatedIds.Any(m => map.ContainsKey(m)))
                {
                    var localMap = new Dictionary <MemberInfo, Expression>();
                    genIdCommand = this.GetGeneratedIdCommand(entity, generatedIds.ToList(), localMap);
                    map          = localMap;
                }

                // is this just a retrieval of one generated id member?
                var mex = selector.Body as MemberExpression;
                if (mex != null && this.mapping.IsPrimaryKey(entity, mex.Member) && this.mapping.IsGenerated(entity, mex.Member))
                {
                    if (genIdCommand != null)
                    {
                        // just use the select from the genIdCommand
                        return(new ProjectionExpression(
                                   genIdCommand.Source,
                                   new ColumnExpression(mex.Type, genIdCommand.Variables[0].QueryType, genIdCommand.Source.Alias, genIdCommand.Source.Columns[0].Name),
                                   aggregator
                                   ));
                    }
                    else
                    {
                        TableAlias alias   = new TableAlias();
                        var        colType = this.GetColumnType(entity, mex.Member);
                        return(new ProjectionExpression(
                                   new SelectExpression(alias, new[] { new ColumnDeclaration("", map[mex.Member], colType) }, null, null),
                                   new ColumnExpression(TypeHelper.GetMemberType(mex.Member), colType, alias, ""),
                                   aggregator
                                   ));
                    }
                }

                where = generatedIds.Select((m, i) =>
                                            this.GetMemberExpression(tex, entity, m).Equal(map[m])
                                            ).Aggregate((x, y) => x.And(y));
            }
            else
            {
                where = this.GetIdentityCheck(tex, entity, instance);
            }

            Expression typeProjector = this.GetEntityExpression(tex, entity);
            Expression selection     = DbExpressionReplacer.Replace(selector.Body, selector.Parameters[0], typeProjector);
            TableAlias newAlias      = new TableAlias();
            var        pc            = ColumnProjector.ProjectColumns(this.translator.Linguist.Language, selection, null, newAlias, tableAlias);
            var        pe            = new ProjectionExpression(
                new SelectExpression(newAlias, pc.Columns, tex, where),
                pc.Projector,
                aggregator
                );

            if (genIdCommand != null)
            {
                return(new BlockCommand(genIdCommand, pe));
            }
            return(pe);
        }
Esempio n. 25
0
 public static ProjectedColumns ProjectColumns(QueryLanguage language, Expression expression, IEnumerable <ColumnDeclaration> existingColumns, TableAlias newAlias, IEnumerable <TableAlias> existingAliases)
 {
     return(ProjectColumns(language, ProjectionAffinity.Client, expression, existingColumns, newAlias, existingAliases));
 }
Esempio n. 26
0
 public static Expression Map(Expression expression, TableAlias newAlias, params TableAlias[] oldAliases)
 {
     return(Map(expression, newAlias, (IEnumerable <TableAlias>)oldAliases));
 }
Esempio n. 27
0
 public static ProjectedColumns ProjectColumns(QueryLanguage language, Expression expression, IEnumerable <ColumnDeclaration> existingColumns, TableAlias newAlias, params TableAlias[] existingAliases)
 {
     return(ProjectColumns(language, expression, existingColumns, newAlias, (IEnumerable <TableAlias>)existingAliases));
 }
        public static SelectExpression AddRedundantSelect(this SelectExpression sel, QueryLanguage language, TableAlias newAlias)
        {
            var newColumns =
                from d in sel.Columns
                let qt = (d.Expression is ColumnExpression) ? ((ColumnExpression)d.Expression).QueryType : language.TypeSystem.GetColumnType(d.Expression.Type)
                         select new ColumnDeclaration(d.Name, new ColumnExpression(d.Expression.Type, qt, newAlias, d.Name), qt);

            var newFrom = new SelectExpression(newAlias, sel.Columns, sel.From, sel.Where, sel.OrderBy, sel.GroupBy, sel.IsDistinct, sel.Skip, sel.Take, sel.IsReverse);

            return(new SelectExpression(sel.Alias, newColumns, newFrom, null, null, null, false, null, null, false));
        }
Esempio n. 29
0
        public static ProjectedColumns ProjectColumns(QueryLanguage language, ProjectionAffinity affinity, Expression expression, IEnumerable <ColumnDeclaration> existingColumns, TableAlias newAlias, IEnumerable <TableAlias> existingAliases)
        {
            ColumnProjector projector = new ColumnProjector(language, affinity, expression, existingColumns, newAlias, existingAliases);
            Expression      expr      = projector.Visit(expression);

            return(new ProjectedColumns(expr, projector.columns.AsReadOnly()));
        }
Esempio n. 30
0
 public DbColumnExpression(Type type, QueryType queryType, TableAlias alias, string name) : base(DbExpressionType.Column, type)
 {
     this.Alias     = alias;
     this.QueryType = queryType ?? throw new ArgumentNullException("queryType");
     this.Name      = name ?? throw new ArgumentNullException("name");
 }