protected void MoveCurrentStatementToSqlTable(
            SqlStatementBuilder sqlStatementBuilder,
            ISqlPreparationContext context,
            Func <ITableInfo, SqlTable> tableGenerator,
            ISqlPreparationStage stage,
            OrderingExtractionPolicy orderingExtractionPolicy = OrderingExtractionPolicy.ExtractOrderingsIntoProjection)
        {
            // Ensure that select clause is named - usually SqlPreparationQueryModelVisitor would do this, but it hasn't done it yet
            sqlStatementBuilder.SelectProjection = new NamedExpression(null, sqlStatementBuilder.SelectProjection);

            var oldStatement       = sqlStatementBuilder.GetStatementAndResetBuilder();
            var fromExpressionInfo = stage.PrepareFromExpression(
                new SqlSubStatementExpression(oldStatement),
                context,
                tableGenerator,
                orderingExtractionPolicy);

            sqlStatementBuilder.SqlTables.Add(fromExpressionInfo.SqlTable);
            sqlStatementBuilder.SelectProjection = fromExpressionInfo.ItemSelector;
            sqlStatementBuilder.Orderings.AddRange(fromExpressionInfo.ExtractedOrderings);
            Assertion.DebugAssert(fromExpressionInfo.WhereCondition == null);

            // the new statement is an identity query that selects the result of its subquery, so it starts with the same data type
            sqlStatementBuilder.DataInfo = oldStatement.DataInfo;

            AddMappingForItemExpression(context, oldStatement.DataInfo, fromExpressionInfo.ItemSelector);
        }
        public SqlTableBase AddQuerySource(IQuerySource source, Expression fromExpression)
        {
            ArgumentUtility.CheckNotNull("source", source);
            ArgumentUtility.CheckNotNull("fromExpression", fromExpression);

            var fromExpressionInfo = _stage.PrepareFromExpression(fromExpression, _context, info => new SqlTable(info, JoinSemantics.Inner));

            AddPreparedFromExpression(fromExpressionInfo);

            _context.AddExpressionMapping(new QuerySourceReferenceExpression(source), fromExpressionInfo.ItemSelector);
            return(fromExpressionInfo.SqlTable);
        }