Inheritance: SqlBaseExpression
Ejemplo n.º 1
0
        protected override Expression VisitSelect(SqlSelectExpression select)
        {
            // Only consider aggregates in these locations

            if (this.hasAggregate)
            {
                return select;
            }

            this.Visit(select.Where);

            if (this.hasAggregate)
            {
                return select;
            }

            this.VisitExpressionList(select.OrderBy);

            if (this.hasAggregate)
            {
                return select;
            }

            this.VisitColumnDeclarations(select.Columns);

            return select;
        }
Ejemplo n.º 2
0
        protected override Expression VisitSelect(SqlSelectExpression selectExpression)
        {
            if (selectExpression.Skip != null)
            {
                var rowNumber = new SqlFunctionCallExpression(typeof(int), "ROW_NUMBER");
                var over = new SqlOverExpression(rowNumber, selectExpression.OrderBy ?? new ReadOnlyList<Expression>(new [] { new SqlOrderByExpression(OrderType.Ascending, selectExpression.Columns[0].Expression) }));
                var additionalColumn = new SqlColumnDeclaration(RowColumnName, over);

                var newAlias = selectExpression.Alias + "INNER";
                var innerColumns = new ReadOnlyList<SqlColumnDeclaration>(selectExpression.Columns.Select(c => c).Concat(new[] { additionalColumn }));

                var innerSelect = new SqlSelectExpression(selectExpression.Type, newAlias, innerColumns, selectExpression.From, selectExpression.Where, null, selectExpression.GroupBy, selectExpression.Distinct, null, null, selectExpression.ForUpdate);

                var outerColumns = selectExpression.Columns.Select(c => new SqlColumnDeclaration(c.Name, new SqlColumnExpression(c.Expression.Type, newAlias, c.Name)));

                Expression rowPredicate = Expression.GreaterThan(new SqlColumnExpression(typeof(int), newAlias, additionalColumn.Name), selectExpression.Skip);

                if (selectExpression.Take != null && !(selectExpression.Take is SqlTakeAllValueExpression))
                {
                    rowPredicate = Expression.And
                    (
                        rowPredicate,
                        Expression.LessThanOrEqual(new SqlColumnExpression(typeof(int), newAlias, additionalColumn.Name), Expression.Add(selectExpression.Skip, selectExpression.Take))
                    );
                }

                return new SqlSelectExpression(selectExpression.Type, selectExpression.Alias, outerColumns, innerSelect, rowPredicate, null, selectExpression.ForUpdate);
            }

            return base.VisitSelect(selectExpression);
        }
Ejemplo n.º 3
0
		internal static bool IsNameMapProjection(SqlSelectExpression select)
		{
			if (select.From is SqlTableExpression)
			{
				return false;
			}

			var fromSelect = select.From as SqlSelectExpression;

			if (fromSelect == null || select.Columns.Count > fromSelect.Columns.Count)
			{
				return false;
			}

			var fromColumnNames = new HashSet<string>(fromSelect.Columns.Select(x => x.Name));

			foreach (var t in @select.Columns)
			{
				var columnExpression = t.Expression as SqlColumnExpression;

				if (columnExpression == null || !fromColumnNames.Contains(columnExpression.Name))
				{
					return false;
				}
			}

			return true;
		}
Ejemplo n.º 4
0
        protected override void AppendLimit(SqlSelectExpression selectExpression)
        {
            if (selectExpression.Skip != null || selectExpression.Take != null)
            {
                if (selectExpression.Take != null)
                {
                    this.Write(" LIMIT ");

                    Visit(selectExpression.Take);

                    this.Write(" ");
                }
                else
                {
                    this.Write(" LIMIT -1 ");
                }

                if (selectExpression.Skip != null)
                {
                    this.Write("OFFSET ");

                    Visit(selectExpression.Skip);
                }
            }
        }
        protected override Expression VisitSelect(SqlSelectExpression selectExpression)
        {
            var from = selectExpression.From;
            var where = Visit(selectExpression.Where);

            var orderBy = selectExpression.OrderBy;
            var groupBy = selectExpression.GroupBy;
            var skip = selectExpression.Skip;
            var take = selectExpression.Take;
            var columns = selectExpression.Columns;

            if (where != null)
            {
                if (where.NodeType == ExpressionType.Constant && where.Type == typeof(bool))
                {
                    var value = (bool)((ConstantExpression)where).Value;

                    if (value)
                    {
                        where = null;
                    }
                }
            }

            if (where != selectExpression.Where)
            {
                return new SqlSelectExpression(selectExpression.Type, selectExpression.Alias, columns, from, where, orderBy, groupBy, selectExpression.Distinct, skip, take, selectExpression.ForUpdate);
            }

            return base.VisitSelect(selectExpression);
        }
