[teiid-commits] teiid SVN: r1222 - in trunk: engine/src/main/java/com/metamatrix/query/processor/dynamic and 17 other directories.

teiid-commits at lists.jboss.org teiid-commits at lists.jboss.org
Sat Aug 8 22:07:35 EDT 2009


Author: shawkins
Date: 2009-08-08 22:07:34 -0400 (Sat, 08 Aug 2009)
New Revision: 1222

Removed:
   trunk/engine/src/main/java/com/metamatrix/query/rewriter/VariableSubstitutionVisitor.java
   trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/CorrelatedVariableSubstitutionVisitor.java
   trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/EvaluateExpressionVisitor.java
   trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/VariableCollectorVisitor.java
Modified:
   trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/NewCalculateCostUtil.java
   trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleCleanCriteria.java
   trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleRaiseAccess.java
   trunk/engine/src/main/java/com/metamatrix/query/processor/dynamic/SqlEval.java
   trunk/engine/src/main/java/com/metamatrix/query/processor/proc/ExecDynamicSqlInstruction.java
   trunk/engine/src/main/java/com/metamatrix/query/processor/proc/ProcedurePlan.java
   trunk/engine/src/main/java/com/metamatrix/query/processor/relational/AccessNode.java
   trunk/engine/src/main/java/com/metamatrix/query/processor/relational/RelationalNodeUtil.java
   trunk/engine/src/main/java/com/metamatrix/query/processor/xquery/XQueryPlan.java
   trunk/engine/src/main/java/com/metamatrix/query/rewriter/QueryRewriter.java
   trunk/engine/src/main/java/com/metamatrix/query/sql/lang/XQuery.java
   trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/EvaluatableVisitor.java
   trunk/engine/src/main/java/com/metamatrix/query/validator/ValidationVisitor.java
   trunk/engine/src/main/java/com/metamatrix/query/xquery/XQueryExpression.java
   trunk/engine/src/main/java/com/metamatrix/query/xquery/XQuerySQLEvaluator.java
   trunk/engine/src/main/java/com/metamatrix/query/xquery/saxon/SaxonXQueryExpression.java
   trunk/engine/src/test/java/com/metamatrix/query/processor/dynamic/TestSqlEval.java
   trunk/engine/src/test/java/com/metamatrix/query/processor/eval/TestExpressionEvaluator.java
   trunk/engine/src/test/java/com/metamatrix/query/processor/proc/TestProcedureProcessor.java
   trunk/engine/src/test/java/com/metamatrix/query/resolver/TestResolver.java
   trunk/engine/src/test/java/com/metamatrix/query/resolver/TestXMLResolver.java
   trunk/engine/src/test/java/com/metamatrix/query/rewriter/TestQueryRewriter.java
   trunk/engine/src/test/java/com/metamatrix/query/xquery/HardcodedSqlEval.java
   trunk/engine/src/test/java/com/metamatrix/query/xquery/TestXQueryEngine.java
   trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatement.java
   trunk/metadata/src/main/java/org/teiid/connector/metadata/MetadataResultsPostProcessor.java
Log:
TEIID-308  TEIID-759 merging misc. visitors with the rewriter and fixing xquery parameter evaluation

Modified: trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/NewCalculateCostUtil.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/NewCalculateCostUtil.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/NewCalculateCostUtil.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -65,7 +65,7 @@
 import com.metamatrix.query.sql.symbol.SingleElementSymbol;
 import com.metamatrix.query.sql.util.SymbolMap;
 import com.metamatrix.query.sql.visitor.ElementCollectorVisitor;
-import com.metamatrix.query.sql.visitor.EvaluateExpressionVisitor;
+import com.metamatrix.query.sql.visitor.EvaluatableVisitor;
 import com.metamatrix.query.sql.visitor.GroupsUsedByElementsVisitor;
 import com.metamatrix.query.util.CommandContext;
 import com.metamatrix.query.util.LogConstants;
@@ -669,7 +669,7 @@
             if(compareValue != null && compareValue.indexOf('%') < 0) {
             	return (childCost / 2) * (1 / 3f  + 1 / ndv); //without knowing length constraints we'll make an average guess
             }
-        } else if (EvaluateExpressionVisitor.willBecomeConstant(criteria.getLeftExpression())) {
+        } else if (EvaluatableVisitor.willBecomeConstant(criteria.getLeftExpression())) {
             return childCost / ndv;
         }
         return childCost / 3;

Modified: trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleCleanCriteria.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleCleanCriteria.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleCleanCriteria.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -36,7 +36,7 @@
 import com.metamatrix.query.optimizer.relational.plantree.NodeEditor;
 import com.metamatrix.query.optimizer.relational.plantree.PlanNode;
 import com.metamatrix.query.sql.lang.Criteria;
