class ReplaceViews implements OptimizerRule {

    @Override
    public PlanNode execute( QueryContext context,
                             PlanNode plan,
                             LinkedList<OptimizerRule> ruleStack ) {
        CanonicalPlanner planner = new CanonicalPlanner();

        // Prepare the maps that will record the old-to-new mappings from the old view SOURCE nodes to the table SOURCEs ...

        // For each of the SOURCE nodes ...
        Schemata schemata = context.getSchemata();
        Set<PlanNode> processedSources = new HashSet<PlanNode>();
        boolean foundViews = false;
        do {
            foundViews = false;
            for (PlanNode sourceNode : plan.findAllAtOrBelow(Type.SOURCE)) {
                if (processedSources.contains(sourceNode)) continue;
                processedSources.add(sourceNode);

                // Resolve the node to find the definition in the schemata ...
                SelectorName tableName = sourceNode.getProperty(Property.SOURCE_NAME, SelectorName.class);
                SelectorName tableAlias = sourceNode.getProperty(Property.SOURCE_ALIAS, SelectorName.class);
                Table table = schemata.getTable(tableName);
                if (table instanceof View) {
                    View view = (View)table;
                    PlanNode viewPlan = planner.createPlan(context, view.getDefinition());
                    if (viewPlan == null) continue; // there were likely errors when creating the plan

                    // If the view doesn't have an alias, or if the view's alias doesn't match the table's name/alias ...
                    PlanNode viewProjectNode = viewPlan.findAtOrBelow(Type.PROJECT);
                    if (viewProjectNode.getSelectors().size() == 1) {
                        SelectorName tableAliasOrName = tableAlias != null ? tableAlias : tableName;
                        SelectorName viewAlias = viewProjectNode.getSelectors().iterator().next();
                        // Replace the view's alias ...
                        Map<SelectorName, SelectorName> replacements = Collections.singletonMap(viewAlias, tableAliasOrName);
                        PlanUtil.replaceReferencesToRemovedSource(context, viewPlan, replacements);

                        if (!context.getHints().validateColumnExistance) {
                            // Find the next highest PROJECT node above the source ...
                            PlanNode project = sourceNode.findAncestor(Type.PROJECT);
                            if (project != null) {
                                List<Column> projectedColumns = project.getPropertyAsList(Property.PROJECT_COLUMNS, Column.class);
                                // There may be columns that don't appear in the source, so make sure they are there ...
                                viewPlan = PlanUtil.addMissingProjectColumns(context, viewProjectNode, projectedColumns);
                                assert viewPlan != null;
                            }
                        }
                    }

                    // Insert the view plan under the parent SOURCE node ...
                    sourceNode.addLastChild(viewPlan);

                    // Remove the source node ...
                    sourceNode.extractFromParent();

                    // // Replace the original view's name with the name/alias ...
                    PlanNode parent = viewPlan.getParent();
                    if (parent != null) {
                        PlanUtil.ColumnMapping aliasMappings = null;
                        if (tableAlias != null) {
                            aliasMappings = PlanUtil.createMappingForAliased(tableAlias, view, viewPlan);
                            PlanUtil.replaceViewReferences(context, parent, aliasMappings);
                        }
                        PlanUtil.ColumnMapping viewMappings = PlanUtil.createMappingFor(view, viewPlan);
                        PlanUtil.replaceViewReferences(context, parent, viewMappings);
                    }

                    if (viewPlan.is(Type.PROJECT)) {
                        // The PROJECT from the plan may actually not be needed if there is another PROJECT above it ...
                        PlanNode node = viewPlan.getParent();
                        while (node != null) {
                            if (node.isOneOf(Type.JOIN)) break;
                            if (node.is(Type.PROJECT) && viewPlan.getSelectors().containsAll(node.getSelectors())) {
                                viewPlan.extractFromParent();
                                break;
                            }
                            node = node.getParent();
                        }
                    }
                    foundViews = true;
                }
            }
        } while (foundViews);

        if (foundViews) {
            // We'll need to try to push up criteria from the join, but we only should do this after this rule
            // is completely done ...
            if (!(ruleStack.getFirst() instanceof RaiseSelectCriteria)) {
                ruleStack.addFirst(RaiseSelectCriteria.INSTANCE);
                ruleStack.addFirst(PushSelectCriteria.INSTANCE);
            }

            // We re-wrote at least one SOURCE, but the resulting plan tree for the view could actually reference
            // other views. Therefore, re-run this rule ...
            ruleStack.addFirst(this);
        }
        return plan;
    }

}