Ejemplo n.º 6
0
 protected override void AppendLimit(SqlSelectExpression selectExpression)
 {
     if (selectExpression.Skip != null && selectExpression.Take != null)
     {
         throw new InvalidOperationException("Skip/Take not supported");
     }
 }
Ejemplo n.º 7
0
        internal static bool HasAggregates(SqlSelectExpression expression, bool ignoreInSubqueries)
        {
            var checker = new HasAggregateChecker(ignoreInSubqueries);

            checker.Visit(expression);

            return checker.hasAggregate;
        }
 protected override Expression VisitSelect(SqlSelectExpression expression)
 {
     this.hashCode ^= expression.Distinct ? 309065085 : 0;
     this.hashCode ^= expression.ForUpdate ? -1548991485 : 0;
     this.hashCode ^= expression.Reverse ? 1018104131 : 0;
     this.hashCode ^= expression.Alias?.GetHashCode() ?? 0;
     return base.VisitSelect(expression);
 }
Ejemplo n.º 9
0
 protected override Expression VisitSelect(SqlSelectExpression expression)
 {
     this.hashCode ^= expression.Distinct ? 309065085 : 0;
     this.hashCode ^= expression.ForUpdate ? -1548991485 : 0;
     this.hashCode ^= expression.Reverse ? 1018104131 : 0;
     this.hashCode ^= expression.Alias?.GetHashCode() ?? 0;
     return(base.VisitSelect(expression));
 }
		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);
		}
Ejemplo n.º 11
0
 public SqlProjectionExpression(Type type, SqlSelectExpression select, Expression projector, LambdaExpression aggregator, bool isElementTableProjection, Expression defaultValue = null)
     : base(type)
 {
     this.Select     = select;
     this.Projector  = projector;
     this.Aggregator = aggregator;
     this.IsElementTableProjection = isElementTableProjection;
     this.DefaultValue             = defaultValue;
 }
		protected override Expression VisitSelect(SqlSelectExpression selectExpression)
		{
			if (selectExpression.OrderBy != null)
			{
				return selectExpression.ChangeOrderBy(null);
			}

			return base.VisitSelect(selectExpression);
		}
Ejemplo n.º 13
0
		public SqlProjectionExpression(Type type, SqlSelectExpression select, Expression projector, LambdaExpression aggregator, bool isElementTableProjection, Expression defaultValue = null)
			: base(type)
		{
			this.Select = select;
			this.Projector = projector;
			this.Aggregator = aggregator;
			this.IsElementTableProjection = isElementTableProjection;
			this.DefaultValue = defaultValue;
		}
Ejemplo n.º 14
0
        protected static SqlProjectionExpression UpdateProjection(SqlProjectionExpression projectionExpression, SqlSelectExpression select, Expression projector, LambdaExpression aggregator)
        {
            if (select != projectionExpression.Select || projector != projectionExpression.Projector || aggregator != projectionExpression.Aggregator)
            {
                return new SqlProjectionExpression(select, projector, aggregator, projectionExpression.IsElementTableProjection, projectionExpression.SelectFirstType, projectionExpression.DefaultValueExpression, projectionExpression.IsDefaultIfEmpty);
            }

            return projectionExpression;
        }
Ejemplo n.º 15
0
 protected override void AppendTop(SqlSelectExpression selectExpression)
 {
     if (selectExpression.Take != null && selectExpression.Skip == null)
     {
         this.Write("TOP(");
         this.Visit(selectExpression.Take);
         this.Write(") ");
     }
 }