-import com.metamatrix.query.sql.visitor.EvaluateExpressionVisitor;
+import com.metamatrix.query.sql.visitor.EvaluatableVisitor;
 import com.metamatrix.query.util.CommandContext;
 
 /**
@@ -67,7 +67,7 @@
             
             Criteria crit = (Criteria)critNode.getProperty(NodeConstants.Info.SELECT_CRITERIA);
             //if not evaluatable, just move on to the next criteria
-            if (!EvaluateExpressionVisitor.isFullyEvaluatable(crit, true)) {
+            if (!EvaluatableVisitor.isFullyEvaluatable(crit, true)) {
                 continue;
             }
             //if evaluatable

Modified: trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleRaiseAccess.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleRaiseAccess.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleRaiseAccess.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -55,7 +55,7 @@
 import com.metamatrix.query.sql.symbol.GroupSymbol;
 import com.metamatrix.query.sql.symbol.SingleElementSymbol;
 import com.metamatrix.query.sql.util.SymbolMap;
-import com.metamatrix.query.sql.visitor.EvaluateExpressionVisitor;
+import com.metamatrix.query.sql.visitor.EvaluatableVisitor;
 import com.metamatrix.query.util.CommandContext;
 
 public final class RuleRaiseAccess implements OptimizerRule {
@@ -370,7 +370,7 @@
         
         if(inSelectClause && !(expr instanceof ElementSymbol)) {
 			if (!CapabilitiesUtil.supportsSelectLiterals(modelID, metadata, capFinder) 
-        		&& (expr instanceof Constant || EvaluateExpressionVisitor.willBecomeConstant(expr))) {
+        		&& (expr instanceof Constant || EvaluatableVisitor.willBecomeConstant(expr))) {
         		return false;
         	}
         }                

Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/dynamic/SqlEval.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/dynamic/SqlEval.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/dynamic/SqlEval.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -23,21 +23,28 @@
 package com.metamatrix.query.processor.dynamic;
 
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.Iterator;
 import java.util.List;
+import java.util.Map;
 
 import javax.xml.transform.Source;
 
 import com.metamatrix.api.exception.MetaMatrixComponentException;
 import com.metamatrix.api.exception.MetaMatrixProcessingException;
+import com.metamatrix.api.exception.query.ExpressionEvaluationException;
 import com.metamatrix.api.exception.query.QueryParserException;
+import com.metamatrix.common.buffer.BlockedException;
 import com.metamatrix.common.buffer.BufferManager;
 import com.metamatrix.common.buffer.TupleSource;
 import com.metamatrix.common.buffer.TupleSourceID;
 import com.metamatrix.common.buffer.TupleSourceNotFoundException;
 import com.metamatrix.common.types.DataTypeManager;
-import com.metamatrix.core.MetaMatrixCoreException;
+import com.metamatrix.query.eval.Evaluator;
+import com.metamatrix.query.processor.ProcessorDataManager;
 import com.metamatrix.query.processor.QueryProcessor;
+import com.metamatrix.query.sql.symbol.ElementSymbol;
+import com.metamatrix.query.sql.symbol.Expression;
 import com.metamatrix.query.sql.symbol.SingleElementSymbol;
 import com.metamatrix.query.sql.symbol.Symbol;
 import com.metamatrix.query.util.CommandContext;
@@ -54,11 +61,15 @@
     private CommandContext context;
     private ArrayList<TupleSourceID> openTupleList;
     private String parentGroup;
+    private Map<String, Expression> params;
+    private ProcessorDataManager dataManager;
     
-    public SqlEval(BufferManager bufferMgr, CommandContext context, String parentGroup) {
+    public SqlEval(BufferManager bufferMgr, ProcessorDataManager dataManager, CommandContext context, String parentGroup, Map<String, Expression> params) {
         this.bufferMgr = bufferMgr;
+        this.dataManager = dataManager;
         this.context = context;
         this.parentGroup = parentGroup;
+        this.params = params;
     }
 
     /** 
@@ -94,6 +105,14 @@
         }
         return SQLSource.createSource(columns, types, src);
     }
+    
+    @Override
+    public Object getParameterValue(String key) throws ExpressionEvaluationException, BlockedException, MetaMatrixComponentException {
+    	String paramName = this.parentGroup + ElementSymbol.SEPARATOR + key;
+    	paramName = paramName.toUpperCase();
+    	Expression expr = this.params.get(paramName);
+    	return new Evaluator(Collections.emptyMap(), this.dataManager, context).evaluate(expr, Collections.emptyList());
+    }
 
     /**
      * Get the Column names from Element Objects 

Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/proc/ExecDynamicSqlInstruction.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/proc/ExecDynamicSqlInstruction.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/proc/ExecDynamicSqlInstruction.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -54,7 +54,6 @@
 import com.metamatrix.query.resolver.util.ResolveVirtualGroupCriteriaVisitor;
 import com.metamatrix.query.resolver.util.ResolverUtil;
 import com.metamatrix.query.rewriter.QueryRewriter;
-import com.metamatrix.query.rewriter.VariableSubstitutionVisitor;
 import com.metamatrix.query.sql.ProcedureReservedWords;
 import com.metamatrix.query.sql.lang.Command;
 import com.metamatrix.query.sql.lang.DynamicCommand;
@@ -190,10 +189,8 @@
             nameValueMap.putAll(QueryResolver.getVariableValues(parentProcCommand.getUserCommand(), metadata));
             // validation visitor?
 
-            VariableSubstitutionVisitor.substituteVariables(command, nameValueMap, command.getType());
-            
 			QueryRewriter.rewrite(command, parentProcCommand, metadata,
-					procEnv.getContext());
+					procEnv.getContext(), nameValueMap, parentProcCommand.getUserCommand().getType());
 
 			if (dynamicCommand.getAsColumns() != null
 					&& !dynamicCommand.getAsColumns().isEmpty()) {

Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/proc/ProcedurePlan.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/proc/ProcedurePlan.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/proc/ProcedurePlan.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -44,7 +44,6 @@
 import com.metamatrix.common.buffer.TupleSourceID;
 import com.metamatrix.common.buffer.TupleSourceNotFoundException;
 import com.metamatrix.common.log.LogManager;
-import com.metamatrix.core.MetaMatrixCoreException;
 import com.metamatrix.dqp.util.LogConstants;
 import com.metamatrix.query.execution.QueryExecPlugin;
 import com.metamatrix.query.metadata.QueryMetadataInterface;
@@ -323,21 +322,11 @@
     private TupleSource getResults()
         throws MetaMatrixComponentException, BlockedException, MetaMatrixProcessingException {
 
-		TupleSource results;
+        this.internalProcessor.process(Integer.MAX_VALUE); //TODO: put a better value here
 
-        try {
-            this.internalProcessor.process(Integer.MAX_VALUE); //TODO: put a better value here
+        // didn't throw processor blocked, so must be done
+        TupleSource results = this.bufferMgr.getTupleSource(this.internalResultID);
 
-            // didn't throw processor blocked, so must be done
-            results = this.bufferMgr.getTupleSource(this.internalResultID);
-        } catch(MetaMatrixComponentException e) {
-            throw e;
-        } catch (MetaMatrixProcessingException e) {
-        	throw e;
-        } catch(MetaMatrixCoreException e) {
-            throw new MetaMatrixComponentException(e, ErrorMessageKeys.PROCESSOR_0023, QueryExecPlugin.Util.getString(ErrorMessageKeys.PROCESSOR_0023, e.getMessage()));
-        }
-
         // clean up internal stuff
         this.internalProcessor = null;
 

Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/relational/AccessNode.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/relational/AccessNode.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/relational/AccessNode.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -37,7 +37,6 @@
 import com.metamatrix.query.execution.QueryExecPlugin;
 import com.metamatrix.query.rewriter.QueryRewriter;
 import com.metamatrix.query.sql.lang.Command;
-import com.metamatrix.query.sql.visitor.EvaluateExpressionVisitor;
 import com.metamatrix.query.util.CommandContext;
 
 public class AccessNode extends RelationalNode {
@@ -114,12 +113,9 @@
 	static boolean prepareCommand(Command atomicCommand, RelationalNode node, CommandContext context)
 			throws ExpressionEvaluationException, MetaMatrixComponentException,
 			MetaMatrixProcessingException, CriteriaEvaluationException {
-		// evaluate all references and any functions on constant values
-        EvaluateExpressionVisitor.replaceExpressions(atomicCommand, true, node.getDataManager(), context);                            
-        
         try {
             // Defect 16059 - Rewrite the command once the references have been replaced with values.
-            QueryRewriter.rewrite(atomicCommand, null, null, context);
+            QueryRewriter.evaluateAndRewrite(atomicCommand, node.getDataManager(), context);
         } catch (QueryValidatorException e) {
             throw new MetaMatrixProcessingException(e, QueryExecPlugin.Util.getString("AccessNode.rewrite_failed", atomicCommand)); //$NON-NLS-1$
         }

Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/relational/RelationalNodeUtil.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/relational/RelationalNodeUtil.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/relational/RelationalNodeUtil.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -35,7 +35,7 @@
 import com.metamatrix.query.sql.lang.SetQuery;
 import com.metamatrix.query.sql.lang.Update;
 import com.metamatrix.query.sql.symbol.Constant;
-import com.metamatrix.query.sql.visitor.EvaluateExpressionVisitor;
+import com.metamatrix.query.sql.visitor.EvaluatableVisitor;
 
 
 /** 
@@ -109,7 +109,7 @@
 
                 if(criteria == null) {
                     return true;
-                } else if(!EvaluateExpressionVisitor.isFullyEvaluatable(criteria, false)) {
+                } else if(!EvaluatableVisitor.isFullyEvaluatable(criteria, false)) {
                     // If there are elements present in the criteria,
                     // then we don't know the result, so assume we need to execute
                     return true;
@@ -133,7 +133,7 @@
                 if (criteria == null) {
                 	return true;
                 }
-                if(!EvaluateExpressionVisitor.isFullyEvaluatable(criteria, false)) {
+                if(!EvaluatableVisitor.isFullyEvaluatable(criteria, false)) {
                     return true;
                 } else if(evaluateCriteria(criteria)) {
                     if (simplifyCriteria) {
@@ -150,7 +150,7 @@
                 if (criteria == null) {
                 	return true;
                 }
-                if(!EvaluateExpressionVisitor.isFullyEvaluatable(criteria, false)) {
+                if(!EvaluatableVisitor.isFullyEvaluatable(criteria, false)) {
                     return true;
                 } else if(evaluateCriteria(criteria)) {
                     if (simplifyCriteria) {

Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/xquery/XQueryPlan.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/xquery/XQueryPlan.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/xquery/XQueryPlan.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -61,6 +61,7 @@
     private BufferManager bufferMgr;
     private String xmlFormat;
     private String parentGroup;
+    private ProcessorDataManager dataManager;
 
     private int chunkSize = Streamable.STREAMING_BATCH_SIZE_IN_BYTES;
     private TupleSourceID resultsTupleSourceId;
@@ -90,7 +91,8 @@
      */
     public void initialize(CommandContext context, ProcessorDataManager dataMgr, BufferManager bufferMgr) {
         setContext(context);
-        this.bufferMgr = bufferMgr;        
+        this.bufferMgr = bufferMgr;
+        this.dataManager = dataMgr;
         if(context.getStreamingBatchSize() != 0){
             this.chunkSize = context.getStreamingBatchSize();
         }        
@@ -126,7 +128,7 @@
     	XQueryExpression expr = this.xQuery.getCompiledXQuery();    
         expr.setXMLFormat(xmlFormat);
         
-        SqlEval sqlEval = new SqlEval(bufferMgr, getContext(), this.parentGroup);
+        SqlEval sqlEval = new SqlEval(bufferMgr, this.dataManager, getContext(), this.parentGroup, this.xQuery.getVariables());
         try {
         	SQLXML xml = expr.evaluateXQuery(sqlEval);
             TupleBatch batch = packResultsIntoBatch(xml);        

Modified: trunk/engine/src/main/java/com/metamatrix/query/rewriter/QueryRewriter.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/rewriter/QueryRewriter.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/main/java/com/metamatrix/query/rewriter/QueryRewriter.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -43,6 +43,8 @@
 import org.teiid.connector.api.SourceSystemFunctions;
 
 import com.metamatrix.api.exception.MetaMatrixComponentException;
+import com.metamatrix.api.exception.MetaMatrixException;
+import com.metamatrix.api.exception.MetaMatrixProcessingException;
 import com.metamatrix.api.exception.query.CriteriaEvaluationException;
 import com.metamatrix.api.exception.query.ExpressionEvaluationException;
 import com.metamatrix.api.exception.query.FunctionExecutionException;
@@ -66,10 +68,12 @@
 import com.metamatrix.query.metadata.TempMetadataAdapter;
 import com.metamatrix.query.metadata.TempMetadataID;
 import com.metamatrix.query.metadata.TempMetadataStore;
+import com.metamatrix.query.processor.ProcessorDataManager;
 import com.metamatrix.query.resolver.QueryResolver;
 import com.metamatrix.query.resolver.util.ResolverUtil;
 import com.metamatrix.query.resolver.util.ResolverVisitor;
 import com.metamatrix.query.sql.LanguageObject;
+import com.metamatrix.query.sql.ProcedureReservedWords;
 import com.metamatrix.query.sql.ReservedWords;
 import com.metamatrix.query.sql.lang.AbstractSetCriteria;
 import com.metamatrix.query.sql.lang.BetweenCriteria;
@@ -100,6 +104,7 @@
 import com.metamatrix.query.sql.lang.SPParameter;
 import com.metamatrix.query.sql.lang.Select;
 import com.metamatrix.query.sql.lang.SetClause;
+import com.metamatrix.query.sql.lang.SetClauseList;
 import com.metamatrix.query.sql.lang.SetCriteria;
 import com.metamatrix.query.sql.lang.SetQuery;
 import com.metamatrix.query.sql.lang.StoredProcedure;
@@ -110,6 +115,7 @@
 import com.metamatrix.query.sql.lang.TranslatableProcedureContainer;
 import com.metamatrix.query.sql.lang.UnaryFromClause;
 import com.metamatrix.query.sql.lang.Update;
+import com.metamatrix.query.sql.lang.XQuery;
 import com.metamatrix.query.sql.navigator.PostOrderNavigator;
 import com.metamatrix.query.sql.navigator.PreOrderNavigator;
 import com.metamatrix.query.sql.proc.AssignmentStatement;
@@ -132,17 +138,18 @@
 import com.metamatrix.query.sql.symbol.ExpressionSymbol;
 import com.metamatrix.query.sql.symbol.Function;
 import com.metamatrix.query.sql.symbol.GroupSymbol;
+import com.metamatrix.query.sql.symbol.Reference;
 import com.metamatrix.query.sql.symbol.ScalarSubquery;
 import com.metamatrix.query.sql.symbol.SearchedCaseExpression;
 import com.metamatrix.query.sql.symbol.SingleElementSymbol;
 import com.metamatrix.query.sql.util.SymbolMap;
 import com.metamatrix.query.sql.visitor.AggregateSymbolCollectorVisitor;
-import com.metamatrix.query.sql.visitor.CorrelatedVariableSubstitutionVisitor;
 import com.metamatrix.query.sql.visitor.CriteriaTranslatorVisitor;
 import com.metamatrix.query.sql.visitor.ElementCollectorVisitor;
-import com.metamatrix.query.sql.visitor.EvaluateExpressionVisitor;
+import com.metamatrix.query.sql.visitor.EvaluatableVisitor;
 import com.metamatrix.query.sql.visitor.ExpressionMappingVisitor;
 import com.metamatrix.query.sql.visitor.PredicateCollectorVisitor;
+import com.metamatrix.query.sql.visitor.EvaluatableVisitor.EvaluationLevel;
 import com.metamatrix.query.util.CommandContext;
 import com.metamatrix.query.util.ErrorMessageKeys;
 
@@ -170,41 +177,81 @@
     	ALIASED_FUNCTIONS.put("||", SourceSystemFunctions.CONCAT); //$NON-NLS-1$
     	ALIASED_FUNCTIONS.put("chr", SourceSystemFunctions.CHAR); //$NON-NLS-1$
     }
+    
+    private QueryMetadataInterface metadata;
+    private CommandContext context;
+    private CreateUpdateProcedureCommand procCommand;
+    
+    private boolean rewriteSubcommands;
+    private ProcessorDataManager dataMgr;
+    private Map variables; //constant propagation
+    private int commandType;
+   
+    private QueryRewriter(QueryMetadataInterface metadata,
+			CommandContext context, CreateUpdateProcedureCommand procCommand) {
+		this.metadata = metadata;
+		this.context = context;
+		this.procCommand = procCommand;
+	}
+    
+    public static Command evaluateAndRewrite(Command command, ProcessorDataManager dataMgr, CommandContext context) throws MetaMatrixProcessingException, MetaMatrixComponentException {
+    	QueryRewriter queryRewriter = new QueryRewriter(null, context, null);
+    	queryRewriter.dataMgr = dataMgr;
+    	queryRewriter.rewriteSubcommands = true;
+    	try {
+    		return queryRewriter.rewriteCommand(command, false);
+    	} catch (MetaMatrixRuntimeException err) {
+    		Throwable e = err.getChild();
+            
+            if (e == null) {
+                throw err;
+            }
+            
+            if(e instanceof ExpressionEvaluationException) {
+                throw (ExpressionEvaluationException) e;
+            } else if(e instanceof MetaMatrixComponentException) {
+                throw (MetaMatrixComponentException) e;                    
+            } else {
+                throw new MetaMatrixComponentException(e, e.getMessage());    
+            }
+    	}
+    }
 
-	private QueryRewriter() { }
-
-    public static Command rewrite(Command command, Command procCommand, QueryMetadataInterface metadata, CommandContext context) throws QueryValidatorException {
-        return rewriteCommand(command, procCommand, metadata, context, false);
+	public static Command rewrite(Command command, CreateUpdateProcedureCommand procCommand, QueryMetadataInterface metadata, CommandContext context, Map variableValues, int commandType) throws QueryValidatorException {
+		QueryRewriter rewriter = new QueryRewriter(metadata, context, procCommand);
+		rewriter.rewriteSubcommands = true;
+		rewriter.variables = variableValues;
+		rewriter.commandType = commandType;
+		return rewriter.rewriteCommand(command, false);
+	}
+    
+	public static Command rewrite(Command command, CreateUpdateProcedureCommand procCommand, QueryMetadataInterface metadata, CommandContext context) throws QueryValidatorException {
+		return rewrite(command, procCommand, metadata, context, null, Command.TYPE_UNKNOWN);
     }
 
     /**
      * Rewrites the command and all of its subcommands (both embedded and non-embedded)
      *  
      * @param command
-     * @param procCommand
-     * @param metadata
-     * @param context
      * @param removeOrderBy
      * @return
      * @throws QueryValidatorException
      */
-	private static Command rewriteCommand(Command command, Command procCommand, final QueryMetadataInterface metadata, final CommandContext context, boolean removeOrderBy) throws QueryValidatorException {
-
-        //TODO: this should be merged with the normal functioning of the rewriter
-        CorrelatedVariableSubstitutionVisitor.substituteVariables(command);
+	private Command rewriteCommand(Command command, boolean removeOrderBy) throws QueryValidatorException {
+		QueryMetadataInterface oldMetadata = metadata;
+		CreateUpdateProcedureCommand oldProcCommand = procCommand;
         
-        Map tempMetadata = command.getTemporaryMetadata();
-        QueryMetadataInterface rewriteMetadata = metadata;
+		Map tempMetadata = command.getTemporaryMetadata();
         if(tempMetadata != null) {
-        	rewriteMetadata = new TempMetadataAdapter(metadata, new TempMetadataStore(tempMetadata));
+        	metadata = new TempMetadataAdapter(metadata, new TempMetadataStore(tempMetadata));
         }
         
         switch(command.getType()) {
 			case Command.TYPE_QUERY:
                 if(command instanceof Query) {
-                    command = rewriteQuery((Query) command, procCommand, rewriteMetadata, context);
+                    command = rewriteQuery((Query) command);
                 }else {
-                    command = rewriteSetQuery((SetQuery) command, procCommand, rewriteMetadata, context);
+                    command = rewriteSetQuery((SetQuery) command);
                 }
             	if (removeOrderBy) {
                 	QueryCommand queryCommand = (QueryCommand)command;
@@ -214,35 +261,38 @@
                 }
                 break;
             case Command.TYPE_STORED_PROCEDURE:
-                command = rewriteExec((StoredProcedure) command, procCommand, rewriteMetadata, context);
+                command = rewriteExec((StoredProcedure) command);
                 break;
     		case Command.TYPE_INSERT:
-                command = rewriteInsert((Insert) command, procCommand, context, rewriteMetadata);
+                command = rewriteInsert((Insert) command);
                 break;
 			case Command.TYPE_UPDATE:
-                command = rewriteUpdate((Update) command, procCommand, context, rewriteMetadata);
+                command = rewriteUpdate((Update) command);
                 break;
 			case Command.TYPE_DELETE:
-                command = rewriteDelete((Delete) command, procCommand, context, rewriteMetadata);
+                command = rewriteDelete((Delete) command);
                 break;
             case Command.TYPE_UPDATE_PROCEDURE:
-                procCommand = command;
-                command = rewriteUpdateProcedure((CreateUpdateProcedureCommand) command, rewriteMetadata, context);
+                procCommand = (CreateUpdateProcedureCommand) command;
+                command = rewriteUpdateProcedure((CreateUpdateProcedureCommand) command);
                 break;
+            case Command.TYPE_XQUERY:
+            	((XQuery)command).setVariables(this.variables);
+            	break;
 		}
         
         //recursively rewrite simple containers - after the container itself was rewritten
         if (command instanceof CommandContainer) {
-            List subCommands = ((CommandContainer)command).getContainedCommands();
+            Map oldVariables = variables;
+        	List subCommands = ((CommandContainer)command).getContainedCommands();
             for (int i = 0; i < subCommands.size(); i++) {
                 Command subCommand = (Command)subCommands.get(i);
                 
                 if (command instanceof ProcedureContainer) {
                        
                     try {
-    	                Map variables = QueryResolver.getVariableValues(command, metadata);                        
-                        VariableSubstitutionVisitor.substituteVariables(subCommand, variables, command.getType());
-
+    	                variables = QueryResolver.getVariableValues(command, metadata);                        
+    	                commandType = command.getType();
                     } catch (QueryMetadataException err) {
                         throw new QueryValidatorException(err, err.getMessage());
                     } catch (QueryResolverException err) {
@@ -252,15 +302,19 @@
                     }
                 }
                 
-                subCommand = rewriteCommand(subCommand, procCommand, metadata, context, false);
+                subCommand = rewriteCommand(subCommand, false);
                 subCommands.set(i, subCommand);
             }
+            variables = oldVariables;
         }
 
-        return removeProceduralWrapper(command, metadata);
+        Command result = removeProceduralWrapper(command);
+        this.metadata = oldMetadata;
+        this.procCommand = oldProcCommand;
+        return result;
 	}
     
-    private static Option mergeOptions( Option sourceOption, Option targetOption ) {
+    private Option mergeOptions( Option sourceOption, Option targetOption ) {
         if ( sourceOption == null ) {
             return targetOption;
         }
@@ -278,7 +332,7 @@
     }
     
 	
-    private static Command removeProceduralWrapper(Command command, QueryMetadataInterface metadata) throws QueryValidatorException {
+    private Command removeProceduralWrapper(Command command) throws QueryValidatorException {
         
         if (!(command instanceof StoredProcedure)) {
             return command;
@@ -303,7 +357,7 @@
         for (Iterator iter = container.getInputParameters().iterator(); iter.hasNext();) {
             SPParameter param = (SPParameter)iter.next();
             Expression expr = param.getExpression();
-            if (!EvaluateExpressionVisitor.isFullyEvaluatable(expr, true)) {
+            if (!EvaluatableVisitor.isFullyEvaluatable(expr, true)) {
                 return command;
             }
             try {
@@ -344,16 +398,16 @@
         return command;
     }
 
-	private static Command rewriteUpdateProcedure(CreateUpdateProcedureCommand procCommand, QueryMetadataInterface metadata, CommandContext context)
+	private Command rewriteUpdateProcedure(CreateUpdateProcedureCommand command)
 								 throws QueryValidatorException {
 		
-		Block block = rewriteBlock(procCommand.getBlock(), procCommand, context, metadata);
-        procCommand.setBlock(block);
+		Block block = rewriteBlock(command.getBlock());
+        command.setBlock(block);
         
-        return procCommand;
+        return command;
 	}
 
-	private static Block rewriteBlock(Block block, Command procCommand, CommandContext context, QueryMetadataInterface metadata)
+	private Block rewriteBlock(Block block)
 								 throws QueryValidatorException {
 		List statements = block.getStatements();
         Iterator stmtIter = statements.iterator();
@@ -362,7 +416,7 @@
 		// plan each statement in the block
         while(stmtIter.hasNext()) {
 			Statement stmnt = (Statement) stmtIter.next();
-			Object newStmt = rewriteStatement(stmnt, procCommand, context, metadata);
+			Object newStmt = rewriteStatement(stmnt);
 			if(newStmt instanceof Statement) {
 				newStmts.add(newStmt);
 			} else if (newStmt instanceof List) {
@@ -375,7 +429,7 @@
         return block;
 	 }
 
-	private static Object rewriteStatement(Statement statement, Command procCommand, CommandContext context, QueryMetadataInterface metadata)
+	private Object rewriteStatement(Statement statement)
 								 throws QueryValidatorException {
 
         // evaluate the HAS Criteria on the procedure and rewrite
@@ -384,24 +438,24 @@
 			case Statement.TYPE_IF:
 				IfStatement ifStmt = (IfStatement) statement;
 				Criteria ifCrit = ifStmt.getCondition();
-				Criteria evalCrit = rewriteCriteria(ifCrit, procCommand, context, metadata);
+				Criteria evalCrit = rewriteCriteria(ifCrit, false);
                 evalCrit = evaluateCriteria(evalCrit);
                 
 				ifStmt.setCondition(evalCrit);
 				if(evalCrit.equals(TRUE_CRITERIA)) {
-					Block ifblock = rewriteBlock(ifStmt.getIfBlock(), procCommand, context, metadata);
+					Block ifblock = rewriteBlock(ifStmt.getIfBlock());
 					return ifblock.getStatements();
 				} else if(evalCrit.equals(FALSE_CRITERIA) || evalCrit.equals(UNKNOWN_CRITERIA)) {
 					if(ifStmt.hasElseBlock()) {
-						Block elseBlock = rewriteBlock(ifStmt.getElseBlock(), procCommand, context, metadata);
+						Block elseBlock = rewriteBlock(ifStmt.getElseBlock());
 						return elseBlock.getStatements();
 					} 
                     return null;
 				} else {
-					Block ifblock = rewriteBlock(ifStmt.getIfBlock(), procCommand, context, metadata);
+					Block ifblock = rewriteBlock(ifStmt.getIfBlock());
 					ifStmt.setIfBlock(ifblock);
 					if(ifStmt.hasElseBlock()) {
-						Block elseBlock = rewriteBlock(ifStmt.getElseBlock(), procCommand, context, metadata);
+						Block elseBlock = rewriteBlock(ifStmt.getElseBlock());
 						ifStmt.setElseBlock(elseBlock);
 					}
 				}
@@ -414,10 +468,10 @@
 				// replaced in the processor with variable values
                 if (assStmt.hasExpression()) {
     				Expression expr = assStmt.getExpression();
-    				expr = rewriteExpression(expr, procCommand, context, metadata);
+    				expr = rewriteExpressionDirect(expr);
                     assStmt.setExpression(expr);
                 } else if (assStmt.hasCommand()) {
-                    rewriteSubqueryContainer(assStmt, procCommand, context, metadata, false);
+                    rewriteSubqueryContainer(assStmt, false);
                     
                     if(assStmt.getCommand().getType() == Command.TYPE_UPDATE) {
                         Update update = (Update)assStmt.getCommand();
@@ -429,7 +483,7 @@
 				return assStmt;
 			case Statement.TYPE_COMMAND:
 				CommandStatement cmdStmt = (CommandStatement) statement;
-                rewriteSubqueryContainer(cmdStmt, procCommand, context, metadata, false);
+                rewriteSubqueryContainer(cmdStmt, false);
                 
 				if(cmdStmt.getCommand().getType() == Command.TYPE_UPDATE) {
                     Update update = (Update)cmdStmt.getCommand();
@@ -441,9 +495,9 @@
             case Statement.TYPE_LOOP: 
                 LoopStatement loop = (LoopStatement)statement; 
                 
-                rewriteSubqueryContainer(loop, procCommand, context, metadata, false);
+                rewriteSubqueryContainer(loop, false);
                 
-                rewriteBlock(loop.getBlock(), procCommand, context, metadata);
+                rewriteBlock(loop.getBlock());
                 
                 if (loop.getBlock().getStatements().isEmpty()) {
                     return null;
@@ -453,6 +507,7 @@
             case Statement.TYPE_WHILE:
                 WhileStatement whileStatement = (WhileStatement) statement;
                 Criteria crit = whileStatement.getCondition();
+                crit = rewriteCriteria(crit, false);
                 evalCrit = evaluateCriteria(crit);
                 
                 whileStatement.setCondition(evalCrit);
@@ -461,7 +516,7 @@
                 } else if(evalCrit.equals(FALSE_CRITERIA) || evalCrit.equals(UNKNOWN_CRITERIA)) {
                     return null;
                 } 
-                whileStatement.setBlock(rewriteBlock(whileStatement.getBlock(), procCommand, context, metadata));
+                whileStatement.setBlock(rewriteBlock(whileStatement.getBlock()));
                 
                 if (whileStatement.getBlock().getStatements().isEmpty()) {
                     return null;
@@ -474,17 +529,13 @@
 	}
     
     /** 
-     * @param procCommand
-     * @param context
-     * @param metadata
      * @param removeOrderBy
      * @param assStmt
      * @throws QueryValidatorException
      */
-    private static void rewriteSubqueryContainer(SubqueryContainer container, Command procCommand,
-                                                 CommandContext context, QueryMetadataInterface metadata, boolean removeOrderBy) throws QueryValidatorException {
-        if (container.getCommand() != null && container.getCommand().getProcessorPlan() == null && metadata != null) {
-        	container.setCommand(rewriteCommand(container.getCommand(), procCommand, metadata, context, removeOrderBy));
+    private void rewriteSubqueryContainer(SubqueryContainer container, boolean removeOrderBy) throws QueryValidatorException {
+        if (rewriteSubcommands && container.getCommand() != null && container.getCommand().getProcessorPlan() == null) {
+        	container.setCommand(rewriteCommand(container.getCommand(), removeOrderBy));
         }
     }
     
@@ -493,9 +544,9 @@
 	 * if type of criteria on the elements specified by the CriteriaSelector is specified on
 	 * the user's command.</p>
 	 */
-	private static Criteria rewriteCriteria(HasCriteria hasCrit, Command procCommand, CommandContext context, QueryMetadataInterface metadata) {
+	private Criteria rewriteCriteria(HasCriteria hasCrit) {
 		Criteria userCrit = null;
-		Command userCommand = ((CreateUpdateProcedureCommand)procCommand).getUserCommand();
+		Command userCommand = procCommand.getUserCommand();
 		int cmdType = userCommand.getType();
 		switch(cmdType) {
 			case Command.TYPE_DELETE:
@@ -599,14 +650,12 @@
 	 * virtual group elements and the expressions on the query transformation defining the
 	 * virtual group.</p>
 	 */
-	private static Criteria rewriteCriteria(TranslateCriteria transCrit, Command command, CommandContext context, QueryMetadataInterface metadata)
+	private Criteria rewriteCriteria(TranslateCriteria transCrit)
 			 throws QueryValidatorException {
 
 		// criteria translated
 		Criteria translatedCriteria = null;
 
-		// command received is the procedure
-		CreateUpdateProcedureCommand procCommand = (CreateUpdateProcedureCommand) command;
 		// get the user's command from the procedure
 		Command userCmd = procCommand.getUserCommand();
 
@@ -632,7 +681,7 @@
 
 		// base on the selector evaluate Has criteria, if false
 		// return a false criteria
-		Criteria result = rewriteCriteria(hasCrit, procCommand, context, metadata);
+		Criteria result = rewriteCriteria(hasCrit);
 
 		if(result.equals(FALSE_CRITERIA)) {
 			return FALSE_CRITERIA;
@@ -652,7 +701,7 @@
 		translatedCriteria = translateVisitor.getTranslatedCriteria();
 		((TranslatableProcedureContainer)userCmd).addImplicitParameters(translateVisitor.getImplicitParams());
 		
-		translatedCriteria = rewriteCriteria(translatedCriteria, null, context, metadata);
+		translatedCriteria = rewriteCriteria(translatedCriteria, false);
 
 		// apply any implicit conversions
 		try {
@@ -664,7 +713,7 @@
 		return translatedCriteria;
 	}
 
-	private static Query rewriteQuery(Query query, final Command procCommand, final QueryMetadataInterface metadata, final CommandContext context)
+	private Query rewriteQuery(Query query)
              throws QueryValidatorException {
         
         // Rewrite from clause
@@ -673,7 +722,7 @@
             List clauses = new ArrayList(from.getClauses().size());
             Iterator clauseIter = from.getClauses().iterator();
             while(clauseIter.hasNext()) {
-                clauses.add( rewriteFromClause(query, (FromClause) clauseIter.next(), procCommand, metadata, context) );
+                clauses.add( rewriteFromClause(query, (FromClause) clauseIter.next()) );
             }
             from.setClauses(clauses);
         } else {
@@ -682,8 +731,8 @@
 
         // Rewrite criteria
         Criteria crit = query.getCriteria();
-        if(crit != null && !query.getIsXML()) {
-            crit = rewriteCriteria(crit, procCommand, context, metadata);
+        if(crit != null) {
+            crit = rewriteCriteria(crit, false);
             if(crit == TRUE_CRITERIA) {
                 query.setCriteria(null);
             } else {
@@ -761,21 +810,20 @@
                 outerQuery.setInto(into);
                 outerQuery.setOption(query.getOption());
                 query = outerQuery;
-                rewriteExpressions(innerSelect, procCommand, metadata, context);
+                rewriteExpressions(innerSelect);
             }
         }
 
         // Rewrite having
         Criteria having = query.getHaving();
         if(having != null) {
-            query.setHaving(rewriteCriteria(having, procCommand, context, metadata));
+            query.setHaving(rewriteCriteria(having, false));
         }
                 
-        rewriteExpressions(query.getSelect(), procCommand, metadata, context);
+        rewriteExpressions(query.getSelect());
 
-        if (query.getOrderBy() != null && !query.getIsXML()) {
-            makeSelectUnique(query.getSelect(), true);
-            rewriteOrderBy(query, procCommand, metadata, context);
+        if (!query.getIsXML()) {
+            rewriteOrderBy(query);
         }
         
         if (query.getLimit() != null) {
@@ -783,16 +831,13 @@
         }
         
         if (query.getInto() != null) {
-            query = rewriteSelectInto(query, metadata, procCommand, context);
+            query = rewriteSelectInto(query);
         }
         
         return query;
     }
     
-    private static void rewriteExpressions(LanguageObject obj,
-                                           final Command procCommand,
-                                           final QueryMetadataInterface metadata,
-                                           final CommandContext context) throws QueryValidatorException {
+    private void rewriteExpressions(LanguageObject obj) throws QueryValidatorException {
         if (obj == null) {
             return;
         }
@@ -803,7 +848,7 @@
             @Override
             public Expression replaceExpression(Expression element) {
                 try {
-                    return rewriteExpression(element, procCommand, context, metadata);
+                    return rewriteExpressionDirect(element);
                 } catch (QueryValidatorException err) {
                     throw new MetaMatrixRuntimeException(err);
                 }
@@ -825,22 +870,15 @@
      * @param query
      * @throws QueryValidatorException 
      */
-    public static void rewriteOrderBy(QueryCommand query, Command procCommand, QueryMetadataInterface metadata, CommandContext context) throws QueryValidatorException {
+    private void rewriteOrderBy(QueryCommand query) throws QueryValidatorException {
         OrderBy orderBy = query.getOrderBy();
         if (orderBy == null) {
             return;
         }
-        List projectedSymbols = null;
-        if (query instanceof Query) {
-            if (((Query)query).getIsXML()) {
-                return;
-            }
-            projectedSymbols = ((Query)query).getSelect().getProjectedSymbols();
-        } else {
-            projectedSymbols = query.getProjectedSymbols();
-        }
+        makeSelectUnique(query.getProjectedQuery().getSelect(), true);
+        List projectedSymbols = query.getProjectedQuery().getSelect().getProjectedSymbols();
         if (orderBy.isInPlanForm()) {
-            rewriteExpressions(orderBy, procCommand, metadata, context);
+            rewriteExpressions(orderBy);
         }
 
         OrderBy newOrderBy = new OrderBy();
@@ -865,7 +903,7 @@
                 continue;
             }
             
-            if (query instanceof Query && EvaluateExpressionVisitor.isFullyEvaluatable(expr, true)) {
+            if (query instanceof Query && EvaluatableVisitor.isFullyEvaluatable(expr, true)) {
                 continue;
             }
             newOrderBy.addVariable((SingleElementSymbol)querySymbol.clone(), orderBy.getOrderType(i).booleanValue());
@@ -884,11 +922,9 @@
      * target table.  This ensures that they will all be uniquely named.
      *  
      * @param query
-     * @param metadata
      * @throws QueryValidatorException
      */
-    private static Query rewriteSelectInto(Query query,
-                                          QueryMetadataInterface metadata, Command procCommand, CommandContext context) throws QueryValidatorException {
+    private Query rewriteSelectInto(Query query) throws QueryValidatorException {
         Into into = query.getInto();
         
         try {
@@ -904,7 +940,7 @@
             
             if (needsView) {
                 query.setInto(null);
-                query = createInlineViewQuery(into.getGroup(), query, metadata);
+                query = createInlineViewQuery(into.getGroup(), query);
                 query.setInto(into);
                 return query;
             }
@@ -919,8 +955,7 @@
         
     }
 
-    private static void correctProjectedTypes(List actualSymbolTypes,
-                                              Query query) throws QueryValidatorException {
+    private void correctProjectedTypes(List actualSymbolTypes, Query query) {
         
         List symbols = query.getSelect().getProjectedSymbols();
         
@@ -929,7 +964,7 @@
         query.getSelect().setSymbols(newSymbols);
     } 
     
-	private static SetQuery rewriteSetQuery(SetQuery setQuery, Command procCommand, QueryMetadataInterface metadata, CommandContext context)
+	private SetQuery rewriteSetQuery(SetQuery setQuery)
 				 throws QueryValidatorException {
         
         if (setQuery.getProjectedTypes() != null) {
@@ -942,13 +977,10 @@
             setQuery.setProjectedTypes(null);
         }
         
-        setQuery.setLeftQuery((QueryCommand)rewriteCommand(setQuery.getLeftQuery(), procCommand, metadata, context, true));
-        setQuery.setRightQuery((QueryCommand)rewriteCommand(setQuery.getRightQuery(), procCommand, metadata, context, true));
+        setQuery.setLeftQuery((QueryCommand)rewriteCommand(setQuery.getLeftQuery(), true));
+        setQuery.setRightQuery((QueryCommand)rewriteCommand(setQuery.getRightQuery(), true));
 
-        if (setQuery.getOrderBy() != null) {
-            makeSelectUnique(setQuery.getProjectedQuery().getSelect(), true);
-            rewriteOrderBy(setQuery, procCommand, metadata, context);
-        }
+        rewriteOrderBy(setQuery);
         
         if (setQuery.getLimit() != null) {
             setQuery.setLimit(rewriteLimitClause(setQuery.getLimit()));
@@ -957,38 +989,36 @@
         return setQuery;
     }
 
-	private static FromClause rewriteFromClause(Query parent, FromClause clause, Command procCommand, QueryMetadataInterface metadata, CommandContext context)
+	private FromClause rewriteFromClause(Query parent, FromClause clause)
 			 throws QueryValidatorException {
 		if(clause instanceof JoinPredicate) {
-			return rewriteJoinPredicate(parent, (JoinPredicate) clause, procCommand, metadata, context);
+			return rewriteJoinPredicate(parent, (JoinPredicate) clause);
         } else if (clause instanceof UnaryFromClause) {
-            rewriteUnaryFromClause(parent, (UnaryFromClause)clause, metadata, context);
+            rewriteUnaryFromClause((UnaryFromClause)clause);
         } else if (clause instanceof SubqueryFromClause) {
-            rewriteSubqueryContainer((SubqueryFromClause)clause, procCommand, context, metadata, true);
+            rewriteSubqueryContainer((SubqueryFromClause)clause, true);
         }
         return clause;
 	}
 
-    private static void rewriteUnaryFromClause(Query parent, UnaryFromClause ufc, QueryMetadataInterface metadata,
-                                               CommandContext context) throws QueryValidatorException {
+    private void rewriteUnaryFromClause(UnaryFromClause ufc) throws QueryValidatorException {
         Command nestedCommand = ufc.getExpandedCommand();
         
         if (nestedCommand == null) {
             return;
         }
             
-        ufc.setExpandedCommand(rewriteCommand(nestedCommand, null, metadata, context, true));
+        ufc.setExpandedCommand(rewriteCommand(nestedCommand, true));
     }
 
-	private static JoinPredicate rewriteJoinPredicate(Query parent, JoinPredicate predicate, Command procCommand,
-        QueryMetadataInterface metadata, CommandContext context)
+	private JoinPredicate rewriteJoinPredicate(Query parent, JoinPredicate predicate)
 			 throws QueryValidatorException {
 		List joinCrits = predicate.getJoinCriteria();
 		if(joinCrits != null && joinCrits.size() > 0) {
 			//rewrite join crits by rewriting a compound criteria
 			Criteria criteria = new CompoundCriteria(new ArrayList(joinCrits));
             joinCrits.clear();
-            criteria = rewriteCriteria(criteria, procCommand, context, metadata);
+            criteria = rewriteCriteria(criteria, false);
             if (criteria instanceof CompoundCriteria && ((CompoundCriteria)criteria).getOperator() == CompoundCriteria.AND) {
                 joinCrits.addAll(((CompoundCriteria)criteria).getCriteria());
             } else {
@@ -1007,8 +1037,8 @@
             predicate.setRightClause(leftClause);
         }
 
-        predicate.setLeftClause( rewriteFromClause(parent, predicate.getLeftClause(), procCommand, metadata, context ));
-        predicate.setRightClause( rewriteFromClause(parent, predicate.getRightClause(), procCommand, metadata, context ));
+        predicate.setLeftClause( rewriteFromClause(parent, predicate.getLeftClause() ));
+        predicate.setRightClause( rewriteFromClause(parent, predicate.getRightClause() ));
     
 		return predicate;
 	}
@@ -1021,49 +1051,48 @@
      * in the procedural language.
      * @return The re-written criteria
      */
-    public static Criteria rewriteCriteria(Criteria criteria, Command procCommand, CommandContext context, QueryMetadataInterface metadata) throws QueryValidatorException {
-       return rewriteCriteria(criteria, procCommand, context, false, metadata);
+    public static Criteria rewriteCriteria(Criteria criteria, CreateUpdateProcedureCommand procCommand, CommandContext context, QueryMetadataInterface metadata) throws QueryValidatorException {
+    	return new QueryRewriter(metadata, context, procCommand).rewriteCriteria(criteria, false);
     }
 
 	/**
 	 * Rewrite the criteria by evaluating some trivial cases.
 	 * @param criteria The criteria to rewrite
-	 * @param metadata
 	 * @param userCriteria The criteria on user's command, used in rewriting HasCriteria
 	 * in the procedural language.
 	 * @return The re-written criteria
 	 */
-    private static Criteria rewriteCriteria(Criteria criteria, Command procCommand, CommandContext context, boolean preserveUnknown, QueryMetadataInterface metadata) throws QueryValidatorException {
+    private Criteria rewriteCriteria(Criteria criteria, boolean preserveUnknown) throws QueryValidatorException {
 		if(criteria instanceof CompoundCriteria) {
-            return rewriteCriteria((CompoundCriteria)criteria, procCommand, context, true, preserveUnknown, metadata);
+            return rewriteCriteria((CompoundCriteria)criteria, true, preserveUnknown);
 		} else if(criteria instanceof NotCriteria) {
-			criteria = rewriteCriteria((NotCriteria)criteria, procCommand, context, metadata);
+			criteria = rewriteCriteria((NotCriteria)criteria);
 		} else if(criteria instanceof CompareCriteria) {
-            criteria = rewriteCriteria((CompareCriteria)criteria, procCommand, context, metadata);
+            criteria = rewriteCriteria((CompareCriteria)criteria);
         } else if(criteria instanceof SubqueryCompareCriteria) {
-            criteria = rewriteCriteria((SubqueryCompareCriteria)criteria, procCommand, context, metadata);
+            criteria = rewriteCriteria((SubqueryCompareCriteria)criteria);
 		} else if(criteria instanceof MatchCriteria) {
-            criteria = rewriteCriteria((MatchCriteria)criteria, procCommand, context, metadata);
+            criteria = rewriteCriteria((MatchCriteria)criteria);
 		} else if(criteria instanceof SetCriteria) {
-            criteria = rewriteCriteria((SetCriteria)criteria, procCommand, context, metadata);
+            criteria = rewriteCriteria((SetCriteria)criteria);
         } else if(criteria instanceof IsNullCriteria) {
-            criteria = rewriteCriteria((IsNullCriteria)criteria, procCommand, context, metadata);
+            criteria = rewriteCriteria((IsNullCriteria)criteria);
         } else if(criteria instanceof BetweenCriteria) {
-            criteria = rewriteCriteria((BetweenCriteria)criteria, procCommand, context, preserveUnknown, metadata);
+            criteria = rewriteCriteria((BetweenCriteria)criteria, preserveUnknown);
 		} else if(criteria instanceof HasCriteria) {
-            criteria = rewriteCriteria((HasCriteria)criteria, procCommand, context, metadata);
+            criteria = rewriteCriteria((HasCriteria)criteria);
 		} else if(criteria instanceof TranslateCriteria) {
-            criteria = rewriteCriteria((TranslateCriteria)criteria, procCommand, context, metadata);
+            criteria = rewriteCriteria((TranslateCriteria)criteria);
 		} else if (criteria instanceof ExistsCriteria) {
-		    rewriteSubqueryContainer((SubqueryContainer)criteria, procCommand, context, metadata, true);
+		    rewriteSubqueryContainer((SubqueryContainer)criteria, true);
 		} else if (criteria instanceof SubquerySetCriteria) {
 		    SubquerySetCriteria sub = (SubquerySetCriteria)criteria;
 		    if (isNull(sub.getExpression())) {
 		        return UNKNOWN_CRITERIA;
 		    }
-		    rewriteSubqueryContainer((SubqueryContainer)criteria, procCommand, context, metadata, true);
+		    rewriteSubqueryContainer((SubqueryContainer)criteria, true);
         } else if (criteria instanceof DependentSetCriteria) {
-            criteria = rewriteCriteria((AbstractSetCriteria)criteria, procCommand, context, metadata);
+            criteria = rewriteCriteria((AbstractSetCriteria)criteria);
         }
 
         return evaluateCriteria(criteria);
@@ -1077,7 +1106,7 @@
      */
     public static Criteria optimizeCriteria(CompoundCriteria criteria) {
         try {
-            return rewriteCriteria(criteria, null, null, false, false, null);
+            return new QueryRewriter(null, null, null).rewriteCriteria(criteria, false, false);
         } catch (QueryValidatorException err) {
             //shouldn't happen
             return criteria;
@@ -1087,7 +1116,7 @@
     /** May be simplified if this is an AND and a sub criteria is always
      * false or if this is an OR and a sub criteria is always true
      */
-    private static Criteria rewriteCriteria(CompoundCriteria criteria, Command procCommand, CommandContext context, boolean rewrite, boolean preserveUnknown, QueryMetadataInterface metadata) throws QueryValidatorException {
+    private Criteria rewriteCriteria(CompoundCriteria criteria, boolean rewrite, boolean preserveUnknown) throws QueryValidatorException {
         List crits = criteria.getCriteria();
         int operator = criteria.getOperator();
 
@@ -1097,10 +1126,10 @@
         while(critIter.hasNext()) {
             Criteria converted = (Criteria) critIter.next();
             if (rewrite) {
-                converted = rewriteCriteria(converted, procCommand, context, preserveUnknown, metadata);
+                converted = rewriteCriteria(converted, preserveUnknown);
                 converted = evaluateCriteria(converted);
             } else if (converted instanceof CompoundCriteria) {
-                converted = rewriteCriteria((CompoundCriteria)converted, null, null, false, preserveUnknown, metadata);
+                converted = rewriteCriteria((CompoundCriteria)converted, false, preserveUnknown);
             }
 
             //begin boolean optimizations
@@ -1151,8 +1180,8 @@
         }
 	}
     
-    private static Criteria evaluateCriteria(Criteria crit) throws QueryValidatorException {
-        if(EvaluateExpressionVisitor.isFullyEvaluatable(crit, true)) {
+    private Criteria evaluateCriteria(Criteria crit) throws QueryValidatorException {
+        if(EvaluatableVisitor.isFullyEvaluatable(crit, true)) {
             try {
             	Boolean eval = new Evaluator(Collections.emptyMap(), null, null).evaluateTVL(crit, Collections.emptyList());
                 
@@ -1177,8 +1206,8 @@
     }
     
 
-	private static Criteria rewriteCriteria(NotCriteria criteria, Command procCommand, CommandContext context, QueryMetadataInterface metadata) throws QueryValidatorException {
-        Criteria innerCrit = rewriteCriteria(criteria.getCriteria(), procCommand, context, true, metadata);
+	private Criteria rewriteCriteria(NotCriteria criteria) throws QueryValidatorException {
+        Criteria innerCrit = rewriteCriteria(criteria.getCriteria(), true);
         
         innerCrit = evaluateCriteria(innerCrit);
         if(innerCrit == TRUE_CRITERIA) {
@@ -1200,11 +1229,10 @@
     /**
      * Rewrites "a [NOT] BETWEEN b AND c" as "a &gt;= b AND a &lt;= c", or as "a &lt;= b OR a&gt;= c"
      * @param criteria
-     * @param procCommand
      * @return
      * @throws QueryValidatorException
      */
-    private static Criteria rewriteCriteria(BetweenCriteria criteria, Command procCommand, CommandContext context, boolean preserveUnknown, QueryMetadataInterface metadata) throws QueryValidatorException {
+    private Criteria rewriteCriteria(BetweenCriteria criteria, boolean preserveUnknown) throws QueryValidatorException {
         CompareCriteria lowerCriteria = new CompareCriteria(criteria.getExpression(),
                                                             criteria.isNegated() ? CompareCriteria.LT: CompareCriteria.GE,
                                                             criteria.getLowerExpression());
@@ -1215,14 +1243,14 @@
                                                             lowerCriteria,
                                                             upperCriteria);
 
-        return rewriteCriteria(newCriteria, procCommand, context, preserveUnknown, metadata);
+        return rewriteCriteria(newCriteria, preserveUnknown);
     }
 
-	private static Criteria rewriteCriteria(CompareCriteria criteria, Command procCommand, CommandContext context, QueryMetadataInterface metadata) throws QueryValidatorException {
-		Expression leftExpr = rewriteExpression(criteria.getLeftExpression(), procCommand, context, metadata);
-		Expression rightExpr = rewriteExpression(criteria.getRightExpression(), procCommand, context, metadata);
+	private Criteria rewriteCriteria(CompareCriteria criteria) throws QueryValidatorException {
+		Expression leftExpr = rewriteExpressionDirect(criteria.getLeftExpression());
+		Expression rightExpr = rewriteExpressionDirect(criteria.getRightExpression());
 
-        if(!EvaluateExpressionVisitor.willBecomeConstant(rightExpr) && EvaluateExpressionVisitor.willBecomeConstant(leftExpr)) {
+        if(!EvaluatableVisitor.willBecomeConstant(rightExpr) && EvaluatableVisitor.willBecomeConstant(leftExpr)) {
             // Swap in this particular case for connectors
             criteria.setLeftExpression(rightExpr);
             criteria.setRightExpression(leftExpr);
@@ -1240,7 +1268,7 @@
 			criteria.setRightExpression(rightExpr);
 		}
 
-        if(criteria.getLeftExpression() instanceof Function && EvaluateExpressionVisitor.willBecomeConstant(criteria.getRightExpression())) {
+        if(criteria.getLeftExpression() instanceof Function && EvaluatableVisitor.willBecomeConstant(criteria.getRightExpression())) {
             criteria = simplifyWithInverse(criteria);
         }
         
@@ -1263,9 +1291,9 @@
      * The thing of primary importance here is that the use of the 'ANY' predicate
      * quantifier is replaced with the canonical and equivalent 'SOME'
      */
-    private static Criteria rewriteCriteria(SubqueryCompareCriteria criteria, Command procCommand, CommandContext context, QueryMetadataInterface metadata) throws QueryValidatorException {
+    private Criteria rewriteCriteria(SubqueryCompareCriteria criteria) throws QueryValidatorException {
 
-        Expression leftExpr = rewriteExpression(criteria.getLeftExpression(), procCommand, context, metadata);
+        Expression leftExpr = rewriteExpressionDirect(criteria.getLeftExpression());
         
         if (isNull(leftExpr)) {
             return UNKNOWN_CRITERIA;
@@ -1277,12 +1305,12 @@
             criteria.setPredicateQuantifier(SubqueryCompareCriteria.SOME);
         }
         
-        rewriteSubqueryContainer(criteria, procCommand, context, metadata, true);
+        rewriteSubqueryContainer(criteria, true);
 
         return criteria;
     }
     
-    private static CompareCriteria simplifyWithInverse(CompareCriteria criteria) throws QueryValidatorException {
+    private CompareCriteria simplifyWithInverse(CompareCriteria criteria) throws QueryValidatorException {
         Expression leftExpr = criteria.getLeftExpression();
         
         Function leftFunction = (Function) leftExpr;
@@ -1300,7 +1328,7 @@
         return criteria;
     }
     
-    private static boolean isSimpleMathematicalFunction(Function function) {
+    private boolean isSimpleMathematicalFunction(Function function) {
         String funcName = function.getName();
         if(funcName.equals("+") || funcName.equals("-") || funcName.equals("*") || funcName.equals("/")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
             Expression[] args = function.getArgs();
@@ -1314,20 +1342,20 @@
     }
 
     // Constants used in simplifying mathematical criteria
-    private static Integer INTEGER_ZERO = new Integer(0);
-    private static Double DOUBLE_ZERO = new Double(0);
-    private static Float FLOAT_ZERO = new Float(0);
-    private static Long LONG_ZERO = new Long(0);
-    private static BigInteger BIG_INTEGER_ZERO = new BigInteger("0"); //$NON-NLS-1$
-    private static BigDecimal BIG_DECIMAL_ZERO = new BigDecimal("0"); //$NON-NLS-1$
-    private static Short SHORT_ZERO = new Short((short)0);
-    private static Byte BYTE_ZERO = new Byte((byte)0);
+    private Integer INTEGER_ZERO = new Integer(0);
+    private Double DOUBLE_ZERO = new Double(0);
+    private Float FLOAT_ZERO = new Float(0);
+    private Long LONG_ZERO = new Long(0);
+    private BigInteger BIG_INTEGER_ZERO = new BigInteger("0"); //$NON-NLS-1$
+    private BigDecimal BIG_DECIMAL_ZERO = new BigDecimal("0"); //$NON-NLS-1$
+    private Short SHORT_ZERO = new Short((short)0);
+    private Byte BYTE_ZERO = new Byte((byte)0);
 
     /**
      * @param criteria
      * @return CompareCriteria
      */
-    private static CompareCriteria simplifyMathematicalCriteria(CompareCriteria criteria)
+    private CompareCriteria simplifyMathematicalCriteria(CompareCriteria criteria)
     throws QueryValidatorException {
 
         Expression leftExpr = criteria.getLeftExpression();
@@ -1468,7 +1496,7 @@
      * @throws QueryValidatorException
      * @since 4.2
      */
-    private static CompareCriteria simplifyConvertFunction(CompareCriteria crit) throws QueryValidatorException {
+    private CompareCriteria simplifyConvertFunction(CompareCriteria crit) throws QueryValidatorException {
         Function leftFunction = (Function) crit.getLeftExpression();
         Constant rightConstant = (Constant) crit.getRightExpression();
         Expression leftExpr = leftFunction.getArgs()[0];
@@ -1529,7 +1557,7 @@
      * @throws QueryValidatorException
      * @since 4.2
      */
-    private static Criteria simplifyConvertFunction(SetCriteria crit, Command procCommand, CommandContext context, QueryMetadataInterface metadata) throws QueryValidatorException {
+    private Criteria simplifyConvertFunction(SetCriteria crit) throws QueryValidatorException {
         Function leftFunction = (Function) crit.getExpression();
         Expression leftExpr = leftFunction.getArgs()[0];
         String leftExprTypeName = DataTypeManager.getDataTypeName(leftExpr.getType());
@@ -1567,14 +1595,14 @@
         	if (!removedSome) {
         		return crit; //just return as is
         	}
-        	return rewriteCriteria(crit, procCommand, context, metadata);
+        	return rewriteCriteria(crit);
         }
         crit.setExpression(leftExpr);
         crit.setValues(newValues);
-        return rewriteCriteria(crit, procCommand, context, metadata);
+        return rewriteCriteria(crit);
     }
         
-    private static CompareCriteria simplifyParseFormatFunction(CompareCriteria crit) throws QueryValidatorException {
+    private CompareCriteria simplifyParseFormatFunction(CompareCriteria crit) throws QueryValidatorException {
         Function leftFunction = (Function) crit.getLeftExpression();
         String funcName = leftFunction.getName().toLowerCase();
         String inverseFunction = null;
@@ -1701,7 +1729,7 @@
      * @param criteria Compare criteria
      * @return Simplified criteria, if possible
      */
-    private static Criteria simplifyTimestampMerge2(CompareCriteria criteria) {
+    private Criteria simplifyTimestampMerge2(CompareCriteria criteria) {
         if(criteria.getOperator() != CompareCriteria.EQ) {
             return criteria;
         }
@@ -1767,7 +1795,7 @@
     * @return Simplified criteria, if possible
     */
 
-   private static Criteria simplifyTimestampMerge(CompareCriteria criteria) {
+   private Criteria simplifyTimestampMerge(CompareCriteria criteria) {
        if(criteria.getOperator() != CompareCriteria.EQ) {
            return criteria;
        }
@@ -1843,9 +1871,9 @@
        }
     }
     
-    private static Criteria rewriteCriteria(MatchCriteria criteria, Command procCommand, CommandContext context, QueryMetadataInterface metadata) throws QueryValidatorException {
-		criteria.setLeftExpression( rewriteExpression(criteria.getLeftExpression(), procCommand, context, metadata));
-		criteria.setRightExpression( rewriteExpression(criteria.getRightExpression(), procCommand, context, metadata));
+    private Criteria rewriteCriteria(MatchCriteria criteria) throws QueryValidatorException {
+		criteria.setLeftExpression( rewriteExpressionDirect(criteria.getLeftExpression()));
+		criteria.setRightExpression( rewriteExpressionDirect(criteria.getRightExpression()));
         
         if (isNull(criteria.getLeftExpression()) || isNull(criteria.getRightExpression())) {
             return UNKNOWN_CRITERIA;
@@ -1878,7 +1906,7 @@
                     if (value.equals(MatchCriteria.WILDCARD_CHAR)) {
                     	return TRUE_CRITERIA;
                     }
-                	return rewriteCriteria(new CompareCriteria(criteria.getLeftExpression(), criteria.isNegated()?CompareCriteria.NE:CompareCriteria.EQ, criteria.getRightExpression()), procCommand, context, metadata);
+                	return rewriteCriteria(new CompareCriteria(criteria.getLeftExpression(), criteria.isNegated()?CompareCriteria.NE:CompareCriteria.EQ, criteria.getRightExpression()));
                 }
             }
         }
@@ -1886,8 +1914,8 @@
 		return criteria;
 	}
     
-    private static Criteria rewriteCriteria(AbstractSetCriteria criteria, Command procCommand, CommandContext context, QueryMetadataInterface metadata) throws QueryValidatorException {
-        criteria.setExpression(rewriteExpression(criteria.getExpression(), procCommand, context, metadata));
+    private Criteria rewriteCriteria(AbstractSetCriteria criteria) throws QueryValidatorException {
+        criteria.setExpression(rewriteExpressionDirect(criteria.getExpression()));
         
         if (isNull(criteria.getExpression())) {
             return UNKNOWN_CRITERIA;
@@ -1897,8 +1925,8 @@
     }
 
 
-	private static Criteria rewriteCriteria(SetCriteria criteria, Command procCommand, CommandContext context, QueryMetadataInterface metadata) throws QueryValidatorException {
-		criteria.setExpression(rewriteExpression(criteria.getExpression(), procCommand, context, metadata));
+	private Criteria rewriteCriteria(SetCriteria criteria) throws QueryValidatorException {
+		criteria.setExpression(rewriteExpressionDirect(criteria.getExpression()));
         
         if (isNull(criteria.getExpression())) {
             return UNKNOWN_CRITERIA;
@@ -1909,7 +1937,7 @@
         LinkedHashSet newVals = new LinkedHashSet(vals.size());
         Iterator valIter = vals.iterator();
         while(valIter.hasNext()) {
-            Expression value = rewriteExpression( (Expression) valIter.next(), procCommand, context, metadata);
+            Expression value = rewriteExpressionDirect( (Expression) valIter.next());
             if (isNull(value)) {
                 continue;
             }
@@ -1920,7 +1948,7 @@
         
         if (newVals.size() == 1) {
             Expression value = (Expression)newVals.iterator().next();
-            return rewriteCriteria(new CompareCriteria(criteria.getExpression(), criteria.isNegated()?CompareCriteria.NE:CompareCriteria.EQ, value), procCommand, context, metadata);
+            return rewriteCriteria(new CompareCriteria(criteria.getExpression(), criteria.isNegated()?CompareCriteria.NE:CompareCriteria.EQ, value));
         } else if (newVals.size() == 0) {
             return FALSE_CRITERIA;
         }
@@ -1929,40 +1957,94 @@
             
             Function leftFunction = (Function)criteria.getExpression();
             if(FunctionLibrary.isConvert(leftFunction)) {
-                return simplifyConvertFunction(criteria, procCommand, context, metadata);        
+                return simplifyConvertFunction(criteria);        
             }
         }
 
 		return criteria;
 	}
 
-	private static Criteria rewriteCriteria(IsNullCriteria criteria, Command procCommand, CommandContext context, QueryMetadataInterface metadata) throws QueryValidatorException {
-		criteria.setExpression(rewriteExpression(criteria.getExpression(), procCommand, context, metadata));
+	private Criteria rewriteCriteria(IsNullCriteria criteria) throws QueryValidatorException {
+		criteria.setExpression(rewriteExpressionDirect(criteria.getExpression()));
 		return criteria;
 	}
+	
+	public static Expression rewriteExpression(Expression expression, CreateUpdateProcedureCommand procCommand, CommandContext context, QueryMetadataInterface metadata) throws QueryValidatorException {
+		return new QueryRewriter(metadata, context, procCommand).rewriteExpressionDirect(expression);
+	}
 
-    public static Expression rewriteExpression(Expression expression, Command procCommand, CommandContext context, QueryMetadataInterface metadata) throws QueryValidatorException {
-		if(expression instanceof Function) {
-			return rewriteFunction((Function) expression, procCommand, context, metadata);
+    private Expression rewriteExpressionDirect(Expression expression) throws QueryValidatorException {
+    	if (expression instanceof Constant) {
+    		return expression;
+    	}
+    	if (expression instanceof ElementSymbol) {
+    		ElementSymbol es = (ElementSymbol)expression;
+    		Class<?> type  = es.getType();
+            if (dataMgr == null && es.isExternalReference()) {
+                String grpName = es.getGroupSymbol().getCanonicalName();
+                
+                if (variables == null) {
+                	return new Reference(es);
+                }
+                
+                Expression value = (Expression)variables.get(es.getCanonicalName());
+
+                if (value == null) {
+	                if (grpName.equals(ProcedureReservedWords.INPUT)) {
+	                	return new Constant(null, es.getType());
+	                } 
+	                if (grpName.equals(ProcedureReservedWords.CHANGING)) {
+	                    Assertion.failed("Changing value should not be null"); //$NON-NLS-1$
+	                } 
+                } else if (value instanceof Constant) {
+                	if (value.getType() == type) {
+                		return value;
+                	}
+                	try {
+						return new Constant(FunctionMethods.convert(((Constant)value).getValue(), DataTypeManager.getDataTypeName(type)), es.getType());
+					} catch (FunctionExecutionException e) {
+						throw new QueryValidatorException(e, e.getMessage());
+					}
+                }
+                return new Reference(es);
+            }
+            return expression;
+    	}
+    	if(expression instanceof Function) {
+    		expression = rewriteFunction((Function) expression);
 		} else if (expression instanceof CaseExpression) {
-            return rewriteCaseExpression((CaseExpression)expression, procCommand, context, metadata);
+			expression = rewriteCaseExpression((CaseExpression)expression);
         } else if (expression instanceof SearchedCaseExpression) {
-            return rewriteCaseExpression((SearchedCaseExpression)expression, procCommand, context, metadata);
+        	expression = rewriteCaseExpression((SearchedCaseExpression)expression);
         } else if (expression instanceof ScalarSubquery) {
-            rewriteSubqueryContainer((ScalarSubquery)expression, procCommand, context, metadata, true);
+            rewriteSubqueryContainer((ScalarSubquery)expression, true);
             return expression;
-        } else if (expression instanceof ExpressionSymbol && !(expression instanceof AggregateSymbol)) {
-            return rewriteExpression(((ExpressionSymbol)expression).getExpression(), procCommand, context, metadata);
-        } else if(expression instanceof AggregateSymbol){
-        	return rewriteExpression((AggregateSymbol)expression);
+        } else if (expression instanceof ExpressionSymbol) {
+        	if (expression instanceof AggregateSymbol) {
+        		expression = rewriteExpression((AggregateSymbol)expression);	
+        	} else {
+            	expression = rewriteExpressionDirect(((ExpressionSymbol)expression).getExpression());
+        	}
+        } 
+    	if (dataMgr == null || (!(expression instanceof Reference) && !EvaluatableVisitor.isEvaluatable(expression, EvaluationLevel.PROCESSING))) {
+    		return expression;
+    	}
+		Object value;
+        try {
+            value = new Evaluator(Collections.emptyMap(), dataMgr, context).evaluate(expression, Collections.emptyList());
+        } catch (MetaMatrixException err) {
+            throw new MetaMatrixRuntimeException(err);
         }
-        return expression;
+        if (value instanceof Constant) {
+        	return (Constant)value; //multi valued substitution
+        }
+		return new Constant(value, expression.getType());
 	}
-
-    private static Expression rewriteExpression(AggregateSymbol expression) {
+    
+    private Expression rewriteExpression(AggregateSymbol expression) {
     	if (!expression.getAggregateFunction().equals(ReservedWords.COUNT)
 				&& !expression.getAggregateFunction().equals(ReservedWords.SUM)
-				&& EvaluateExpressionVisitor.willBecomeConstant(expression.getExpression())) {
+				&& EvaluatableVisitor.willBecomeConstant(expression.getExpression())) {
 			try {
 				return new ExpressionSymbol(expression.getName(), ResolverUtil
 						.convertExpression(expression.getExpression(),DataTypeManager.getDataTypeName(expression.getType())));
@@ -1974,7 +2056,7 @@
 		return expression;
 	}
 
-	private static Expression rewriteFunction(Function function, Command procCommand, CommandContext context, QueryMetadataInterface metadata) throws QueryValidatorException {
+	private Expression rewriteFunction(Function function) throws QueryValidatorException {
 		//rewrite alias functions
 		String actualName =ALIASED_FUNCTIONS.get(function.getName().toLowerCase());
 		if (actualName != null) {
@@ -1990,7 +2072,7 @@
 	        	FunctionLibraryManager.getFunctionLibrary().findFunction(SourceSystemFunctions.REPEAT, new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.INTEGER});
 			result.setFunctionDescriptor(descriptor);
 			result.setType(DataTypeManager.DefaultDataClasses.STRING);
-			return rewriteFunction(result, procCommand, context, metadata);
+			return rewriteFunction(result);
 		}
 		
 		//from_unixtime(a) => timestampadd(SQL_TSI_SECOND, a, new Timestamp(0)) 
@@ -2002,7 +2084,7 @@
 	        	FunctionLibraryManager.getFunctionLibrary().findFunction(FunctionLibrary.TIMESTAMPADD, new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.INTEGER, DataTypeManager.DefaultDataClasses.TIMESTAMP });
 			result.setFunctionDescriptor(descriptor);
 			result.setType(DataTypeManager.DefaultDataClasses.TIMESTAMP);
-			return rewriteFunction(result, procCommand, context, metadata);
+			return rewriteFunction(result);
 		}
 		
 		//rewrite nullif(a, b) => case when (a = b) then null else a
@@ -2013,7 +2095,7 @@
 			SearchedCaseExpression caseExpr = new SearchedCaseExpression(when, then);
 			caseExpr.setElseExpression(function.getArg(0));
 			caseExpr.setType(function.getType());
-			return rewriteExpression(caseExpr, procCommand, context, metadata);
+			return rewriteExpressionDirect(caseExpr);
 		}
 		
 		if (function.getName().equalsIgnoreCase(FunctionLibrary.COALESCE)) {
@@ -2026,7 +2108,7 @@
 		        	FunctionLibraryManager.getFunctionLibrary().findFunction(SourceSystemFunctions.IFNULL, new Class[] { function.getType(), function.getType()  });
 				result.setFunctionDescriptor(descriptor);
 				result.setType(function.getType());
-				return rewriteFunction(result, procCommand, context, metadata);
+				return rewriteFunction(result);
 			}
 		}
 		
@@ -2056,7 +2138,7 @@
 			SearchedCaseExpression caseExpr = new SearchedCaseExpression(when, then);
 			caseExpr.setElseExpression(concat);
 			caseExpr.setType(DataTypeManager.DefaultDataClasses.STRING);
-			return rewriteExpression(caseExpr, procCommand, context, metadata);
+			return rewriteExpressionDirect(caseExpr);
 		}
 		
 		Expression[] args = function.getArgs();
@@ -2064,7 +2146,7 @@
 		        
         // Rewrite args
 		for(int i=0; i<args.length; i++) {
-			newArgs[i] = rewriteExpression(args[i], procCommand, context, metadata);
+			newArgs[i] = rewriteExpressionDirect(args[i]);
             if (isNull(newArgs[i]) && !function.getFunctionDescriptor().isNullDependent()) {
                 return new Constant(null, function.getType());
             }
@@ -2090,7 +2172,7 @@
             return convertDecodeFunction(function);
         }
         
-        if(EvaluateExpressionVisitor.isFullyEvaluatable(function, true)) {
+        if(EvaluatableVisitor.isFullyEvaluatable(function, true)) {
             try {
                 Object result = new Evaluator(Collections.emptyMap(), null, context).evaluate(function, Collections.emptyList());
 				Constant constant = new Constant(result, function.getType());
@@ -2113,7 +2195,7 @@
         return function;
 	}
 
-	private static Expression convertDecodeFunction(Function function){
+	private Expression convertDecodeFunction(Function function){
     	Expression exprs[] = function.getArgs();
     	String decodeString = (String)((Constant)exprs[1]).getValue();
     	String decodeDelimiter = ","; //$NON-NLS-1$
@@ -2153,7 +2235,7 @@
         return newCaseExpr;
 	}
 	
-    public static String convertString(String string) {
+    private static String convertString(String string) {
         /*
          * if there are no characters in the compare string we designate that as
          * an indication of null.  ie if the decode string looks like this:
@@ -2198,7 +2280,7 @@
         return string;
     }
 	
-    private static Expression rewriteCaseExpression(CaseExpression expr, Command procCommand, CommandContext context, QueryMetadataInterface metadata)
+    private Expression rewriteCaseExpression(CaseExpression expr)
         throws QueryValidatorException {
     	List<CompareCriteria> whens = new ArrayList<CompareCriteria>(expr.getWhenCount());
     	for (Expression expression: (List<Expression>)expr.getWhen()) {
@@ -2207,10 +2289,10 @@
     	SearchedCaseExpression sce = new SearchedCaseExpression(whens, expr.getThen());
     	sce.setElseExpression(expr.getElseExpression());
     	sce.setType(expr.getType());
-    	return rewriteCaseExpression(sce, procCommand, context, metadata);
+    	return rewriteCaseExpression(sce);
     }
 
-    private static Expression rewriteCaseExpression(SearchedCaseExpression expr, Command procCommand, CommandContext context, QueryMetadataInterface metadata)
+    private Expression rewriteCaseExpression(SearchedCaseExpression expr)
         throws QueryValidatorException {
         int whenCount = expr.getWhenCount();
         ArrayList whens = new ArrayList(whenCount);
@@ -2219,27 +2301,20 @@
         for (int i = 0; i < whenCount; i++) {
             
             // Check the when to see if this CASE can be rewritten due to an always true/false when
-            Criteria rewrittenWhen = rewriteCriteria(expr.getWhenCriteria(i), procCommand, context, metadata);
-            if(EvaluateExpressionVisitor.isFullyEvaluatable(rewrittenWhen, true)) {
-                try {
-                	boolean eval = Evaluator.evaluate(rewrittenWhen);
-                    if(eval) {
-                        // WHEN is always true, so just return the THEN
-                        return rewriteExpression(expr.getThenExpression(i), procCommand, context, metadata);
-                    } 
-
-                    // WHEN is never true, so just skip this WHEN/THEN pair in the lists
-                    continue;
-                } catch(Exception e) {
-                    // ignore and don't simplify - shouldn't happen
-                }
-            } 
+            Criteria rewrittenWhen = rewriteCriteria(expr.getWhenCriteria(i), false);
+            if(rewrittenWhen == TRUE_CRITERIA) {
+                // WHEN is always true, so just return the THEN
+                return rewriteExpressionDirect(expr.getThenExpression(i));
+            }
+            if (rewrittenWhen == FALSE_CRITERIA || rewrittenWhen == UNKNOWN_CRITERIA) {
+            	continue;
+            }
             
             whens.add(rewrittenWhen);
-            thens.add(rewriteExpression(expr.getThenExpression(i), procCommand, context, metadata));
+            thens.add(rewriteExpressionDirect(expr.getThenExpression(i)));
         }
 
-        expr.setElseExpression(rewriteExpression(expr.getElseExpression(), procCommand, context, metadata));
+        expr.setElseExpression(rewriteExpressionDirect(expr.getElseExpression()));
         
         Expression elseExpr = expr.getElseExpression();
         if(whens.size() == 0) {
@@ -2278,27 +2353,26 @@
         return expr;
     }
         
-    private static Command rewriteExec(StoredProcedure storedProcedure, Command procCommand, QueryMetadataInterface metadata, CommandContext context) throws QueryValidatorException {
+    private Command rewriteExec(StoredProcedure storedProcedure) throws QueryValidatorException {
         //After this method, no longer need to display named parameters
         storedProcedure.setDisplayNamedParameters(false);
         
         for (Iterator i = storedProcedure.getInputParameters().iterator(); i.hasNext();) {
             SPParameter param = (SPParameter)i.next();
-            param.setExpression(rewriteExpression(param.getExpression(), procCommand, context, metadata));
+            param.setExpression(rewriteExpressionDirect(param.getExpression()));
         }
-        
         return storedProcedure;
     }
 
-	private static Command rewriteInsert(Insert insert, Command procCommand, CommandContext context, QueryMetadataInterface metadata) throws QueryValidatorException {
+	private Command rewriteInsert(Insert insert) throws QueryValidatorException {
         
         if ( insert.getQueryExpression() != null ) {
             Query query = null;
             QueryCommand nested = insert.getQueryExpression();
-            QueryRewriter.rewrite(nested, procCommand, metadata, context);
+            rewriteCommand(nested, true);
             if(nested instanceof SetQuery) {
                 try {
-                    query = createInlineViewQuery(insert.getGroup(), nested, metadata);
+                    query = createInlineViewQuery(insert.getGroup(), nested);
                 } catch (QueryMetadataException err) {
                     throw new QueryValidatorException(err, err.getMessage());
                 } catch (QueryResolverException err) {
@@ -2320,7 +2394,7 @@
         Iterator expIter = expressions.iterator();
         while(expIter.hasNext()) {
             Expression exp = (Expression) expIter.next();
-            evalExpressions.add( rewriteExpression( exp, procCommand, context, metadata ));
+            evalExpressions.add( rewriteExpressionDirect( exp ));
         }
 
         insert.setValues(evalExpressions);        
@@ -2331,14 +2405,13 @@
 	/**
 	 * Creates an inline view around the target query.
 	 */
-    private static Query createInlineViewQuery(GroupSymbol group,
-                                          QueryCommand nested,
-                                          QueryMetadataInterface metadata) throws QueryMetadataException, QueryResolverException, MetaMatrixComponentException {
+    private Query createInlineViewQuery(GroupSymbol group,
+                                          QueryCommand nested) throws QueryMetadataException, QueryResolverException, MetaMatrixComponentException {
         List actualSymbols = ResolverUtil.resolveElementsInGroup(group, metadata);
         return createInlineViewQuery(group, nested, metadata, actualSymbols);
     }
 
-    public static Query createInlineViewQuery(GroupSymbol group,
+    private static Query createInlineViewQuery(GroupSymbol group,
                                                QueryCommand nested,
                                                QueryMetadataInterface metadata,
                                                List actualSymbols) throws QueryMetadataException,
@@ -2427,44 +2500,82 @@
         }
     }
 
-	private static Update rewriteUpdate(Update update, Command procCommand, CommandContext context, QueryMetadataInterface metadata) throws QueryValidatorException {
-        // Evaluate any function on the right side of set clauses
+	private Update rewriteUpdate(Update update) throws QueryValidatorException {
+		if (commandType == Command.TYPE_UPDATE && variables != null) {
+	        SetClauseList newChangeList = new SetClauseList();
+	        for (SetClause entry : update.getChangeList().getClauses()) {
+	            Expression rightExpr = entry.getValue();
+	            boolean retainChange = checkInputVariables(rightExpr);
+	            if (retainChange) {
+	                newChangeList.addClause(entry.getSymbol(), entry.getValue());
+	            }
+	        }
+	        update.setChangeList(newChangeList);
+        }
+
+		// Evaluate any function on the right side of set clauses
         for (SetClause entry : update.getChangeList().getClauses()) {
-        	entry.setValue(rewriteExpression(entry.getValue(), procCommand, context, metadata));
+        	entry.setValue(rewriteExpressionDirect(entry.getValue()));
         }
 
 		// Rewrite criteria
 		Criteria crit = update.getCriteria();
 		if(crit != null) {
-			update.setCriteria(rewriteCriteria(crit, procCommand, context, metadata));
+			update.setCriteria(rewriteCriteria(crit, false));
 		}
 
 		return update;
 	}
+	
+    /**
+     * Checks variables in an expression, if the variables are INPUT variables and if
+     * none of them are changing, then this method returns a false, if all of them
+     * are changing this returns a true, if some are changing and some are not, then
+     * that is an invalid case and the method adds to the list of invalid variables.
+     * @throws QueryValidatorException 
+     */
+    private boolean checkInputVariables(Expression expr) throws QueryValidatorException {
+        Boolean result = null;
+        for (ElementSymbol var : ElementCollectorVisitor.getElements(expr, false)) {
+            String grpName = var.getGroupSymbol().getName();
+            if (var.isExternalReference() && grpName.equals(ProcedureReservedWords.INPUT)) {
+                
+                String changingKey = ProcedureReservedWords.CHANGING + ElementSymbol.SEPARATOR + var.getShortCanonicalName();
+                
+                Boolean changingValue = (Boolean)((Constant)variables.get(changingKey)).getValue();
+                
+                if (result == null) {
+                    result = changingValue;
+                } else if (!result.equals(changingValue)) {
+                	throw new QueryValidatorException(QueryExecPlugin.Util.getString("VariableSubstitutionVisitor.Input_vars_should_have_same_changing_state", expr)); //$NON-NLS-1$
+                }
+            }
+        }
+        
+        if (result != null) {
+            return result.booleanValue();
+        }
+        
+        return true;
+    }
 
-	private static Delete rewriteDelete(Delete delete, Command procCommand, CommandContext context, QueryMetadataInterface metadata) throws QueryValidatorException {
+	private Delete rewriteDelete(Delete delete) throws QueryValidatorException {
 		// Rewrite criteria
 		Criteria crit = delete.getCriteria();
 		if(crit != null) {
-			delete.setCriteria(rewriteCriteria(crit, procCommand, context, metadata));
+			delete.setCriteria(rewriteCriteria(crit, false));
 		}
 
 		return delete;
 	}
     
-    private static Limit rewriteLimitClause(Limit limit) {
-        try {
-            if (limit.getOffset() != null && EvaluateExpressionVisitor.isFullyEvaluatable(limit.getOffset(), true)) {
-                limit.setOffset(new Constant(Evaluator.evaluate(limit.getOffset())));
-            }
-            if (limit.getRowLimit() != null && EvaluateExpressionVisitor.isFullyEvaluatable(limit.getRowLimit(), true)) {
-                limit.setRowLimit(new Constant(Evaluator.evaluate(limit.getRowLimit())));
-            }
-        } catch (ExpressionEvaluationException e) {
-            throw new MetaMatrixRuntimeException(e);
-        } catch (MetaMatrixComponentException e) {
-            throw new MetaMatrixRuntimeException(e);
+    private Limit rewriteLimitClause(Limit limit) throws QueryValidatorException {
+        if (limit.getOffset() != null) {
+            limit.setOffset(rewriteExpressionDirect(limit.getOffset()));
         }
+        if (limit.getRowLimit() != null) {
+            limit.setRowLimit(rewriteExpressionDirect(limit.getRowLimit()));
+        }
         return limit;
     }
 }
\ No newline at end of file

Deleted: trunk/engine/src/main/java/com/metamatrix/query/rewriter/VariableSubstitutionVisitor.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/rewriter/VariableSubstitutionVisitor.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/main/java/com/metamatrix/query/rewriter/VariableSubstitutionVisitor.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -1,219 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.query.rewriter;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.Map;
-
-import com.metamatrix.api.exception.query.QueryResolverException;
-import com.metamatrix.api.exception.query.QueryValidatorException;
-import com.metamatrix.common.types.DataTypeManager;
-import com.metamatrix.core.util.Assertion;
-import com.metamatrix.query.execution.QueryExecPlugin;
-import com.metamatrix.query.resolver.util.ResolverUtil;
-import com.metamatrix.query.sql.LanguageObject;
-import com.metamatrix.query.sql.ProcedureReservedWords;
-import com.metamatrix.query.sql.lang.Command;
-import com.metamatrix.query.sql.lang.Delete;
-import com.metamatrix.query.sql.lang.DynamicCommand;
-import com.metamatrix.query.sql.lang.Insert;
-import com.metamatrix.query.sql.lang.Query;
-import com.metamatrix.query.sql.lang.SetClause;
-import com.metamatrix.query.sql.lang.SetClauseList;
-import com.metamatrix.query.sql.lang.SetQuery;
-import com.metamatrix.query.sql.lang.Update;
-import com.metamatrix.query.sql.lang.XQuery;
-import com.metamatrix.query.sql.navigator.DeepPreOrderNavigator;
-import com.metamatrix.query.sql.symbol.Constant;
-import com.metamatrix.query.sql.symbol.ElementSymbol;
-import com.metamatrix.query.sql.symbol.Expression;
-import com.metamatrix.query.sql.visitor.ExpressionMappingVisitor;
-import com.metamatrix.query.sql.visitor.ReferenceCollectorVisitor;
-import com.metamatrix.query.sql.visitor.VariableCollectorVisitor;
-
-/**
- * <p>This visitor class will traverse a language object tree, it finds variables in the language
- * object and replaces the variable with a <code>Reference</code> obj.,/p>
- *
- * <p>This will also evaluate special variables INPUT and CHANGING by looking at the user's query,
- *  it finds these special variables it replaces the variable with a value(in case of INPUT) of the
- *  corresponding variable in set the user command or replace it with a constant of boolean value
- *  (in case CHANGING) indicating if the variable value is set on the user's command.</p>
- *
- * <p>The easiest way to use this visitor is to call the static method which creates the
- * the visitor by passing it the Language Object and the variable context to be looked up.
- * The public visit() methods should NOT be called directly.</p>
- */
-public class VariableSubstitutionVisitor extends ExpressionMappingVisitor {
-
-    // INPUT variables for which problems were identified during
-    // substitution
-    private Collection invalidInput;
-    private int commandType;
-    
-    private QueryResolverException conversionException = null;
-    
-	/**
-	 * Construct a new visitor with the list of references.
-	 * @param references A list of references on to be collected
-	 */
-	public VariableSubstitutionVisitor(Map variableValues, int commandType) {
-        super(variableValues);
-        this.commandType = commandType;
-	}
-
-    public void visit(XQuery obj) {
-        obj.getCompiledXQuery().setParameters(getVariableValues());
-    }
-    
-    public void visit(Update obj) {
-        if (commandType != Command.TYPE_UPDATE) {
-            return;
-        }
-
-        SetClauseList newChangeList = new SetClauseList();
-        for (SetClause entry : obj.getChangeList().getClauses()) {
-            Expression rightExpr = entry.getValue();
-            boolean retainChange = checkInputVariables(rightExpr);
-            if (retainChange) {
-                newChangeList.addClause(entry.getSymbol(), entry.getValue());
-            }
-        }
-        obj.setChangeList(newChangeList);
-    }
-    
-    /**
-     * Checks variables in an expression, if the variables are INPUT variables and if
-     * none of them are changing, then this method returns a false, if all of them
-     * are changing this returns a true, if some are changing and some are not, then
-     * that is an invalid case and the method adds to the list of invalid variables.
-     */
-    private boolean checkInputVariables(Expression expr) {
-        Iterator varIter =
-            VariableCollectorVisitor.getVariables(expr, false).iterator();
-        
-        Boolean result = null;
-        
-        while (varIter.hasNext()) {
-            ElementSymbol var = (ElementSymbol) varIter.next();
-            String grpName = var.getGroupSymbol().getName();
-            if (grpName.equals(ProcedureReservedWords.INPUT)) {
-                
-                String changingKey = ProcedureReservedWords.CHANGING + ElementSymbol.SEPARATOR + var.getShortCanonicalName();
-                
-                Boolean changingValue = (Boolean)((Constant)getVariableValues().get(changingKey)).getValue();
-                
-                if (result == null) {
-                    result = changingValue;
-                } else if (!result.equals(changingValue)) {
-                    if (invalidInput == null) {
-                        invalidInput = new ArrayList();
-                    }
-                    invalidInput.add(expr);
-                }
-            }
-        }
-        
-        if (result != null) {
-            return result.booleanValue();
-        }
-        
-        return true;
-    }
-
-    /**
-     * Common pattern used by visit methods in this Visitor
-     * @param expr
-     * @return
-     */
-    public Expression replaceExpression(Expression expr) {
-        if (expr == null) {
-            return null;
-        }
-        
-        Class type = expr.getType();
-        
-        if (expr instanceof ElementSymbol) {
-            ElementSymbol symbol = (ElementSymbol)expr;
-            if (symbol.isExternalReference()) {
-                String grpName = symbol.getGroupSymbol().getCanonicalName();
-                
-                Expression value = (Expression)this.getVariableValues().get(symbol.getCanonicalName());
-
-                if (value != null) {
-                    //don't forward references
-                    if (!ReferenceCollectorVisitor.getReferences(value).isEmpty()) {
-                        return expr;
-                    }
-                    expr = value;
-                } else if (grpName.equals(ProcedureReservedWords.INPUT)) {
-                    expr =  new Constant(null, symbol.getType());
-                } else if (grpName.equals(ProcedureReservedWords.CHANGING)) {
-                    Assertion.failed("Changing value should not be null"); //$NON-NLS-1$
-                } 
-            }
-        }
-        
-        try {
-            expr = ResolverUtil.convertExpression(expr, DataTypeManager.getDataTypeName(type));
-        } catch (QueryResolverException err) {
-            this.conversionException = err;
-            setAbort(true);
-        }
-        
-        return expr;
-    }
-    
-	/**
-	 * <p>Helper to visit the language object specified and replace any variables a Reference obj,
-	 * and collect the references returned.</p>
-	 * @param obj The Language object that is to be visited
-     * @param commandType The command type of the user command invoking this procedure
-     * @param forwardReferences If references in the variable values should be substituted into expressions in this command
-	 * @return true if a reference was not forwarded
-	 * @throws QueryValidatorException 
-	 * @throws QueryValidatorException
-	 */
-	public static final void substituteVariables(
-		LanguageObject obj,
-		Map variableValues,
-        int commandType) throws QueryValidatorException {
-		VariableSubstitutionVisitor visitor =
-			new VariableSubstitutionVisitor(variableValues, commandType);
-        if (obj == null) {
-            return;
-        }
-        
-		DeepPreOrderNavigator.doVisit(obj, visitor);
-        
-        if (visitor.invalidInput != null) {
-            throw new QueryValidatorException(QueryExecPlugin.Util.getString("VariableSubstitutionVisitor.Input_vars_should_have_same_changing_state", visitor.invalidInput)); //$NON-NLS-1$
-        }
-        if (visitor.conversionException != null) {
-            throw new QueryValidatorException(visitor.conversionException, visitor.conversionException.getMessage());
-        }
-    }
-    
-}

Modified: trunk/engine/src/main/java/com/metamatrix/query/sql/lang/XQuery.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/sql/lang/XQuery.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/main/java/com/metamatrix/query/sql/lang/XQuery.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -41,6 +41,7 @@
     
     private String xQuery;
     private XQueryExpression compiledXQuery;
+    private Map variables;
     
     public XQuery(){
     }
@@ -50,6 +51,14 @@
         this.compiledXQuery = compiledXQuery;
     }
     
+    public void setVariables(Map variables) {
+		this.variables = variables;
+	}
+    
+    public Map getVariables() {
+		return variables;
+	}
+    
     public String getXQuery(){
         return xQuery;
     }
@@ -110,6 +119,7 @@
      */
     public Object clone() {
         XQuery copy = new XQuery(getXQuery(), this.compiledXQuery);
+        copy.variables = variables;
         copyMetadataState(copy);
         return copy;
     }

Deleted: trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/CorrelatedVariableSubstitutionVisitor.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/CorrelatedVariableSubstitutionVisitor.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/CorrelatedVariableSubstitutionVisitor.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -1,78 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.query.sql.visitor;
-
-import java.util.Collections;
-
-import com.metamatrix.query.sql.LanguageObject;
-import com.metamatrix.query.sql.navigator.PreOrderNavigator;
-import com.metamatrix.query.sql.symbol.ElementSymbol;
-import com.metamatrix.query.sql.symbol.Expression;
-import com.metamatrix.query.sql.symbol.Reference;
-
-/**
- * <p>This visitor class will traverse a language object tree, finds variables in the language
- * object and replaces the variable with a <code>Reference</code> obj.  This visitor is
- * needed for correlated subqueries.</p>
- * 
- * <p>The easiest way to use this visitor is to call the static method which creates the 
- * the visitor by passing it the Langiuage Object and the variable context to be looked up.
- * The public visit() methods should NOT be called directly.</p>
- */
-public class CorrelatedVariableSubstitutionVisitor extends ExpressionMappingVisitor {
-
-    public CorrelatedVariableSubstitutionVisitor() {
-        super(Collections.EMPTY_MAP);
-    }
-
-    /** 
-     * @see com.metamatrix.query.sql.visitor.ExpressionMappingVisitor#replaceExpression(com.metamatrix.query.sql.symbol.Expression)
-     */
-    public Expression replaceExpression(Expression expression) {
-        
-        if (expression instanceof ElementSymbol) {
-            ElementSymbol variable = (ElementSymbol)expression;
-
-            if (variable.isExternalReference()) {
-                return new Reference(variable);
-            }
-        } 
-
-        return expression;
-    }
-    
-    /**
-     * <p>Helper to visit the language object specified and replace any variables with a Reference obj, 
-     * and collect the references returned.</p>
-     * @param obj The Language object that is to be visited
-     * that the client (outer query) is interested in references to from the correlated subquery
-     * @param metadata QueryMetadataInterface
-     * @return a List of References collected
-     */
-    public static final void substituteVariables(LanguageObject obj) {
-
-        CorrelatedVariableSubstitutionVisitor visitor =
-            new CorrelatedVariableSubstitutionVisitor();
-        PreOrderNavigator.doVisit(obj, visitor);
-    }
-}

Modified: trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/EvaluatableVisitor.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/EvaluatableVisitor.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/EvaluatableVisitor.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -155,7 +155,22 @@
     	return levels.last().compareTo(targetLevel) <= 0;
     }
     
-    public static final boolean isEvaluatable(LanguageObject obj, EvaluationLevel target) {
+    /**
+	 *  Will return true if the expression can be deterministically evaluated at runtime, but it may not be
+	 *  evaluatable during planning
+	 */
+	public static final boolean willBecomeConstant(LanguageObject obj) {
+	    return willBecomeConstant(obj, false);
+	}
+
+	/**
+	 *  Should be called to check if the object can fully evaluated
+	 */
+	public static final boolean isFullyEvaluatable(LanguageObject obj, boolean duringPlanning) {
+	    return isEvaluatable(obj, duringPlanning?EvaluationLevel.PLANNING:EvaluationLevel.PROCESSING);
+	}
+
+	public static final boolean isEvaluatable(LanguageObject obj, EvaluationLevel target) {
         EvaluatableVisitor visitor = new EvaluatableVisitor();
         visitor.targetLevel = target;
         PreOrderNavigator.doVisit(obj, visitor);

Deleted: trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/EvaluateExpressionVisitor.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/EvaluateExpressionVisitor.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/EvaluateExpressionVisitor.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -1,137 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.query.sql.visitor;
-
-import java.util.Collections;
-
-import com.metamatrix.api.exception.MetaMatrixComponentException;
-import com.metamatrix.api.exception.MetaMatrixException;
-import com.metamatrix.api.exception.query.ExpressionEvaluationException;
-import com.metamatrix.core.MetaMatrixRuntimeException;
-import com.metamatrix.query.eval.Evaluator;
-import com.metamatrix.query.processor.ProcessorDataManager;
-import com.metamatrix.query.sql.LanguageObject;
-import com.metamatrix.query.sql.navigator.DeepPostOrderNavigator;
-import com.metamatrix.query.sql.navigator.PostOrderNavigator;
-import com.metamatrix.query.sql.symbol.Constant;
-import com.metamatrix.query.sql.symbol.Expression;
-import com.metamatrix.query.sql.symbol.Reference;
-import com.metamatrix.query.sql.symbol.ScalarSubquery;
-import com.metamatrix.query.sql.visitor.EvaluatableVisitor.EvaluationLevel;
-import com.metamatrix.query.util.CommandContext;
-
-/**
- * <p>This visitor simplifies Language Objects by evaluating and/or replacing 
- * Expressions within them.</p>
- * 
- * <p>The easiest way to use this visitor is to call the static methods which create 
- * the visitor and run it.
- * The public visit() methods should NOT be called directly.</p>
- */
-public class EvaluateExpressionVisitor extends ExpressionMappingVisitor {
-
-    private CommandContext context;
-    private ProcessorDataManager dataMgr;
-        
-    EvaluateExpressionVisitor() {
-        super(null);
-    }
-
-    public void setContext(CommandContext context) {
-        this.context = context;
-    }
-
-    /**
-     * Evaluate the expression.  This method takes into account whether the 
-     * Expression CAN be evaluated or not.  
-     * 
-     * This method also takes into account if the Expression is a 
-     * Reference.  The Reference may not be evaluatable (may not have data tuple and
-     * element map set on it), in which case this method may return the Reference itself
-     * or the Expression inside the Reference, depending on the instance variables of this
-     * visitor.
-     * @param expr
-     * @return
-     */
-    public Expression replaceExpression(Expression expr) {
-        //if the expression is a constant or is not evaluatable, just return
-        if (expr instanceof Constant || expr instanceof ScalarSubquery || (!(expr instanceof Reference) && !EvaluatableVisitor.isEvaluatable(expr, EvaluationLevel.PROCESSING))) {
-            return expr;
-        }
-
-		Object value;
-        try {
-            value = new Evaluator(Collections.emptyMap(), dataMgr, context).evaluate(expr, Collections.emptyList());
-        } catch (MetaMatrixException err) {
-            throw new MetaMatrixRuntimeException(err);
-        }
-        if (value instanceof Constant) {
-        	return (Constant)value; //multi valued substitution
-        }
-		return new Constant(value, expr.getType());
-    }
-    
-    /**
-     *  Will return true if the expression can be deterministically evaluated at runtime, but it may not be
-     *  evaluatable during planning
-     */
-    public static final boolean willBecomeConstant(LanguageObject obj) {
-        return EvaluatableVisitor.willBecomeConstant(obj, false);
-    }
-    
-    /**
-     *  Should be called to check if the object can fully evaluated
-     */
-    public static final boolean isFullyEvaluatable(LanguageObject obj, boolean duringPlanning) {
-        return EvaluatableVisitor.isEvaluatable(obj, duringPlanning?EvaluationLevel.PLANNING:EvaluationLevel.PROCESSING);
-    }
-        
-    public static final void replaceExpressions(LanguageObject obj, boolean deep, ProcessorDataManager dataMgr, CommandContext context)
-    throws ExpressionEvaluationException, MetaMatrixComponentException {
-        EvaluateExpressionVisitor visitor = new EvaluateExpressionVisitor();
-        visitor.setContext(context);
-        visitor.dataMgr = dataMgr;
-        
-        try {
-            if(deep) {
-                DeepPostOrderNavigator.doVisit(obj, visitor);
-            } else {
-                PostOrderNavigator.doVisit(obj, visitor);
-            }
-        } catch (MetaMatrixRuntimeException err) {
-            Throwable e = err.getChild();
-            
-            if (e == null) {
-                throw err;
-            }
-            
-            if(e instanceof ExpressionEvaluationException) {
-                throw (ExpressionEvaluationException) e;
-            } else if(e instanceof MetaMatrixComponentException) {
-                throw (MetaMatrixComponentException) e;                    
-            } else {
-                throw new MetaMatrixComponentException(e, e.getMessage());    
-            }
-        }
-    }
-}

Deleted: trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/VariableCollectorVisitor.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/VariableCollectorVisitor.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/VariableCollectorVisitor.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -1,114 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.query.sql.visitor;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-
-import com.metamatrix.query.QueryPlugin;
-import com.metamatrix.query.sql.LanguageObject;
-import com.metamatrix.query.sql.LanguageVisitor;
-import com.metamatrix.query.sql.navigator.PreOrderNavigator;
-import com.metamatrix.query.sql.symbol.ElementSymbol;
-import com.metamatrix.query.util.ErrorMessageKeys;
-
-/**
- * <p>This visitor class will traverse a language object tree and collect all variable
- *  symbol  references it finds.  It uses a collection to collect the elements in so
- * different collections will give you different collection properties - for instance,
- * using a Set will remove duplicates.</p>
- *
- * <p>The easiest way to use this visitor is to call the static methods which create
- * the visitor (and possibly the collection), run the visitor, and return the collection.
- * The public visit() methods should NOT be called directly.</p>
- */
-public class VariableCollectorVisitor extends LanguageVisitor {
-
-    private Collection variables;
-
-    /**
-     * Construct a new visitor with the specified collection, which should
-     * be non-null.
-     * @param variables Collection to use for variables
-     * @throws IllegalArgumentException If elements is null
-     */
-    public VariableCollectorVisitor(Collection variables) {
-        if(variables == null) {
-            throw new IllegalArgumentException(QueryPlugin.Util.getString(ErrorMessageKeys.SQL_0028));
-        }
-        this.variables = variables;
-    }
-
-
-    /**
-     * Get the variables collected by the visitor.  This should best be called
-     * after the visitor has been run on the language object tree.
-     * @return Collection of {@link com.metamatrix.query.sql.symbol.ElementSymbol}
-     */
-    public Collection getVariables() {
-        return this.variables;
-    }
-
-    /**
-     * Visit a language object and collect symbols.  This method should <b>NOT</b> be
-     * called directly.
-     * @param obj Language object
-     */
-    public void visit(ElementSymbol obj) {
-        if(obj.isExternalReference()) {
-            this.variables.add(obj);
-        }
-    }
-
-    /**
-     * Helper to quickly get the variables from obj in the variables collection
-     * @param obj Language object
-     * @param variables Collection to collect variables in
-     */
-    public static final void getVariables(LanguageObject obj, Collection variables) {
-        VariableCollectorVisitor visitor = new VariableCollectorVisitor(variables);
-        PreOrderNavigator.doVisit(obj, visitor);
-    }
-
-    /**
-     * Helper to quickly get the variables from obj in a collection.  The
-     * removeDuplicates flag affects whether duplicate variables will be
-     * filtered out.
-     * @param obj Language object
-     * @param removeDuplicates True to remove duplicates
-     * @return Collection of {@link com.metamatrix.query.sql.symbol.ElementSymbol}
-     */
-    public static final Collection getVariables(LanguageObject obj, boolean removeDuplicates) {
-        Collection variables = null;
-        if(removeDuplicates) {
-            variables = new HashSet();
-        } else {
-            variables = new ArrayList();
-        }
-        VariableCollectorVisitor visitor = new VariableCollectorVisitor(variables);
-        PreOrderNavigator.doVisit(obj, visitor);
-        return variables;
-    }
-
-}

Modified: trunk/engine/src/main/java/com/metamatrix/query/validator/ValidationVisitor.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/validator/ValidationVisitor.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/main/java/com/metamatrix/query/validator/ValidationVisitor.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -98,7 +98,7 @@
 import com.metamatrix.query.sql.visitor.AggregateSymbolCollectorVisitor;
 import com.metamatrix.query.sql.visitor.CommandCollectorVisitor;
 import com.metamatrix.query.sql.visitor.ElementCollectorVisitor;
-import com.metamatrix.query.sql.visitor.EvaluateExpressionVisitor;
+import com.metamatrix.query.sql.visitor.EvaluatableVisitor;
 import com.metamatrix.query.sql.visitor.FunctionCollectorVisitor;
 import com.metamatrix.query.sql.visitor.GroupCollectorVisitor;
 import com.metamatrix.query.sql.visitor.PredicateCollectorVisitor;
@@ -775,7 +775,7 @@
                 Expression nextValue = (Expression) valIter.next();
                 ElementSymbol nextVar = (ElementSymbol) varIter.next();
 
-                if (EvaluateExpressionVisitor.isFullyEvaluatable(nextValue, true)) {
+                if (EvaluatableVisitor.isFullyEvaluatable(nextValue, true)) {
                     try {
                         // If nextValue is an expression, evaluate it before checking for null
                         Object evaluatedValue = Evaluator.evaluate(nextValue);
@@ -823,7 +823,7 @@
 			    // Check that right expression is a constant and is non-null
                 Expression value = entry.getValue();
                 
-                if (EvaluateExpressionVisitor.isFullyEvaluatable(value, true)) {
+                if (EvaluatableVisitor.isFullyEvaluatable(value, true)) {
                     try {
                         value = new Constant(Evaluator.evaluate(value));
                     } catch (ExpressionEvaluationException err) {
@@ -835,7 +835,7 @@
                     if(((Constant)value).isNull() && ! getMetadata().elementSupports(elementID.getMetadataID(), SupportConstants.Element.NULL)) {
                         handleValidationError(QueryPlugin.Util.getString(ErrorMessageKeys.VALIDATOR_0060, SQLStringVisitor.getSQLString(elementID)), elementID);
                     }// end of if
-                } else if (!EvaluateExpressionVisitor.willBecomeConstant(value)) {
+                } else if (!EvaluatableVisitor.willBecomeConstant(value)) {
                     // If this is an update on a virtual group, verify that no elements are in the right side
                     GroupSymbol group = update.getGroup();
                     if(getMetadata().isVirtualGroup(group.getMetadataID())) {

Modified: trunk/engine/src/main/java/com/metamatrix/query/xquery/XQueryExpression.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/xquery/XQueryExpression.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/main/java/com/metamatrix/query/xquery/XQueryExpression.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -23,7 +23,6 @@
 package com.metamatrix.query.xquery;
 
 import java.sql.SQLXML;
-import java.util.Map;
 
 import com.metamatrix.api.exception.MetaMatrixComponentException;
 import com.metamatrix.api.exception.MetaMatrixProcessingException;
@@ -70,13 +69,4 @@
      */
     public void setXMLFormat(String xmlFormat);  
     
-    /**
-     * Set external parameter values.  These much match up to declared external variables
-     * in the xquery expression itself.  For example, xml literal inputs need to be declared
-     * like this in the prolog:
-     *    declare variable $input as node() external;
-     * @param params Map of parameter name -> value
-     */
-    public void setParameters(Map params);
-        
 }

Modified: trunk/engine/src/main/java/com/metamatrix/query/xquery/XQuerySQLEvaluator.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/xquery/XQuerySQLEvaluator.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/main/java/com/metamatrix/query/xquery/XQuerySQLEvaluator.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -26,7 +26,9 @@
 
 import com.metamatrix.api.exception.MetaMatrixComponentException;
 import com.metamatrix.api.exception.MetaMatrixProcessingException;
+import com.metamatrix.api.exception.query.ExpressionEvaluationException;
 import com.metamatrix.api.exception.query.QueryParserException;
+import com.metamatrix.common.buffer.BlockedException;
 
 
 /** 
@@ -47,4 +49,6 @@
      * Closes any resources opened during the evaluation 
      */
     void close() throws MetaMatrixComponentException ;
+
+	Object getParameterValue(String key) throws ExpressionEvaluationException, BlockedException, MetaMatrixComponentException;
 }

Modified: trunk/engine/src/main/java/com/metamatrix/query/xquery/saxon/SaxonXQueryExpression.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/xquery/saxon/SaxonXQueryExpression.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/main/java/com/metamatrix/query/xquery/saxon/SaxonXQueryExpression.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -66,8 +66,7 @@
     private net.sf.saxon.query.XQueryExpression xQuery;    
     private Map virtualDocuments;
     private String xmlFormat;
-    private Map params; // map of param name to value
-    private Map paramDeclarations;
+    private Map<String, String> paramDeclarations;
 
     // Create a default error listener to use when compiling - this prevents 
     // errors from being printed to System.err.
@@ -108,7 +107,7 @@
      * 
      */
     private void parseParameters() {
-        this.paramDeclarations = new HashMap();
+        this.paramDeclarations = new HashMap<String, String>();
         
         Matcher matcher = EXTERNAL_VARIABLE_PATTERN.matcher(xQueryString);
         while(matcher.find()) {
@@ -131,41 +130,19 @@
         dynamicContext.setURIResolver(new DocFunctionURIResolver(this.virtualDocuments, sqlEval));
         
         // Set external parameter values (if used in a view with params)
-        if(this.params != null && this.params.size() > 0) {
-            Iterator paramIter = params.entrySet().iterator();
-            while(paramIter.hasNext()) {
-                Map.Entry entry = (Map.Entry) paramIter.next();
-                String paramName = (String)entry.getKey();
-                paramName = StringUtil.getLastToken(paramName, "."); //$NON-NLS-1$
-                
-                Expression expr = (Expression)entry.getValue();
-                Object value = Evaluator.evaluate(expr);
-                
-                if(! paramDeclarations.containsKey(paramName)) {
-                    // Look for a different case match
-                    Iterator declIter = this.paramDeclarations.keySet().iterator();
-                    while(declIter.hasNext()) {
-                        String paramDecl = (String) declIter.next();
-                        if(paramName.equalsIgnoreCase(paramDecl)) {
-                            paramName = paramDecl;
-                            break;
-                        }
-                    }
+        for (Map.Entry<String, String> entry : this.paramDeclarations.entrySet()) {
+        	Object value = sqlEval.getParameterValue(entry.getKey());
+            // Check for xml and serialize
+            String type = entry.getValue();
+            if(type != null && type.equals("node()") && value != null) { //$NON-NLS-1$                    
+                try {
+                    value = ((SQLXML)value).getSource(null);
+                } catch (SQLException e) {
+                    throw new MetaMatrixProcessingException(e);
                 }
-                
-                // Check for xml and serialize
-                String type = (String) paramDeclarations.get(paramName);
-                if(type != null && type.equals("node()") && value != null) { //$NON-NLS-1$                    
-                    try {
-                        value = ((SQLXML)value).getSource(null);
-                    } catch (SQLException e) {
-                        throw new MetaMatrixProcessingException(e);
-                    }
-                }
-                
-                dynamicContext.setParameter(paramName, value);                
             }
-        }
+            dynamicContext.setParameter(entry.getKey(), value);                
+		}
         
         // Evaluate
         List rawResults = null;
@@ -218,11 +195,4 @@
         this.xmlFormat = xmlFormat;
     }
     
-    /** 
-     * @see com.metamatrix.query.xquery.XQueryExpression#setParameters(java.util.Map)
-     * @since 4.3
-     */
-    public void setParameters(Map params) {
-        this.params = params;
-    }        
 }

Modified: trunk/engine/src/test/java/com/metamatrix/query/processor/dynamic/TestSqlEval.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/processor/dynamic/TestSqlEval.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/test/java/com/metamatrix/query/processor/dynamic/TestSqlEval.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -23,6 +23,7 @@
 package com.metamatrix.query.processor.dynamic;
 
 import java.io.BufferedReader;
+import java.util.Collections;
 
 import javax.xml.transform.Source;
 import javax.xml.transform.sax.SAXSource;
@@ -68,7 +69,7 @@
         CommandContext cc = TestProcessor.createCommandContext();
         cc.setQueryProcessorFactory(factory);
         
-        SqlEval sqlEval = new SqlEval(bufferMgr, cc, null);
+        SqlEval sqlEval = new SqlEval(bufferMgr, null, cc, null, Collections.EMPTY_MAP);
         Source results =  sqlEval.executeSQL(sql);        
         String result = toXMLString(results);
         sqlEval.close();

Modified: trunk/engine/src/test/java/com/metamatrix/query/processor/eval/TestExpressionEvaluator.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/processor/eval/TestExpressionEvaluator.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/test/java/com/metamatrix/query/processor/eval/TestExpressionEvaluator.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -42,14 +42,11 @@
 import com.metamatrix.query.function.FunctionLibraryManager;
 import com.metamatrix.query.processor.FakeDataManager;
 import com.metamatrix.query.processor.ProcessorDataManager;
-import com.metamatrix.query.sql.ReservedWords;
 import com.metamatrix.query.sql.lang.CollectionValueIterator;
 import com.metamatrix.query.sql.lang.Query;
 import com.metamatrix.query.sql.lang.SubqueryContainer;
-import com.metamatrix.query.sql.symbol.AggregateSymbol;
 import com.metamatrix.query.sql.symbol.CaseExpression;
 import com.metamatrix.query.sql.symbol.Constant;
-import com.metamatrix.query.sql.symbol.ContextReference;
 import com.metamatrix.query.sql.symbol.ElementSymbol;
 import com.metamatrix.query.sql.symbol.Expression;
 import com.metamatrix.query.sql.symbol.Function;
@@ -59,7 +56,6 @@
 import com.metamatrix.query.sql.symbol.TestCaseExpression;
 import com.metamatrix.query.sql.symbol.TestSearchedCaseExpression;
 import com.metamatrix.query.sql.util.ValueIterator;
-import com.metamatrix.query.sql.visitor.EvaluateExpressionVisitor;
 import com.metamatrix.query.util.CommandContext;
 
 /**
@@ -415,18 +411,4 @@
         }
     }    
     
-    //tests that the visitor is safe to use against a null expression in the aggregate symbol
-    public void testCountStar() throws Exception {
-    	ElementSymbol x = new ElementSymbol("x"); //$NON-NLS-1$
-        ElementSymbol y = new ElementSymbol("y"); //$NON-NLS-1$
-        
-        HashMap map = new HashMap();
-        map.put(x, y);
-        
-    	AggregateSymbol countStar = new AggregateSymbol("agg1", ReservedWords.COUNT, false, null); //$NON-NLS-1$ //$NON-NLS-2$
-    	AggregateSymbol countStar1 = new AggregateSymbol("agg1", ReservedWords.COUNT, false, null); //$NON-NLS-1$ //$NON-NLS-2$
-    	EvaluateExpressionVisitor.replaceExpressions(countStar, true, null, null);
-    	
-    	assertEquals(countStar1, countStar);
-    }
 }

Modified: trunk/engine/src/test/java/com/metamatrix/query/processor/proc/TestProcedureProcessor.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/processor/proc/TestProcedureProcessor.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/test/java/com/metamatrix/query/processor/proc/TestProcedureProcessor.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -22,6 +22,8 @@
 
 package com.metamatrix.query.processor.proc;
 
+import static org.junit.Assert.*;
+
 import java.sql.SQLException;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -31,7 +33,7 @@
 import java.util.List;
 import java.util.Map;
 
-import junit.framework.TestCase;
+import org.junit.Test;
 
 import com.metamatrix.api.exception.MetaMatrixComponentException;
 import com.metamatrix.api.exception.MetaMatrixException;
@@ -54,11 +56,8 @@
 import com.metamatrix.query.metadata.TempMetadataID;
 import com.metamatrix.query.optimizer.QueryOptimizer;
 import com.metamatrix.query.optimizer.TestOptimizer;
-import com.metamatrix.query.optimizer.capabilities.AllCapabilities;
 import com.metamatrix.query.optimizer.capabilities.CapabilitiesFinder;
 import com.metamatrix.query.optimizer.capabilities.DefaultCapabilitiesFinder;
-import com.metamatrix.query.optimizer.capabilities.FakeCapabilitiesFinder;
-import com.metamatrix.query.optimizer.capabilities.SourceCapabilities;
 import com.metamatrix.query.parser.QueryParser;
 import com.metamatrix.query.processor.FakeDataManager;
 import com.metamatrix.query.processor.ProcessorDataManager;
@@ -81,11 +80,7 @@
 import com.metamatrix.query.validator.ValidatorFailure;
 import com.metamatrix.query.validator.ValidatorReport;
 
-public class TestProcedureProcessor extends TestCase {
-
-    public TestProcedureProcessor(String name) {
-        super(name);
-    }
+public class TestProcedureProcessor {
 	
     public static ProcessorPlan getProcedurePlan(String userQuery, FakeMetadataFacade metadata) throws Exception {
     	return getProcedurePlan(userQuery, metadata, /*capabilitiesFinder*/null);
@@ -342,7 +337,7 @@
     }    
     
 	// procedure does nothing returns zero update count	
-    public void testProcedureProcessor1() throws Exception {
+    @Test public void testProcedureProcessor1() throws Exception {
         String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
         procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
         procedure = procedure + "DECLARE integer var1 = 0;\n"; //$NON-NLS-1$
@@ -361,7 +356,7 @@
     }
 
 	// testing if statement    
-    public void testProcedureProcessor2() throws Exception {
+    @Test public void testProcedureProcessor2() throws Exception {
         String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
         procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
         procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
@@ -384,7 +379,7 @@
     }
     
     // testing if statement    
-    public void testProcedureProcessor2WithBlockedException() throws Exception  {
+    @Test public void testProcedureProcessor2WithBlockedException() throws Exception  {
         String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
         procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
         procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
@@ -408,7 +403,7 @@
     }
 
 	// testing rows updated incremented, Input and assignment statements
-    public void testProcedureProcessor3() throws Exception {
+    @Test public void testProcedureProcessor3() throws Exception {
         String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
         procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
         procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
@@ -429,7 +424,7 @@
     }
     
     // if/else test
-    public void testProcedureProcessor4() throws Exception {
+    @Test public void testProcedureProcessor4() throws Exception {
         String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
         procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
         procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
@@ -458,7 +453,7 @@
 		helpTestProcess(plan, 5, dataMgr);									 
     }
     
-    public void testProcedureProcessor4WithBlockedException() throws Exception {
+    @Test public void testProcedureProcessor4WithBlockedException() throws Exception {
         String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
         procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
         procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
@@ -489,7 +484,7 @@
     }
 
     // if/else test    
-    public void testProcedureProcessor5() throws Exception {
+    @Test public void testProcedureProcessor5() throws Exception {
         String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
         procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
         procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
@@ -516,7 +511,7 @@
     }
     
     // more rows than expected
-    public void testProcedureProcessor6() throws Exception {
+    @Test public void testProcedureProcessor6() throws Exception {
         String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
         procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
         procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
@@ -534,22 +529,22 @@
     }
 
     // error statement
-    public void testProcedureProcessor7() throws Exception {
+    @Test public void testProcedureProcessor7() throws Exception {
         String errorValue = "\"MY ERROR\""; //$NON-NLS-1$
         helpTestErrorStatment(errorValue, "MY ERROR"); //$NON-NLS-1$
     }
     
-    public void testProcedureProcessor8() throws Exception {
+    @Test public void testProcedureProcessor8() throws Exception {
         String errorValue = "var1"; //$NON-NLS-1$
         helpTestErrorStatment(errorValue, "5"); //$NON-NLS-1$
     }
     
-    public void testProcedureProcessor9() throws Exception {
+    @Test public void testProcedureProcessor9() throws Exception {
         String errorValue = "var1||\"MY ERROR\""; //$NON-NLS-1$
         helpTestErrorStatment(errorValue, "5MY ERROR"); //$NON-NLS-1$
     }
         
-    public void testProcedureProcessor10() throws Exception {
+    @Test public void testProcedureProcessor10() throws Exception {
         String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
         procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
         procedure = procedure + "loop on (Select pm1.g1.e2 from pm1.g1 where e2 = 5) as mycursor\n"; //$NON-NLS-1$
@@ -591,7 +586,7 @@
     }
     
 	/** test if statement's if block with lookup in if condition */
-	public void testLookupFunction1() throws Exception {     
+	@Test public void testLookupFunction1() throws Exception {     
 		String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
 		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
 		procedure = procedure + "DECLARE integer var2;\n"; //$NON-NLS-1$
@@ -622,7 +617,7 @@
 	}
 	
 	/** test if statement's else block with lookup in if condition */
-	public void testLookupFunction2() throws Exception {     
+	@Test public void testLookupFunction2() throws Exception {     
 		String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
 		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
 		procedure = procedure + "DECLARE integer var2;\n"; //$NON-NLS-1$
@@ -651,7 +646,7 @@
 		helpTestProcess(plan, 12, dataMgr);        
 	}
 
-    public void testVirtualProcedure() throws Exception {
+    @Test public void testVirtualProcedure() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp2()"; //$NON-NLS-1$
     
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
@@ -668,7 +663,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testVirtualProcedureWithBlockedException() throws Exception {
+    @Test public void testVirtualProcedureWithBlockedException() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp2()"; //$NON-NLS-1$
     
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
@@ -686,7 +681,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testVirtualProcedure2() throws Exception {
+    @Test public void testVirtualProcedure2() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp3()"; //$NON-NLS-1$
     
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
@@ -701,7 +696,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testVirtualProcedure3() throws Exception {
+    @Test public void testVirtualProcedure3() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp4()"; //$NON-NLS-1$
     
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
@@ -716,7 +711,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
         
-    public void testVirtualProcedure4() throws Exception {
+    @Test public void testVirtualProcedure4() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp5()"; //$NON-NLS-1$
     
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
@@ -731,7 +726,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testVirtualProcedure5() throws Exception {
+    @Test public void testVirtualProcedure5() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp6()"; //$NON-NLS-1$
     
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
@@ -746,7 +741,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
        
-    public void testVirtualProcedure6() throws Exception {
+    @Test public void testVirtualProcedure6() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp7(5)"; //$NON-NLS-1$
     
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
@@ -761,7 +756,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
           
-    public void testVirtualProcedure7() throws Exception {
+    @Test public void testVirtualProcedure7() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp8(51)"; //$NON-NLS-1$
     
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
@@ -776,7 +771,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
               
-    public void testVirtualProcedure8() throws Exception {
+    @Test public void testVirtualProcedure8() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp9(51)"; //$NON-NLS-1$
     
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
@@ -791,7 +786,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
              
-    public void testVirtualProcedure9() throws Exception {
+    @Test public void testVirtualProcedure9() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp10(51)"; //$NON-NLS-1$
     
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
@@ -806,7 +801,7 @@
     }
 
               
-    public void testVirtualProcedure10() throws Exception {
+    @Test public void testVirtualProcedure10() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp13()"; //$NON-NLS-1$
     
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
@@ -821,7 +816,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testVirtualProcedure11() throws Exception {
+    @Test public void testVirtualProcedure11() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp14()";     //$NON-NLS-1$
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
         // Set up data
@@ -839,7 +834,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testVirtualProcedure12() throws Exception {
+    @Test public void testVirtualProcedure12() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp15()";     //$NON-NLS-1$
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
         // Set up data
@@ -870,7 +865,7 @@
     }
     
     //Defect17447_testVirtualProcedure13
-    public void testVirtualProcedure13() throws Exception {
+    @Test public void testVirtualProcedure13() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp16()";     //$NON-NLS-1$
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
 
@@ -901,7 +896,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     		
-    public void testVirtualProcedure14() throws Exception {
+    @Test public void testVirtualProcedure14() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp17()";     //$NON-NLS-1$
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
         // Set up data
@@ -958,7 +953,7 @@
         return plan;
     }
     
-    public void testVirtualProcedure15() throws Exception {
+    @Test public void testVirtualProcedure15() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp19()";     //$NON-NLS-1$
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
 
@@ -980,7 +975,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testVirtualProcedure16() throws Exception {
+    @Test public void testVirtualProcedure16() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp20()";     //$NON-NLS-1$
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
         // Set up data
@@ -998,7 +993,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testVirtualProcedure17() throws Exception {
+    @Test public void testVirtualProcedure17() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp21(7)";     //$NON-NLS-1$
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
         //Set up data
@@ -1017,7 +1012,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testVirtualProcedure18() throws Exception {
+    @Test public void testVirtualProcedure18() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp22(7)";     //$NON-NLS-1$
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
         //Set up data
@@ -1034,7 +1029,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testVirtualProcedure19() throws Exception {
+    @Test public void testVirtualProcedure19() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp23(7)";     //$NON-NLS-1$
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
         //Set up data
@@ -1050,7 +1045,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testVirtualProcedure19WithBlockedException() throws Exception {
+    @Test public void testVirtualProcedure19WithBlockedException() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp23(7)";     //$NON-NLS-1$
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
         //Set up data
@@ -1065,7 +1060,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
 
-    public void testVirtualProcedureNoDataInTempTable() throws Exception {
+    @Test public void testVirtualProcedureNoDataInTempTable() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp25()";     //$NON-NLS-1$
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
 
@@ -1082,7 +1077,7 @@
     }
     
     //procedure with Has Criteria and Translate Criteria 
-    public void testDefect13625() throws Exception {
+    @Test public void testDefect13625() throws Exception {
         String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
         procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
         procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
@@ -1107,7 +1102,7 @@
 		helpTestProcess(plan, 5, dataMgr);
     }
     
-    public void testVirtualProcedure30() throws Exception {
+    @Test public void testVirtualProcedure30() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp30()";     //$NON-NLS-1$
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
     
@@ -1124,7 +1119,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
 
-    public void testVirtualProcedure31() throws Exception {
+    @Test public void testVirtualProcedure31() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp31(51)";     //$NON-NLS-1$
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
         
@@ -1138,7 +1133,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
 
-    public void testVirtualProcedureDefect14282() throws Exception {
+    @Test public void testVirtualProcedureDefect14282() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp24()"; //$NON-NLS-1$
     
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
@@ -1153,7 +1148,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }    
     
-    public void testDefect16193() throws Exception {
+    @Test public void testDefect16193() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp35(51)";     //$NON-NLS-1$
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
@@ -1167,7 +1162,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testVirtualProcedure16602() throws Exception {
+    @Test public void testVirtualProcedure16602() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp37()";     //$NON-NLS-1$
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
@@ -1193,7 +1188,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testDefect16649_1() throws Exception {
+    @Test public void testDefect16649_1() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp38()";     //$NON-NLS-1$
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
@@ -1207,7 +1202,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testDefect16649_2() throws Exception {
+    @Test public void testDefect16649_2() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp39()";     //$NON-NLS-1$
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
@@ -1221,7 +1216,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testDefect16694() throws Exception {
+    @Test public void testDefect16694() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp40()";     //$NON-NLS-1$
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
@@ -1235,7 +1230,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testDefect16707() throws Exception {
+    @Test public void testDefect16707() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp44(2)";     //$NON-NLS-1$
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
@@ -1251,7 +1246,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testDefect16707_1() throws Exception {
+    @Test public void testDefect16707_1() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp43(2)";     //$NON-NLS-1$
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
@@ -1267,7 +1262,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testDefect17451() throws Exception {
+    @Test public void testDefect17451() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp45()";     //$NON-NLS-1$
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
 
@@ -1299,7 +1294,7 @@
     }
     
     //Defect 17447
-    public void testVirtualProcedure46() throws Exception {
+    @Test public void testVirtualProcedure46() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp46()";     //$NON-NLS-1$
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
 
@@ -1330,7 +1325,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testDefect17650() throws Exception {
+    @Test public void testDefect17650() throws Exception {
         String procedure1 = "CREATE PROCEDURE  "; //$NON-NLS-1$
         procedure1 = procedure1 + "BEGIN\n"; //$NON-NLS-1$
         procedure1 = procedure1 + "DECLARE integer var1;\n"; //$NON-NLS-1$
@@ -1358,7 +1353,7 @@
         helpTestProcess(plan, 5, dataMgr);
     }
     
-    public void testDefect19982() throws Exception {
+    @Test public void testDefect19982() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp55(5)";     //$NON-NLS-1$
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
@@ -1374,7 +1369,7 @@
         helpTestProcess(plan, expected, dataMgr);
     } 
     
-    public void testCase3521() throws Exception {
+    @Test public void testCase3521() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp1()"; //$NON-NLS-1$
     
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
@@ -1393,7 +1388,7 @@
     }
 
     //procedure with Has Criteria and Translate Criteria and changing
-    public void testDynamicCommandWithTranslate() throws Exception {
+    @Test public void testDynamicCommandWithTranslate() throws Exception {
         String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
         procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
         procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
@@ -1419,7 +1414,7 @@
 		helpTestProcess(plan, 5, dataMgr);
     }
     
-    public void testDynamicCommandWithIntoExpression() throws Exception {
+    @Test public void testDynamicCommandWithIntoExpression() throws Exception {
     	
     	//Test INTO clause with expression
     	FakeMetadataFacade metadata = FakeMetadataFactory.example1();
@@ -1448,7 +1443,7 @@
         helpTestProcess(plan, expected, dataMgr);
       }
     
-    public void testDynamicCommandWithIntoAndLoop() throws Exception {
+    @Test public void testDynamicCommandWithIntoAndLoop() throws Exception {
     	
     	//Test INTO clause with loop
     	FakeMetadataFacade metadata = FakeMetadataFactory.example1();
@@ -1490,7 +1485,7 @@
         helpTestProcess(plan, expected, dataMgr);
       }
     
-    public void testDynamicCommandWithParameter() throws Exception {
+    @Test public void testDynamicCommandWithParameter() throws Exception {
         FakeMetadataFacade metadata = FakeMetadataFactory.example1();
         
         FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
@@ -1518,7 +1513,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testDynamicCommandWithUsing() throws Exception {
+    @Test public void testDynamicCommandWithUsing() throws Exception {
         FakeMetadataFacade metadata = FakeMetadataFactory.example1();
         
         FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
@@ -1546,7 +1541,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testDynamicCommandWithVariable() throws Exception {
+    @Test public void testDynamicCommandWithVariable() throws Exception {
         FakeMetadataFacade metadata = FakeMetadataFactory.example1();
         
         FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
@@ -1574,7 +1569,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
 
-    public void testDynamicCommandWithSingleSelect() throws Exception {
+    @Test public void testDynamicCommandWithSingleSelect() throws Exception {
     	//Test select of a single value in a DynamicCommand
         FakeMetadataFacade metadata = FakeMetadataFactory.example1();
         
@@ -1603,7 +1598,7 @@
 
     
     //converts e1 from integer to string, with a different name
-    public void testDynamicCommandTypeConversion() throws Exception {
+    @Test public void testDynamicCommandTypeConversion() throws Exception {
     	 FakeMetadataFacade metadata = FakeMetadataFactory.example1();
          
          FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
@@ -1631,7 +1626,7 @@
          helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testDynamicCommandRecursion() throws Exception {
+    @Test public void testDynamicCommandRecursion() throws Exception {
         FakeMetadataFacade metadata = FakeMetadataFactory.example1();
 
         FakeMetadataObject pm1 = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
@@ -1662,7 +1657,7 @@
                                "Couldn't execute the dynamic SQL command \"EXECUTE STRING 'EXEC pm1.sq2(''First'')' AS e1 string, e2 integer\" with the SQL statement \"'EXEC pm1.sq2(''First'')'\" due to: There is a recursive invocation of group 'PM1.SQ2'. Please correct the SQL."); //$NON-NLS-1$
     }
     
-    public void testDynamicCommandIncorrectProjectSymbolCount() throws Exception {
+    @Test public void testDynamicCommandIncorrectProjectSymbolCount() throws Exception {
     	//Tests dynamic query with incorrect number of elements   
         FakeMetadataFacade metadata = FakeMetadataFactory.example1();
         
@@ -1692,7 +1687,7 @@
         helpTestProcessFailure(false, plan, dataMgr, "Couldn't execute the dynamic SQL command \"EXECUTE STRING 'EXEC pm1.sq1(''First'')' AS e1 string, e2 integer\" with the SQL statement \"'EXEC pm1.sq1(''First'')'\" due to: The dynamic sql string contains an incorrect number of elements."); //$NON-NLS-1$
      }
     
-    public void testDynamicCommandIncorrectProjectSymbolNames() throws Exception {
+    @Test public void testDynamicCommandIncorrectProjectSymbolNames() throws Exception {
     	//Tests dynamic query with incorrect number of elements   
         FakeMetadataFacade metadata = FakeMetadataFactory.example1();
         
@@ -1717,7 +1712,7 @@
         helpTestProcessFailure(false, plan, dataMgr, "Couldn't execute the dynamic SQL command \"EXECUTE STRING 'select e1 as x, e2 from pm1.g1'\" with the SQL statement \"'select e1 as x, e2 from pm1.g1'\" due to: No match found for expected symbol 'E1' in the dynamic SQL."); //$NON-NLS-1$
      }
     
-    public void testDynamicCommandIncorrectProjectSymbolDatatypes() throws Exception {
+    @Test public void testDynamicCommandIncorrectProjectSymbolDatatypes() throws Exception {
     	//Tests dynamic query with a different datatype definition for an element in the AS clause that
     	//has no implicit conversion. 
         FakeMetadataFacade metadata = FakeMetadataFactory.example1();
@@ -1742,7 +1737,7 @@
         helpTestProcessFailure(false, plan, dataMgr, "Couldn't execute the dynamic SQL command \"EXECUTE STRING 'select e1 from pm1.g1'\" with the SQL statement \"'select e1 from pm1.g1'\" due to: The datatype 'string' for element 'E1' in the dynamic SQL cannot be implicitly converted to 'integer'."); //$NON-NLS-1$
      }
  
-    public void testDynamicCommandInvalidModelUpdateCountEqualOne() throws Exception {
+    @Test public void testDynamicCommandInvalidModelUpdateCountEqualOne() throws Exception {
     	//Test invalid update model count
     	//Set update model count to 1 while actual is 2   
         FakeMetadataFacade metadata = FakeMetadataFactory.example1();
@@ -1773,7 +1768,7 @@
         helpTestProcessFailure(true, plan, dataMgr, "Couldn't execute the dynamic SQL command \"EXECUTE STRING 'EXEC pm1.sq1(''First'')' AS e1 string UPDATE 1\" with the SQL statement \"'EXEC pm1.sq1(''First'')'\" due to: The actual model update count '2' is greater than the expected value of '1'.  This is potentially unsafe in OPTIMISTIC transaction mode.  Please adjust the UPDATE clause of the dynamic SQL statement."); //$NON-NLS-1$ 
       }
     
-    public void testDynamicCommandWithTwoDynamicStatements() throws Exception {
+    @Test public void testDynamicCommandWithTwoDynamicStatements() throws Exception {
     	//Tests dynamic query with two consecutive DynamicCommands. The first without an AS clause and returning different results. 
         FakeMetadataFacade metadata = FakeMetadataFactory.example1();
         
@@ -1803,7 +1798,7 @@
         helpTestProcess(plan, expected, dataMgr);
      }
     
-    public void testAssignmentWithCase() throws Exception {
+    @Test public void testAssignmentWithCase() throws Exception {
         FakeMetadataFacade metadata = FakeMetadataFactory.example1();
         
         String sql = new StringBuffer("declare integer caseValue = ") //$NON-NLS-1$
@@ -1840,7 +1835,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testDynamicCommandInsertIntoTempTableWithDifferentDatatypeFromSource() throws Exception {
+    @Test public void testDynamicCommandInsertIntoTempTableWithDifferentDatatypeFromSource() throws Exception {
     	//Tests dynamic query with insert into a temp table using data returned from a physical table.
     	//See defect 23394  
         FakeMetadataFacade metadata = FakeMetadataFactory.example1();
@@ -1870,7 +1865,7 @@
         helpTestProcess(plan, expected, dataMgr);
      }
     
-    public void testDynamicCommandWithVariableOnly() throws Exception {
+    @Test public void testDynamicCommandWithVariableOnly() throws Exception {
     	//Tests dynamic query with only a variable that represents thte entire dynamic query.
         FakeMetadataFacade metadata = FakeMetadataFactory.example1();
         
@@ -1897,7 +1892,7 @@
         helpTestProcess(plan, expected, dataMgr);
      }
     
-    public void testVirtualProcedureWithCreate() throws Exception{
+    @Test public void testVirtualProcedureWithCreate() throws Exception{
         String userUpdateStr = "EXEC pm1.vsp60()"; //$NON-NLS-1$
         
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
@@ -1914,7 +1909,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testVirtualProcedureWithCreateAndDrop() throws Exception{
+    @Test public void testVirtualProcedureWithCreateAndDrop() throws Exception{
         String userUpdateStr = "EXEC pm1.vsp61()"; //$NON-NLS-1$
         
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
@@ -1931,7 +1926,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testVirtualProcedureWithCreateAndSelectInto() throws Exception{
+    @Test public void testVirtualProcedureWithCreateAndSelectInto() throws Exception{
         String userUpdateStr = "EXEC pm1.vsp62()"; //$NON-NLS-1$
         
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
@@ -1948,7 +1943,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testDifferentlyScopedTempTables() throws Exception {
+    @Test public void testDifferentlyScopedTempTables() throws Exception {
         
         FakeMetadataFacade metadata = FakeMetadataFactory.example1();
         
@@ -1991,7 +1986,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testLoopsWithBreak() throws Exception {
+    @Test public void testLoopsWithBreak() throws Exception {
         
         FakeMetadataFacade metadata = FakeMetadataFactory.example1();
         
@@ -2033,7 +2028,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testCreateWithoutDrop() throws Exception {
+    @Test public void testCreateWithoutDrop() throws Exception {
         
         FakeMetadataFacade metadata = FakeMetadataFactory.example1();
         
@@ -2066,7 +2061,7 @@
     /**
      *  We allow drops to silently fail
      */
-    public void testDoubleDrop() throws Exception {
+    @Test public void testDoubleDrop() throws Exception {
         
         FakeMetadataFacade metadata = FakeMetadataFactory.example1();
         
@@ -2101,7 +2096,7 @@
     /**
      * defect 23975 
      */
-    public void testFunctionInput() throws Exception {
+    @Test public void testFunctionInput() throws Exception {
         FakeMetadataObject v1 = FakeMetadataFactory.createVirtualModel("v1"); //$NON-NLS-1$
 
         FakeMetadataObject p1 = FakeMetadataFactory.createParameter("v1.vp1.in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
@@ -2142,7 +2137,7 @@
      * Also, even after the bug for passing procedure inputs to non-execs was fixed, the special case of
      * if (below) and while statements popped up.  
      */
-    public void testIfEvaluation() throws Exception {
+    @Test public void testIfEvaluation() throws Exception {
         String procedure1 = "CREATE PROCEDURE  "; //$NON-NLS-1$
         procedure1 += "BEGIN\n"; //$NON-NLS-1$
         procedure1 += "DECLARE string var1 = INPUT.e1;\n"; //$NON-NLS-1$
@@ -2171,7 +2166,7 @@
      *  This is a slight variation of TestProcessor.testVariableInExecParam, where the proc wrapper can be 
      *  removed after rewrite
      */
-    public void testReferenceForwarding() throws Exception { 
+    @Test public void testReferenceForwarding() throws Exception { 
         // Create query 
         String sql = "EXEC pm1.vsp49()"; //$NON-NLS-1$
         
@@ -2205,7 +2200,7 @@
         helpTestProcess(plan, expected, dataManager);
     }
     
-    public void testInsertAfterCreate() throws Exception {
+    @Test public void testInsertAfterCreate() throws Exception {
         FakeMetadataFacade metadata = FakeMetadataFactory.example1();
         
         FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
@@ -2241,7 +2236,7 @@
     /**
      * the update will not be executed, but the assignment value should still be 0
      */
-    public void testUpdateAssignmentNotExecuted() throws Exception {
+    @Test public void testUpdateAssignmentNotExecuted() throws Exception {
         String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
         procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
         procedure = procedure + "DECLARE integer var1 = UPDATE pm1.g1 SET pm1.g1.e1 = INPUT.e2;"; //$NON-NLS-1$
@@ -2259,7 +2254,7 @@
         helpTestProcess(plan, 1, dataMgr);
     }
     
-    public void testUpdateAssignmentNotExecutedVirtual() throws Exception {
+    @Test public void testUpdateAssignmentNotExecutedVirtual() throws Exception {
         String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
         procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
         procedure = procedure + "DECLARE integer var1 = UPDATE vm1.g2 SET e1 = INPUT.e2;"; //$NON-NLS-1$
@@ -2286,7 +2281,7 @@
         helpTestProcess(plan, 1, dataMgr);
     }
     
-    public void testEvaluatableSelectWithOrderBy() throws Exception {
+    @Test public void testEvaluatableSelectWithOrderBy() throws Exception {
         FakeMetadataFacade metadata = FakeMetadataFactory.example1();
         
         FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
@@ -2316,7 +2311,7 @@
         
     }
     
-    public void testEvaluatableSelectWithOrderBy1() throws Exception {
+    @Test public void testEvaluatableSelectWithOrderBy1() throws Exception {
         FakeMetadataFacade metadata = FakeMetadataFactory.example1();
         
         FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
@@ -2356,7 +2351,7 @@
      * 
      * If this function were deterministic, it would be evaluated during rewrite to a single value.
      */
-    public void testNonDeterministicEvaluation() throws Exception {
+    @Test public void testNonDeterministicEvaluation() throws Exception {
         StringBuffer procedure = new StringBuffer("CREATE VIRTUAL PROCEDURE \n") //$NON-NLS-1$
         .append("BEGIN\n") //$NON-NLS-1$
         .append("DECLARE integer x = 0;\n") //$NON-NLS-1$
@@ -2399,7 +2394,7 @@
         return metadata;
     }
     
-    public void testTempTableTypeConversion() throws Exception {
+    @Test public void testTempTableTypeConversion() throws Exception {
         
         String procedure = "CREATE VIRTUAL PROCEDURE\n"; //$NON-NLS-1$
         procedure += "BEGIN\n";       //$NON-NLS-1$
@@ -2426,7 +2421,7 @@
      * 
      * Now it will not and the rewriter should remove empty loops, where this was happening
      */
-    public void testGetChildPlans() {
+    @Test public void testGetChildPlans() {
         Program program = new Program();
         assertEquals(Collections.EMPTY_LIST, program.getChildPlans());
     }
@@ -2434,7 +2429,7 @@
     /**
      * wraps {@link TestXMLPlanningEnhancements.testNested2WithContextCriteria5d1} in a procedure
      */
-    public void testXMLWithExternalCriteria() throws Exception {
+    @Test public void testXMLWithExternalCriteria() throws Exception {
         FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
         FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
         String resultFile = "TestXMLProcessor-testNested2WithContextCriteria5d.xml"; //$NON-NLS-1$
@@ -2463,7 +2458,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testXMLWithExternalCriteria_InXMLVar() throws Exception {
+    @Test public void testXMLWithExternalCriteria_InXMLVar() throws Exception {
         FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
         FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
         String resultFile = "TestXMLProcessor-testNested2WithContextCriteria5d.xml"; //$NON-NLS-1$
@@ -2497,7 +2492,7 @@
      * 
      * This one will successfully auto-stage
      */
-    public void testXMLWithExternalCriteria1() throws Exception {
+    @Test public void testXMLWithExternalCriteria1() throws Exception {
         FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
         FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
         String expectedDoc = 
@@ -2559,7 +2554,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testCase174806() throws Exception{
+    @Test public void testCase174806() throws Exception{
         String userUpdateStr = "EXEC pm1.vsp63()"; //$NON-NLS-1$
         
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
@@ -2574,7 +2569,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testJoinProcAndPhysicalModel() throws Exception {
+    @Test public void testJoinProcAndPhysicalModel() throws Exception {
         String userUpdateStr = "select a.e1 from (EXEC pm1.vsp46()) as a, pm1.g1 where a.e1=pm1.g1.e1";     //$NON-NLS-1$
         FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
 
@@ -2617,7 +2612,7 @@
      * assigned value in the <code>DECLARE</code> statement.</p> 
      * @throws Exception
      */
-    public void testDeclareWithQueryAssignment() throws Exception {
+    @Test public void testDeclareWithQueryAssignment() throws Exception {
     	// procedure comes from test case IT236455 / JBEDSP-818
         String procedure = "CREATE VIRTUAL PROCEDURE \n"; //$NON-NLS-1$
         procedure += "BEGIN\n"; //$NON-NLS-1$
@@ -2652,7 +2647,7 @@
         helpTestProcess(plan, expected, dataMgr);
     }
     
-    public void testDefect8693() throws Exception {
+    @Test public void testDefect8693() throws Exception {
         String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
         procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
         procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
@@ -2671,7 +2666,7 @@
 		helpTestProcess(plan, 5, dataMgr);									 
     }
     
-    public void testWhileWithSubquery() throws Exception {
+    @Test public void testWhileWithSubquery() throws Exception {
         String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
         procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
         procedure = procedure + "DECLARE integer var1 = 2;\n"; //$NON-NLS-1$
@@ -2689,7 +2684,7 @@
 		helpTestProcess(plan, 0, dataMgr);									 
     }
     
-    public void testDefect18404() throws Exception {
+    @Test public void testDefect18404() throws Exception {
         String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
         procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
         procedure = procedure + "DECLARE integer var1 = 5 + (select count(e2) from pm1.g1);\n"; //$NON-NLS-1$
@@ -2713,7 +2708,7 @@
      *  
      * @throws Exception
      */
-    public void testRemovalOfNonJoinCritWithReference() throws Exception {
+    @Test public void testRemovalOfNonJoinCritWithReference() throws Exception {
     	String proc = ""; //$NON-NLS-1$
     	
         String sql = ""; //$NON-NLS-1$
@@ -2757,7 +2752,7 @@
      *  
      * @throws Exception
      */
-    public void testRemovalOfNonJoinCritWithReference2() throws Exception {
+    @Test public void testRemovalOfNonJoinCritWithReference2() throws Exception {
     	String proc = ""; //$NON-NLS-1$
     	
         String sql = ""; //$NON-NLS-1$

Modified: trunk/engine/src/test/java/com/metamatrix/query/resolver/TestResolver.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/resolver/TestResolver.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/test/java/com/metamatrix/query/resolver/TestResolver.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -31,7 +31,6 @@
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.HashMap;
-import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
@@ -96,7 +95,6 @@
 import com.metamatrix.query.sql.visitor.FunctionCollectorVisitor;
 import com.metamatrix.query.sql.visitor.GroupCollectorVisitor;
 import com.metamatrix.query.sql.visitor.ReferenceCollectorVisitor;
-import com.metamatrix.query.sql.visitor.VariableCollectorVisitor;
 import com.metamatrix.query.unittest.FakeMetadataFacade;
 import com.metamatrix.query.unittest.FakeMetadataFactory;
 import com.metamatrix.query.unittest.FakeMetadataObject;
@@ -176,9 +174,7 @@
      */
     private Command helpResolveSubquery(String sql, String[] variableNames){
         Query query = (Query)helpResolve(sql);
-        Collection variables = new HashSet();
-        VariableCollectorVisitor visitor = new VariableCollectorVisitor(variables);
-        DeepPreOrderNavigator.doVisit(query, visitor);
+        Collection<ElementSymbol> variables = getVariables(query);
 
         assertTrue("Expected variables size " + variableNames.length + " but was " + variables.size(),  //$NON-NLS-1$ //$NON-NLS-2$
                    variables.size() == variableNames.length);
@@ -197,6 +193,17 @@
         
         return query;         
     }
+
+	public static Collection<ElementSymbol> getVariables(LanguageObject languageObject) {
+		Collection<ElementSymbol> variables = ElementCollectorVisitor.getElements(languageObject, false, true);
+    	for (Iterator<ElementSymbol> iterator = variables.iterator(); iterator.hasNext();) {
+			ElementSymbol elementSymbol = iterator.next();
+			if (!elementSymbol.isExternalReference()) {
+				iterator.remove();
+			}
+		}
+		return variables;
+	}
     
     public static Command helpResolve(String sql, QueryMetadataInterface queryMetadata, AnalysisRecord analysis){
         return helpResolve(helpParse(sql), queryMetadata, analysis);
@@ -1053,7 +1060,7 @@
 
         // Verify results        
         helpCheckFrom((Query)command, new String[] { "pm1.g1" });         //$NON-NLS-1$
-        Collection vars = VariableCollectorVisitor.getVariables(command, false);
+        Collection vars = getVariables(command);
         assertEquals("Did not find variable in resolved query", 1, vars.size()); //$NON-NLS-1$
     }
 
@@ -1073,7 +1080,7 @@
 
         // Verify results        
         helpCheckFrom((Query)command, new String[] { "pm1.g1" });         //$NON-NLS-1$
-        Collection vars = VariableCollectorVisitor.getVariables(command, false);
+        Collection vars = getVariables(command);
         assertEquals("Did not find variable in resolved query", 1, vars.size()); //$NON-NLS-1$
     }
 
@@ -1092,7 +1099,7 @@
         QueryResolver.resolveCommand(command, externalMetadata, false, metadata, AnalysisRecord.createNonRecordingRecord());
 
         // Verify results
-        Collection vars = VariableCollectorVisitor.getVariables(command, false);
+        Collection vars = getVariables(command);
         assertEquals("Did not find variable in resolved query", 1, vars.size()); //$NON-NLS-1$
     }
     

Modified: trunk/engine/src/test/java/com/metamatrix/query/resolver/TestXMLResolver.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/resolver/TestXMLResolver.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/test/java/com/metamatrix/query/resolver/TestXMLResolver.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -27,6 +27,8 @@
 import java.util.HashMap;
 import java.util.Map;
 
+import junit.framework.TestCase;
+
 import com.metamatrix.common.types.DataTypeManager;
 import com.metamatrix.query.analysis.AnalysisRecord;
 import com.metamatrix.query.parser.ParseInfo;
@@ -41,11 +43,8 @@
 import com.metamatrix.query.sql.symbol.Function;
 import com.metamatrix.query.sql.symbol.GroupSymbol;
 import com.metamatrix.query.sql.util.ElementSymbolOptimizer;
-import com.metamatrix.query.sql.visitor.VariableCollectorVisitor;
 import com.metamatrix.query.unittest.FakeMetadataFactory;
 
-import junit.framework.TestCase;
-
 public class TestXMLResolver extends TestCase {
     
     public Command helpResolve(String sql) {
@@ -403,7 +402,7 @@
         QueryResolver.resolveCommand(command, externalMetadata, false, FakeMetadataFactory.example1Cached(), AnalysisRecord.createNonRecordingRecord());
     
         // Verify results        
-        Collection vars = VariableCollectorVisitor.getVariables(command, false);
+        Collection vars = TestResolver.getVariables(command);
         assertEquals("Did not find variable in resolved query", 1, vars.size()); //$NON-NLS-1$
     }
       

Modified: trunk/engine/src/test/java/com/metamatrix/query/rewriter/TestQueryRewriter.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/rewriter/TestQueryRewriter.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/test/java/com/metamatrix/query/rewriter/TestQueryRewriter.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -1740,21 +1740,6 @@
         assertEquals("SELECT e1, e2 FROM pm1.g1 WHERE e1 = '1'", rewriteCommand.toString()); //$NON-NLS-1$
     }
 
-    @Test public void testRewriteExecCase6455() throws Exception {
-        Command command = QueryParser.getQueryParser().parseCommand("exec pm1.sq2(env('sessionid')) OPTION PLANONLY DEBUG");             //$NON-NLS-1$
-        
-        QueryResolver.resolveCommand(command, FakeMetadataFactory.example1Cached());
-        
-        CommandContext context = new CommandContext();
-        Properties props = new Properties();
-        props.setProperty(ContextProperties.SESSION_ID, "1"); //$NON-NLS-1$
-        context.setEnvironmentProperties(props);
-        Command rewriteCommand = QueryRewriter.rewrite(command, null, null, context);
-        
-        assertEquals("SELECT e1, e2 FROM pm1.g1 WHERE e1 = '1' OPTION PLANONLY DEBUG", rewriteCommand.toString()); //$NON-NLS-1$
-    }
-
-
     @Test public void testRewriteNestedFunctions() {
         helpTestRewriteCommand("SELECT e1 FROM pm1.g1 where convert(parsedate(e1, 'yyyy-MM-dd'), string) = '2006-07-01'", "SELECT e1 FROM pm1.g1 WHERE e1 = '2006-07-01'"); //$NON-NLS-1$ //$NON-NLS-2$
     }
@@ -1914,7 +1899,7 @@
     }
     
     @Test public void testRewriteXMLCriteriaCases5630And5640() {
-        helpTestRewriteCommand("select * from xmltest.doc1 where node1 = null", "SELECT * FROM xmltest.doc1 WHERE node1 = null"); //$NON-NLS-1$ //$NON-NLS-2$
+        helpTestRewriteCommand("select * from xmltest.doc1 where node1 = null", "SELECT * FROM xmltest.doc1 WHERE null <> null"); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
     @Test public void testRewriteCorrelatedSubqueryInHaving() {

Modified: trunk/engine/src/test/java/com/metamatrix/query/xquery/HardcodedSqlEval.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/xquery/HardcodedSqlEval.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/test/java/com/metamatrix/query/xquery/HardcodedSqlEval.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -23,13 +23,16 @@
 package com.metamatrix.query.xquery;
 
 import java.io.StringReader;
+import java.util.Map;
 
 import javax.xml.transform.Source;
 import javax.xml.transform.stream.StreamSource;
 
 import com.metamatrix.api.exception.MetaMatrixComponentException;
 import com.metamatrix.api.exception.MetaMatrixProcessingException;
+import com.metamatrix.api.exception.query.ExpressionEvaluationException;
 import com.metamatrix.api.exception.query.QueryParserException;
+import com.metamatrix.common.buffer.BlockedException;
 
 
 /** 
@@ -37,6 +40,7 @@
 public class HardcodedSqlEval implements XQuerySQLEvaluator {
 
     String result;
+    Map<String, Object> params;
     public HardcodedSqlEval(String result) {
         this.result = result;
     }
@@ -55,4 +59,11 @@
     public void close() throws MetaMatrixComponentException {
     }
 
+	@Override
+	public Object getParameterValue(String key)
+			throws ExpressionEvaluationException, BlockedException,
+			MetaMatrixComponentException {
+		return params.get(key);
+	}
+
 }

Modified: trunk/engine/src/test/java/com/metamatrix/query/xquery/TestXQueryEngine.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/xquery/TestXQueryEngine.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/test/java/com/metamatrix/query/xquery/TestXQueryEngine.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -37,7 +37,6 @@
 import com.metamatrix.common.types.SQLXMLImpl;
 import com.metamatrix.core.util.FileUtil;
 import com.metamatrix.core.util.UnitTestUtil;
-import com.metamatrix.query.sql.symbol.Constant;
 import com.metamatrix.query.xquery.saxon.SaxonXQueryExpression;
 
 /**
@@ -46,13 +45,6 @@
 public class TestXQueryEngine extends TestCase {
 
     /**
-     * constructor
-     */
-    public TestXQueryEngine() {
-        super();
-    }
-
-    /**
      * @param name
      */
     public TestXQueryEngine(String name) {
@@ -73,7 +65,7 @@
         assertEquals(expected.getString(), actualResults.getString());        
     }
 
-    private void helpTestEngineFails(String xQuery, Class expectedFailure, XQuerySQLEvaluator sqlEval) throws Exception{
+    private void helpTestEngineFails(String xQuery, Class<?> expectedFailure, XQuerySQLEvaluator sqlEval) throws Exception{
         XQueryExpression expr = new SaxonXQueryExpression();
         expr.compileXQuery(xQuery);
         
@@ -203,10 +195,10 @@
                         "<Name>Lamp</Name>" +   //$NON-NLS-1$
                         "</set>"; //$NON-NLS-1$                        
         XQueryExpression expr = new SaxonXQueryExpression();
-        HashMap params= new HashMap();
-        params.put("ItemID", new Constant("001")); //$NON-NLS-1$ //$NON-NLS-2$
-        expr.setParameters(params);
-        helpTestEngine(expr, xquery, new SQLXMLImpl(expected), new HardcodedSqlEval(inputdoc));        
+        HardcodedSqlEval eval = new HardcodedSqlEval(inputdoc);
+        eval.params = new HashMap<String, Object>();
+        eval.params.put("itemid", "001"); //$NON-NLS-1$ //$NON-NLS-2$
+        helpTestEngine(expr, xquery, new SQLXMLImpl(expected), eval);        
     }     
 
 }

Modified: trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatement.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatement.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatement.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -386,7 +386,7 @@
             Arrays.asList(1),
         };    
     
-		List values = Arrays.asList("aa "); //$NON-NLS-1$
+		List<String> values = Arrays.asList("aa "); //$NON-NLS-1$
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData2b(dataManager);
 		helpTestProcessing(preparedSql, values, expected, dataManager, FakeMetadataFactory.example1Cached(), false, false);
@@ -399,5 +399,31 @@
         FakeDataManager dataManager = new FakeDataManager();
 		helpTestProcessing(preparedSql, values, null, dataManager, FakeMetadataFactory.example1Cached(), false, false);
     }
+    
+    @Test public void testExecParam() throws Exception {
+        String preparedSql = "exec pm1.sq2(?)"; //$NON-NLS-1$
+        
+		List<String> values = Arrays.asList("c"); //$NON-NLS-1$
+        List[] expected = new List[] { 
+                Arrays.asList("c", 1),
+            };    
+        
+        FakeDataManager dataManager = new FakeDataManager();
+        TestProcessor.sampleData1(dataManager);
+		helpTestProcessing(preparedSql, values, expected, dataManager, FakeMetadataFactory.example1Cached(), false, false);
+    }
+    
+    @Test public void testXQueryParam() throws Exception {
+        String preparedSql = "exec m.xproc3(?)"; //$NON-NLS-1$
+        
+		List<String> values = Arrays.asList("<test1/>"); //$NON-NLS-1$
+        List[] expected = new List[] { 
+                Arrays.asList("<?xml version=\"1.0\" encoding=\"UTF-8\"?><wrap><test1/></wrap>"), //$NON-NLS-1$
+            };    
+        
+        FakeDataManager dataManager = new FakeDataManager();
+        TestProcessor.sampleData1(dataManager);
+		helpTestProcessing(preparedSql, values, expected, dataManager, FakeMetadataFactory.exampleXQueryTransformations(), false, false);
+    }
 
 }

Modified: trunk/metadata/src/main/java/org/teiid/connector/metadata/MetadataResultsPostProcessor.java
===================================================================
--- trunk/metadata/src/main/java/org/teiid/connector/metadata/MetadataResultsPostProcessor.java	2009-08-07 19:37:21 UTC (rev 1221)
+++ trunk/metadata/src/main/java/org/teiid/connector/metadata/MetadataResultsPostProcessor.java	2009-08-09 02:07:34 UTC (rev 1222)
@@ -140,22 +140,18 @@
      * @since 4.3
      */
     public ModelRecordImpl getModelRecordWithUpdatedVisibility(final ModelRecordImpl record) {
-        if(record instanceof ModelRecordImpl){
-            //set visibility
-            ModelRecordImpl mRecord = (ModelRecordImpl)record;
-            String modelName = mRecord.getName();   
-            if(!SystemVdbUtility.isSystemModelWithSystemTableType(modelName)){
-                int visibility = ModelInfo.PUBLIC;
-                if(this.vdbService != null) {
-                    try {
-                        visibility = vdbService.getModelVisibility(vdbName, vdbVersion, modelName);
-                    } catch (MetaMatrixComponentException e) {
-                        throw new MetaMatrixRuntimeException(e);
-                    }
+        String modelName = record.getName();   
+        if(!SystemVdbUtility.isSystemModelWithSystemTableType(modelName)){
+            int visibility = ModelInfo.PUBLIC;
+            if(this.vdbService != null) {
+                try {
+                    visibility = vdbService.getModelVisibility(vdbName, vdbVersion, modelName);
+                } catch (MetaMatrixComponentException e) {
+                    throw new MetaMatrixRuntimeException(e);
                 }
-                mRecord.setVisible(visibility == ModelInfo.PUBLIC);
-                return mRecord;
             }
+            record.setVisible(visibility == ModelInfo.PUBLIC);
+            return record;
         }
         return null;
     }



More information about the teiid-commits mailing list