private TablePlan JoinToSingle(IList<TablePlan> allPlans)
{
// If there are no plans then return null
if (allPlans.Count == 0)
return null;
if (allPlans.Count == 1)
// Return early if there is only 1 table.
return allPlans[0];
// Make a working copy of the plan list.
var workingPlanList = new List<TablePlan>(allPlans);
// We go through each plan in turn.
while (workingPlanList.Count > 1) {
var leftPlan = workingPlanList[0];
var rightPlan = workingPlanList[1];
// First we need to determine if the left and right plan can be
// naturally joined.
int status = AssertBeNaturalJoin(leftPlan, rightPlan);
if (status == 0) {
// Yes they can so join them
var newPlan = NaturallyJoinPlans(leftPlan, rightPlan);
// Remove the left and right plan from the list and add the new plan
workingPlanList.Remove(leftPlan);
workingPlanList.Remove(rightPlan);
workingPlanList.Insert(0, newPlan);
} else if (status == 1) {
// No we can't because of a right join clash, so we join the left
// plan right in hopes of resolving the clash.
var newPlan = NaturallyJoinPlans(leftPlan, leftPlan.RightPlan);
workingPlanList.Remove(leftPlan);
workingPlanList.Remove(leftPlan.RightPlan);
workingPlanList.Insert(0, newPlan);
} else if (status == 2) {
// No we can't because of a left join clash, so we join the left
// plan left in hopes of resolving the clash.
var newPlan = NaturallyJoinPlans(leftPlan, leftPlan.LeftPlan);
workingPlanList.Remove(leftPlan);
workingPlanList.Remove(leftPlan.LeftPlan);
workingPlanList.Insert(0, newPlan);
} else {
throw new InvalidOperationException(String.Format("Natural join assessed status {0} is unknown.", status));
}
}
// Return the working plan of the merged tables.
return workingPlanList[0];
}