Ejemplo n.º 16
0
		protected override Expression VisitSelect(SqlSelectExpression selectExpression)
		{
			selectNesting++;

			var retval = base.VisitSelect(selectExpression);

			selectNesting--;

			return retval;
		}
Ejemplo n.º 17
0
        protected override Expression VisitSelect(SqlSelectExpression selectExpression)
        {
            if (selectExpression.Columns.Count == 1
                && selectExpression.From.NodeType == (ExpressionType)SqlExpressionType.Select
                && selectExpression.Columns[0].Expression.NodeType == (ExpressionType)SqlExpressionType.Aggregate)
            {
                var from = (SqlSelectExpression)selectExpression.From;
                var aggregateExpression = (SqlAggregateExpression)selectExpression.Columns[0].Expression;

                if (from.Columns.Count > 1
                    || aggregateExpression.IsDistinct
                    || from.Distinct
                    || from.Take != null
                    || from.Skip != null
                    || from.GroupBy != null
                    /* Don't fold a from with an orderby into the outer select if it has a count or other aggregate */
                    || from.OrderBy != null && from.OrderBy.Count > 0 && SqlAggregateChecker.HasAggregates(selectExpression))
                {
                    return base.VisitSelect(selectExpression);
                }

                var newColumns = new List<SqlColumnDeclaration>();

                if (from.Columns.Count == 1)
                {
                    foreach (var column in from.Columns)
                    {
                        if (column.Expression.NodeType != (ExpressionType)SqlExpressionType.Column)
                        {
                            return base.VisitSelect(selectExpression);
                        }

                        var newAggregate = new SqlAggregateExpression
                        (
                            aggregateExpression.Type,
                            aggregateExpression.AggregateType,
                            column.Expression,
                            aggregateExpression.IsDistinct
                        );

                        newColumns.Add(new SqlColumnDeclaration(column.Name, newAggregate));
                    }
                }
                else
                {
                    newColumns.Add(selectExpression.Columns[0]);
                }

                var where = this.Visit(from.Where);

                return from.ChangeWhereAndColumns(where, newColumns.ToReadOnlyList(), from.ForUpdate || selectExpression.ForUpdate);
            }

            return base.VisitSelect(selectExpression);
        }
Ejemplo n.º 18
0
 public SqlProjectionExpression(SqlSelectExpression select, Expression projector, LambdaExpression aggregator, bool isElementTableProjection, SelectFirstType selectFirstType, Expression defaultValueExpression, bool isDefaultIfEmpty)
     : base(selectFirstType == SelectFirstType.None ? select.Type : select.Type.GetGenericArguments()[0])
 {
     this.Select = select;
     this.Projector = projector;
     this.Aggregator = aggregator;
     this.SelectFirstType = selectFirstType;
     this.DefaultValueExpression = defaultValueExpression;
     this.IsElementTableProjection = isElementTableProjection;
     this.IsDefaultIfEmpty = isDefaultIfEmpty;
 }
Ejemplo n.º 19
0
 protected override Expression VisitSelect(SqlSelectExpression select)
 {
     if (this.selectsToRemove.Contains(select))
     {
         return this.Visit(select.From);
     }
     else
     {
         return base.VisitSelect(select);
     }
 }
Ejemplo n.º 20
0
		private static bool IsRedudantSubquery(SqlSelectExpression select)
		{
			return (IsSimpleProjection(select) || IsNameMapProjection(select))
				&& !select.Distinct
				&& (select.Take == null)
				&& (select.Skip == null)
				&& select.Where == null
				&& !select.Columns.Any(c => c.NoOptimise)
				&& ((select.OrderBy?.Count ?? 0) == 0)
				&& ((select.GroupBy?.Count ?? 0) == 0);
		}
Ejemplo n.º 21
0
 public SqlProjectionExpression(SqlSelectExpression select, Expression projector, LambdaExpression aggregator, bool isElementTableProjection, SelectFirstType selectFirstType, Expression defaultValueExpression, bool isDefaultIfEmpty)
     : base(selectFirstType == SelectFirstType.None ? select.Type : select.Type.GetGenericArguments()[0])
 {
     this.Select                   = select;
     this.Projector                = projector;
     this.Aggregator               = aggregator;
     this.SelectFirstType          = selectFirstType;
     this.DefaultValueExpression   = defaultValueExpression;
     this.IsElementTableProjection = isElementTableProjection;
     this.IsDefaultIfEmpty         = isDefaultIfEmpty;
 }
Ejemplo n.º 22
0
		protected override Expression VisitSelect(SqlSelectExpression selectExpression)
		{
			if (selectExpression.GroupBy != null && selectExpression.GroupBy.Count == 1
				&& selectExpression.GroupBy[0].NodeType == ExpressionType.New)
			{
				var groupBy = ((NewExpression)selectExpression.GroupBy[0]).Arguments;

				return new SqlSelectExpression(selectExpression.Type, selectExpression.Alias, selectExpression.Columns.ToReadOnlyCollection(), selectExpression.From, selectExpression.Where, selectExpression.OrderBy.ToReadOnlyCollection(), groupBy.ToReadOnlyCollection(), selectExpression.Distinct, selectExpression.Skip, selectExpression.Take, selectExpression.ForUpdate);	
			}

			return base.VisitSelect(selectExpression);
		}
Ejemplo n.º 23
0
        protected override Expression VisitSelect(SqlSelectExpression select)
        {
            var columnRemoved = false;

            select = (SqlSelectExpression)base.VisitSelect(select);

            var columnsOrderedByName = select.Columns.OrderBy(c => c.Name).ToList();

            var removedColumns = new BitArray(select.Columns.Count);

            for (int i = 0, n = columnsOrderedByName.Count; i < n - 1; i++)
            {
                var icolumn = columnsOrderedByName[i];
                var iNewColumnExpression = new SqlColumnExpression(icolumn.Expression.Type, select.Alias, icolumn.Name);

                for (var j = i + 1; j < n; j++)
                {
                    if (!removedColumns.Get(j))
                    {
                        var jcolumn = columnsOrderedByName[j];

                        if (IsSameExpression(icolumn.Expression, jcolumn.Expression))
                        {
                            // 'j' references should now be a reference to 'i'

                            var jNewColumnExpression = new SqlColumnExpression(jcolumn.Expression.Type, select.Alias, jcolumn.Name);
                            this.visitedColumns.Add(jNewColumnExpression, iNewColumnExpression);

                            removedColumns.Set(j, true);
                            columnRemoved = true;
                        }
                    }
                }
            }

            if (columnRemoved)
            {
                var newColumnDeclarations = new List<SqlColumnDeclaration>();

                for (int i = 0, n = columnsOrderedByName.Count; i < n; i++)
                {
                    if (!removedColumns.Get(i))
                    {
                        newColumnDeclarations.Add(columnsOrderedByName[i]);
                    }
                }

                select = select.ChangeColumns(newColumnDeclarations);
            }

            return select;
        }
			protected override Expression VisitSelect(SqlSelectExpression select)
			{
				var savedIsTopLevel = this.isTopLevel;

				this.isTopLevel = false;
				
				select = (SqlSelectExpression)base.VisitSelect(select);

				// Attempt to merge subqueries that would have been removed by the above
				// logic except for the existence of a where clause

				while (CanMergeWithFrom(select))
				{
					var fromSelect = select.From.GetLeftMostSelect();

					CanMergeWithFrom(select);

					// remove the redundant subquery
					select = SubqueryRemover.Remove(select, fromSelect);

					// merge where expressions 
					var where = select.Where;

					if (fromSelect.Where != null)
					{
						if (where != null)
						{
							where = Expression.And(fromSelect.Where, where);
						}
						else
						{
							where = fromSelect.Where;
						}
					}
					
					var orderBy = select.OrderBy != null && select.OrderBy.Count > 0 ? select.OrderBy : fromSelect.OrderBy;
					var groupBy = select.GroupBy != null && select.GroupBy.Count > 0 ? select.GroupBy : fromSelect.GroupBy;
					var skip = select.Skip ?? fromSelect.Skip;
					var take = select.Take ?? fromSelect.Take;
					var isDistinct = select.Distinct || fromSelect.Distinct;

					if (where != select.Where || orderBy != select.OrderBy || groupBy != select.GroupBy || isDistinct != select.Distinct || skip != select.Skip || take != select.Take)
					{
						select = new SqlSelectExpression(select.Type, select.Alias, select.Columns, select.From, where, orderBy, groupBy, isDistinct, skip, take, select.ForUpdate);
					}
				}

				this.isTopLevel = savedIsTopLevel;

				return select;
			}
Ejemplo n.º 25
0
		internal static bool IsSimpleProjection(SqlSelectExpression select)
		{
			foreach (var decl in select.Columns)
			{
				var col = decl.Expression as SqlColumnExpression;

				if (col == null || decl.Name != col.Name)
				{
					return false;
				}
			}

			return true;
		}
Ejemplo n.º 26
0
        protected override Expression VisitSelect(SqlSelectExpression select)
        {
            select = (SqlSelectExpression)base.VisitSelect(select);

            // Expand all purely redundant subqueries

            var redundantQueries = RedundantSubqueryFinder.Find(select.From);

            if (redundantQueries != null)
            {
                select = SubqueryRemover.Remove(select, redundantQueries);
            }

            return select;
        }
Ejemplo n.º 27
0
		protected override Expression VisitSelect(SqlSelectExpression select)
		{
			var canHaveOrderBy = select.Take != null || select.Skip != null;
			var hasGroupBy = select.GroupBy?.Count > 0;
			var canReceiveOrderings = canHaveOrderBy && !hasGroupBy && !select.Distinct && !SqlAggregateChecker.HasAggregates(select);

			this.outerCanReceiveOrderings &= canReceiveOrderings;

			select = (SqlSelectExpression)base.VisitSelect(select);

			var hasOrderBy = select.OrderBy?.Count > 0;
				
			if (hasOrderBy)
			{
				this.PrependOrderings(select.OrderBy);
			}
				
			var columns = select.Columns;
			var orderings = canReceiveOrderings ? this.gatheredOrderings : select.OrderBy;
			var canPassOnOrderings = this.outerCanReceiveOrderings && !hasGroupBy && !select.Distinct;

			if (this.gatheredOrderings != null)
			{
				if (canPassOnOrderings)
				{
					var producedAliases = SqlAliasesProduced.Gather(select.From);
					var project = this.RebindOrderings(this.gatheredOrderings, select.Alias, producedAliases, select.Columns);

					this.gatheredOrderings = null;
					this.PrependOrderings(project.Orderings);

					columns = project.Columns;
				}
				else
				{
					this.gatheredOrderings = null;
				}
			}

			if (orderings != select.OrderBy || columns != select.Columns)
			{
				select = new SqlSelectExpression(select.Type, select.Alias, columns, select.From, select.Where, orderings, select.GroupBy, select.Distinct, select.Skip, select.Take, select.ForUpdate);
			}

			return select;
		}
Ejemplo n.º 28
0
		protected override Expression VisitSelect(SqlSelectExpression selectExpression)
		{
			if (selectExpression.Skip != null)
			{
				var rowNumber = new SqlFunctionCallExpression(typeof(int), "ROW_NUMBER");

				var oldAliases = (selectExpression.From as ISqlExposesAliases)?.Aliases;
				var innerSelectWithRowAlias = selectExpression.Alias + "_ROW";

				var cols = selectExpression.Columns.Select(c => new SqlColumnDeclaration(c.Name, new SqlColumnExpression(c.Expression.Type, selectExpression.Alias, c.Name))).ToList();
				var over = new SqlOverExpression(rowNumber, selectExpression.OrderBy?.ToReadOnlyCollection() ?? cols.Select(c => new SqlOrderByExpression(OrderType.Ascending, c.Expression)).ToReadOnlyCollection());

				if (oldAliases != null)
				{
					over = (SqlOverExpression)AliasReferenceReplacer.Replace(over, oldAliases.Contains, selectExpression.Alias);
				}

				var rowColumn = new SqlColumnDeclaration(RowColumnName, over);

				cols.Add(rowColumn);

				var innerSelectWithRowColumns = cols.ToReadOnlyCollection();
				var innerSelectWithRow = new SqlSelectExpression(selectExpression.Type, innerSelectWithRowAlias, innerSelectWithRowColumns, this.Visit(selectExpression.ChangeOrderBy(null).ChangeSkipTake(null, null)), null, null, null, false, null, null, false);
				var outerColumns = selectExpression.Columns.Select(c => new SqlColumnDeclaration(c.Name, new SqlColumnExpression(c.Expression.Type, innerSelectWithRowAlias, c.Name)));

				Expression rowPredicate = Expression.GreaterThan(new SqlColumnExpression(typeof(int), innerSelectWithRowAlias, rowColumn.Name), selectExpression.Skip);

				if (selectExpression.Take != null && !(selectExpression.Take is SqlTakeAllValueExpression))
				{
					rowPredicate = Expression.And
					(
						rowPredicate,
						Expression.LessThanOrEqual(new SqlColumnExpression(typeof(int), innerSelectWithRowAlias, rowColumn.Name), Expression.Add(selectExpression.Skip, selectExpression.Take))
					);
				}

				var retval = new SqlSelectExpression(selectExpression.Type, selectExpression.Alias, outerColumns.ToReadOnlyCollection(), innerSelectWithRow, rowPredicate, null, null, selectExpression.Distinct, null, null, selectExpression.ForUpdate, selectExpression.Reverse, selectExpression.Into);

				return retval;
			}

			return base.VisitSelect(selectExpression);
		}
Ejemplo n.º 29
0
        protected virtual Expression VisitSelect(SqlSelectExpression selectExpression)
        {
            var from = VisitSource(selectExpression.From);

            var where = Visit(selectExpression.Where);

            var orderBy = this.VisitExpressionList(selectExpression.OrderBy);
            var groupBy = this.VisitExpressionList(selectExpression.GroupBy);
            var skip    = this.Visit(selectExpression.Skip);
            var take    = this.Visit(selectExpression.Take);
            var columns = VisitColumnDeclarations(selectExpression.Columns);

            if (from != selectExpression.From || where != selectExpression.Where || columns != selectExpression.Columns || orderBy != selectExpression.OrderBy || groupBy != selectExpression.GroupBy || take != selectExpression.Take || skip != selectExpression.Skip)
            {
                return(new SqlSelectExpression(selectExpression.Type, selectExpression.Alias, columns, from, where, orderBy, groupBy, selectExpression.Distinct, skip, take, selectExpression.ForUpdate));
            }

            return(selectExpression);
        }
		protected override Expression VisitSelect(SqlSelectExpression selectExpression)
		{
			var saveIsOuterMostSelect = this.isOuterMostSelect;

			try
			{
				this.isOuterMostSelect = false;

				if (!saveIsOuterMostSelect && selectExpression.OrderBy != null && selectExpression.Take == null)
				{
					return selectExpression.ChangeSkipTake(selectExpression.Skip, new SqlTakeAllValueExpression());
				}

				return base.VisitSelect(selectExpression);
			}
			finally
			{
				this.isOuterMostSelect = saveIsOuterMostSelect;
			}
		}
Ejemplo n.º 31
0
		protected override Expression VisitSelect(SqlSelectExpression select)
		{
			var savedWhere = this.currentWhere;

			try
			{
				this.currentWhere = select.Where;

				var result = (SqlSelectExpression)base.VisitSelect(select);

				if (this.currentWhere != result.Where)
				{
					return result.ChangeWhere(this.currentWhere);
				}

				return result;
			}
			finally
			{
				this.currentWhere = savedWhere;
			}
		}
		protected override Expression VisitSelect(SqlSelectExpression select)
		{
			select = (SqlSelectExpression)base.VisitSelect(select);

			if (this.aggregateSubqueriesBySelectAlias.Contains(select.Alias))
			{
				var columnsIncludingAggregates = new List<SqlColumnDeclaration>(select.Columns);

				foreach (var aggregateSubqueryExpression in this.aggregateSubqueriesBySelectAlias[select.Alias])
				{
					var name = "__AGGR" + columnsIncludingAggregates.Count;

					var columnDeclaration = new SqlColumnDeclaration(name, aggregateSubqueryExpression.AggregateInGroupSelect);

					this.aggregateSubqueryInstances.Add(aggregateSubqueryExpression, new SqlColumnExpression(aggregateSubqueryExpression.Type, aggregateSubqueryExpression.GroupByAlias, name));

					columnsIncludingAggregates.Add(columnDeclaration);
				}

				return new SqlSelectExpression(select.Type, select.Alias, columnsIncludingAggregates.ToReadOnlyCollection(), select.From, select.Where, select.OrderBy, select.GroupBy, select.Distinct, select.Skip, select.Take, select.ForUpdate);
			}

			return select;
		}
Ejemplo n.º 33
0
        protected static SqlProjectionExpression UpdateProjection(SqlProjectionExpression projectionExpression, SqlSelectExpression select, Expression projector, LambdaExpression aggregator)
        {
            if (select != projectionExpression.Select || projector != projectionExpression.Projector || aggregator != projectionExpression.Aggregator)
            {
                return(new SqlProjectionExpression(select, projector, aggregator, projectionExpression.IsElementTableProjection, projectionExpression.SelectFirstType, projectionExpression.DefaultValueExpression, projectionExpression.IsDefaultIfEmpty));
            }

            return(projectionExpression);
        }
Ejemplo n.º 34
0
			protected override Expression VisitSelect(SqlSelectExpression select)
			{
				this.aliases.Add(select.Alias);

				return select;
			}
		protected override Expression VisitSelect(SqlSelectExpression selectExpression)
		{
			if (this.currentProjection == null || this.currentProjection.Select != selectExpression)
			{
				return base.VisitSelect(selectExpression);
			}

			var objectType = selectExpression.Type.GetSequenceElementType();

			if (!objectType.IsDataAccessObjectType())
			{
				return base.VisitSelect(selectExpression);
			}

			var aliasesAndTypes = SqlAliasTypeCollector.Collect(selectExpression)
				.ToDictionary(c => c.Item1, c => typeDescriptorProvider.GetTypeDescriptor(c.Item2.GetSequenceElementType() ?? c.Item2));

			List<SqlOrderByExpression> orderBys = null;
			var includeJoins = selectExpression.From.GetIncludeJoins().ToList();
			List<SqlColumnExpression> leftMostColumns = null;

			foreach (var includeJoin in includeJoins)
			{
				var equalsExpression = (BinaryExpression)SqlExpressionFinder.FindFirst(includeJoin, c => c.NodeType == ExpressionType.Equal);

				var left = (SqlColumnExpression)equalsExpression.Left;
				var right = (SqlColumnExpression)equalsExpression.Right;

				var leftType  = aliasesAndTypes[left.SelectAlias];
				var rightType = aliasesAndTypes[right.SelectAlias];

				if (leftMostColumns == null)
				{
					var typeDescriptor = this.typeDescriptorProvider.GetTypeDescriptor(objectType);
					var primaryKeyColumns = new HashSet<string>(QueryBinder.GetPrimaryKeyColumnInfos(this.typeDescriptorProvider, typeDescriptor).Select(c => c.ColumnName));
					
					leftMostColumns = primaryKeyColumns
						.Select(c => new SqlColumnExpression(objectType, left.SelectAlias, c))
						.ToList();
				}

				var rightProperty = rightType.GetPropertyDescriptorByColumnName(right.Name);
				var leftProperty = rightProperty.RelationshipInfo?.TargetProperty ?? leftType.GetPropertyDescriptorByColumnName(left.Name);

				if (leftProperty.PropertyType.GetGenericTypeDefinitionOrNull() == typeof(RelatedDataAccessObjects<>))
				{
					var rightColumns = SqlExpressionFinder.FindAll(includeJoin, c => c.NodeType == (ExpressionType)SqlExpressionType.Column && ((SqlColumnExpression)c).SelectAlias == right.SelectAlias);
					var leftColumns = SqlExpressionFinder.FindAll(includeJoin, c => c.NodeType == (ExpressionType)SqlExpressionType.Column && ((SqlColumnExpression)c).SelectAlias == left.SelectAlias);

					if (orderBys == null)
					{
						orderBys = new List<SqlOrderByExpression>();

						if (selectExpression.OrderBy?.Count > 0)
						{
							orderBys.AddRange(selectExpression.OrderBy);
							orderBys.AddRange(leftMostColumns.Select(c => new SqlOrderByExpression(OrderType.Ascending, c)));
						}
					}

					orderBys.AddRange(rightColumns.Select(c => new SqlOrderByExpression(OrderType.Ascending, c)));
					orderBys.AddRange(leftColumns.Select(c => new SqlOrderByExpression(OrderType.Ascending, c)));
				}
			}

			return selectExpression.ChangeOrderBy(orderBys?.Distinct(SqlExpressionEqualityComparer<SqlOrderByExpression>.Default) ?? selectExpression.OrderBy);
		}
Ejemplo n.º 36
0
 public SqlProjectionExpression(SqlSelectExpression select, Expression projector, LambdaExpression aggregator, bool isElementTableProjection)
     : this(select, projector, aggregator, isElementTableProjection, SelectFirstType.None, null, false)
 {
 }
Ejemplo n.º 37
0
 public SqlScalarExpression(Type type, SqlSelectExpression select)
     : base(type, select)
 {
 }
Ejemplo n.º 38
0
 public SqlProjectionExpression ChangeSelect(SqlSelectExpression select)
 {
     return(new SqlProjectionExpression(this.Type, select, this.Projector, this.Aggregator, this.IsElementTableProjection, this.DefaultValue));
 }
Ejemplo n.º 39
0
 public SqlProjectionExpression(SqlSelectExpression select, Expression projector, LambdaExpression aggregator)
     : this(select, projector, aggregator, false)
 {
 }
Ejemplo n.º 40
0
 public SqlProjectionExpression(SqlSelectExpression select, Expression projector, LambdaExpression aggregator, bool isElementTableProjection, Expression defaultValue = null)
     : this(select.Type, select, projector, aggregator, isElementTableProjection, defaultValue)
 {
 }
Ejemplo n.º 41
0
 public virtual SqlScalarExpression ChangeSelect(SqlSelectExpression select)
 {
     return(new SqlScalarExpression(this.Type, select));
 }
Ejemplo n.º 42
0
 public SqlProjectionExpression(SqlSelectExpression select, Expression projector, LambdaExpression aggregator, Expression defaultValue = null)
     : this(select.Type, select, projector, aggregator, false, defaultValue)
 {
 }
Ejemplo n.º 43
0
 public SqlProjectionExpression(SqlSelectExpression select, Expression projector)
     : this(select, projector, null)
 {
 }
Ejemplo n.º 44
0
 protected override Expression VisitSelect(SqlSelectExpression selectExpression)
 {
     return(base.VisitSelect(selectExpression));
 }
Ejemplo n.º 45
0
 public SqlSubqueryExpression(Type type, SqlSelectExpression select)
     : base(type)
 {
     this.Select = select;
 }
Ejemplo n.º 46
0
        protected override Expression VisitSelect(SqlSelectExpression selectExpression)
        {
            SqlSelectExpression current;

            if (!TryGetCurrent(selectExpression, out current))
            {
                return(selectExpression);
            }

            result = result && (current.Alias == selectExpression.Alias &&
                                current.Distinct == selectExpression.Distinct &&
                                current.ForUpdate == selectExpression.ForUpdate);

            if (result)
            {
                currentObject = current.Skip;

                this.Visit(current.Skip);
            }

            if (result)
            {
                currentObject = current.Take;

                this.Visit(current.Take);
            }

            if (!result)
            {
                return(selectExpression);
            }

            if (result)
            {
                currentObject = current.Columns;
                VisitColumnDeclarations(selectExpression.Columns);
                currentObject = current;
            }

            if (result)
            {
                currentObject = current.Where;
                Visit(selectExpression.Where);
                currentObject = current;
            }

            if (result)
            {
                currentObject = current.GroupBy;
                VisitExpressionList(selectExpression.GroupBy);
                currentObject = current;
            }

            if (result)
            {
                currentObject = current.OrderBy;
                this.VisitExpressionList(selectExpression.OrderBy);
                currentObject = current;
            }


            return(selectExpression);
        }